How can I count all the black & white pixels from a circular mask passing through a binary image

1 view (last 30 days)
Hello everybody,
I'm working on a code that uses a circular mask and do a serie of things with it. One of the things I need to do is count all black and white pixels that are inside of this circular mask. I don't know why when I'll count the black pixels inside the mask, I count ALL the black pixels in the image, not only those are inside the mask, but when I do it for the white pixels, it works well.
clc;clear all; close all;
% Carrega imagem
image = imread('img.png');
% Binariza a imagem
level = graythresh(image);
imgBW = im2bw(image,level);
% Identifica as dimensões da imagem
sz = size(imgBW);
[columnsInImage rowsInImage] = meshgrid(1:sz(1), 1:sz(2));
% Cria a máscara circular na imagem
for i=3 % only 3 interations to test
for j=3
centerX = i;
centerY = j;
radius = 10;
X = columnsInImage - centerX;
Y = rowsInImage - centerY;
circlemask = (X).^2 + (Y).^2 <= (radius).^2;
circle_image = double(imgBW) .* circlemask;
angle = atan2(Y, X);
quadrant1 = circlemask & angle > -pi/2 & angle <= 0;
quadrant2 = circlemask & angle > -3*pi/2 & angle <= -pi/2;
quadrant3 = circlemask & angle > pi/2 & angle <= pi;
quadrant4 = circlemask & angle > 0 & angle <= pi/2;
quad1_image = double(imgBW) .* quadrant1;
quad2_image = double(imgBW) .* quadrant2;
quad3_image = double(imgBW) .* quadrant3;
quad4_image = double(imgBW) .* quadrant4;
ne = length(find(circle_image > 0)) % here I count all white pixels in the whole mask
*nw = length(find(circle_image == 0)) % here is the problem...*
de = ne/nw;
n(1) = length(find(quad1_image > 0));%here I count all white pixels in each quadrant an it works very well
n(2) = length(find(quad2_image > 0));
n(3) = length(find(quad3_image > 0));
n(4) = length(find(quad4_image > 0));
ds = min(n)/mean(n);
matriz_I(i+1,j+1) = de*ds ;
end
end
% Plots
subplot(2,4,1);imshow(image);title('Imagem original');
subplot(2,4,2);imshow(imgBW);title('Imagem binarizada');
subplot(2,4,3);imshow(circle_image, []);title('Máscara circular');
subplot(2,4,4);imshow(quad1_image, []);title('Primeiro quadrante');
subplot(2,4,5);imshow(quad2_image, []);title('Segundo quadrante');
subplot(2,4,6);imshow(quad3_image, []);title('Terceiro quadrante');
subplot(2,4,7);imshow(quad4_image, []);title('Quarto quadrante');
  1 Comment
Italo Wieczorek
Italo Wieczorek on 15 Apr 2015
PROBLEM SOLVED:
black_pixels = imgBW;
black_pixels(~circlemask) = 1;
ne = length(find(circle_image > 0))
nw = length(find(black_pixels == 0))
It turns all the black pixels outside the mask to 1, so you just have to count the black pixels inside the mask. Thanks anyway.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!