How to count black pixels in a region of an image that can only have 1 white neighbor pixel
11 ビュー (過去 30 日間)
古いコメントを表示
I have a binary image (black background and white pixels). How do i count the number of blackpixels witch in it's neighbourhood of 5*7 (5 lines and 7 colums) can only have a white pixel.
I can try using bwhitmiss() but i would need 35 matrixs with one white pixel in each "matrix slot".
Can you tell me an easyest way to achieve this?
0 件のコメント
採用された回答
Ashish Uthama
2012 年 4 月 6 日
You could try leveraging conv2.
Here is the idea:
in = [
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 ]
k = [
1 1 1
1 1 1
1 1 1]
r = conv2(in,k,'same')
The result r will have 0 at all locations which DO NOT have 1's in the immediate 3x3 neighborhood.
6 件のコメント
Ashish Uthama
2012 年 4 月 9 日
João, conv2 pads with zeros around the edges, and it ought to work. convole these two images with [1 1 ; 1 1] to see whats going on and to understand the 'neighborhood' being used.
その他の回答 (1 件)
Image Analyst
2012 年 4 月 6 日
Here is the solution in case you want to compare yours to mine:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Create an image of all zeros.
imageArray = false(50, 70);
% Get up to a tenth of the pixels as white dots.
numberOfSinglePixels = 100 %int32(rand * numel(imageArray) / 10)
scrambledCoords = randperm(numel(imageArray));
coordinatesToSet = scrambledCoords(1:numberOfSinglePixels)';
imageArray(coordinatesToSet) = true;
% Display the image
imshow(imageArray, 'InitialMagnification', 300);
title('Original Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Count up the dots in a sliding 5x7 window.
windowRows = 5;
windowCols = 7;
sumImage = conv2(double(imageArray), ones(windowRows, windowCols), 'same');
% Extract only those pixels where the window is centered
% at dots in the input image.
sumImageMasked = sumImage .* double(imageArray);
% Count those places where the count is exactly 1.
numberOfDots = sum(sumImageMasked(:) == 1)
% Get the locations of those dots in a 5x7 black neighborhood.
[dotRows dotCols] = find(sumImageMasked == 1);
% Plot crosses on those dots.
hold on;
plot(dotCols, dotRows, 'r+', 'MarkerSize', 25);
caption = sprintf('Red crosses over the dots that are in an isolated %x by %d window',...
windowRows, windowCols);
title(caption, 'FontSize', fontSize);
message = sprintf('%d of the %d pixels are in a black neighborhood of %d by %d\n',...
numberOfDots, numberOfSinglePixels, windowRows, windowCols);
fprintf('%s\n', message);
msgbox(message);
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!