How to calculate pixel values of a specific area in a binary image?

5 次查看(过去 30 天)
I have the following image, I want to identify the pixel values of the white object in the marked region. I cannot do any operations like imfill etc to make it one object and detect the pixel values as I need the original ratio of white and black pixels of that specific region. How can I have the pixel values from the specific marked region?
  1 个评论
Image Analyst
Image Analyst 2018-11-8
What do you consider the region of interest over which you want to count the black and white pixels? Do you want to take the convex hull of the blobs? Do you then want to call imdilate() to dilate it as large as the red oval? Can you attach the original image, without the red oval so people can try things with it? In the meantime, look up regionprops, especially the Solidity measurement.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2018-11-9
TRK - are you still there?
Since I didn't hear from you I had to make up several options for masks. As you can see I made up 5 possible masks. I'm not sure which method is closest to what you want. But as you can see they all product different masks with different sizes and shapes, and because of that the number of white, black, and mask pixels will be different in each one and the area fractions will also be all different.
Here is the code:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 18;
%===============================================================================
% Read in gray scale demo image.
folder = pwd; % Determine where demo folder is (works with all versions).
baseFileName = 'somename.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
% grayImage = rgb2gray(rgbImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
grayImage = rgbImage(:, :, 1); % Take red channel.
else
grayImage = rgbImage; % It's already gray scale.
end
% Now it's gray scale with range of 0 to 255.
% Display the image.
subplot(3, 3, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
hp = impixelinfo();
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
% Binarize the image
binaryImage = grayImage > 128;
% Display the image.
subplot(3, 3, 2);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Make one type of mask, and display it.
mask1 = bwareafilt(binaryImage, 1);
mask1 = imfill(mask1, 'holes');
% Display the image.
subplot(3, 3, 3);
imshow(mask1, []);
title('Mask1 = exact outline of biggest blob', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find boundary and display it
boundary1 = bwboundaries(mask1);
hold on;
plot(boundary1{1}(:, 2), boundary1{1}(:, 1), 'r-', 'LineWidth', 2);
% Make another type of mask, and display it.
mask2 = imclose(binaryImage, true(3));
mask2 = bwareafilt(mask2, 1);
mask2 = imfill(mask2, 'holes');
mask2 = bwconvhull(mask2);
% Display the image.
subplot(3, 3, 4);
imshow(mask2, []);
title('Mask2 = smoothed then convex hull', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find boundary and display it
boundary2 = bwboundaries(mask2);
hold on;
plot(boundary2{1}(:, 2), boundary2{1}(:, 1), 'r-', 'LineWidth', 2);
% Make another type of mask, and display it.
windowWidth = 89;
kernel = ones(windowWidth) / windowWidth^2;
threshold = 0.13;
mask3 = conv2(double(binaryImage), kernel, 'same') > threshold;
mask3 = bwareafilt(mask3, 1);
mask3 = imfill(mask3, 'holes');
% Display the image.
subplot(3, 3, 5);
imshow(mask3, []);
title('Mask3 = blurred then thresholded', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find boundary and display it
boundary3 = bwboundaries(mask3);
hold on;
plot(boundary3{1}(:, 2), boundary3{1}(:, 1), 'r-', 'LineWidth', 2);
% Make another type of mask, and display it.
mask4 = imclose(binaryImage, true(3));
mask4 = bwareafilt(mask4, 1);
mask4 = imfill(mask4, 'holes');
mask4 = bwconvhull(mask4);
se = strel('disk', 35, 0);
mask4 = imdilate(mask4, se);
% Display the image.
subplot(3, 3, 6);
imshow(mask4, []);
title('Mask4 = dilated convex hull', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find boundary and display it
boundary4 = bwboundaries(mask4);
hold on;
plot(boundary4{1}(:, 2), boundary4{1}(:, 1), 'r-', 'LineWidth', 2);
% Make one type of mask, and display it.
mask5 = bwareafilt(binaryImage, 1);
mask5 = imfill(mask5, 'holes');
% Find centroid
props = regionprops(mask5, 'Centroid');
% Create a logical image of a circle with specified
% diameter, center, and image size.
% First create the image.
[columnsInImage rowsInImage] = meshgrid(1:columns, 1:rows);
% Next create the circle in the image.
centerX = props.Centroid(1);
centerY = props.Centroid(2);
radius = 200;
mask5 = (rowsInImage - centerY).^2 ...
+ (columnsInImage - centerX).^2 <= radius.^2;
% circlePixels is a 2D "logical" array.
% Display the image.
subplot(3, 3, 7);
imshow(mask5, []);
title('Mask5 = perfect circle', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
% Find boundary and display it
boundary5 = bwboundaries(mask5);
hold on;
plot(boundary5{1}(:, 2), boundary5{1}(:, 1), 'r-', 'LineWidth', 2);
%=====================================================================
% Show all boundaries on original image.
% Display the image.
figure;
imshow(binaryImage, []);
title('All Boundaries', 'FontSize', fontSize, 'Interpreter', 'None');
axis('on', 'image');
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
hold on;
plot(boundary1{1}(:, 2), boundary1{1}(:, 1), 'r-', 'LineWidth', 2);
plot(boundary2{1}(:, 2), boundary2{1}(:, 1), 'r-', 'LineWidth', 2);
plot(boundary3{1}(:, 2), boundary3{1}(:, 1), 'r-', 'LineWidth', 2);
plot(boundary4{1}(:, 2), boundary4{1}(:, 1), 'r-', 'LineWidth', 2);
plot(boundary5{1}(:, 2), boundary5{1}(:, 1), 'r-', 'LineWidth', 2);
% Compute number of white, black, and area fraction of each mask
fprintf('Mask # Num White, Num Black, Num Mask, Area Fraction\n----------------------------------------------------------\n');
% For mask #1:
areaMask = nnz(mask1);
areaWhite = nnz(mask1 & binaryImage);
areaBlack = areaMask - areaWhite;
areaFraction = areaWhite / areaMask;
fprintf(' 1 %12d %10d %11d %12.3f\n', areaWhite, areaBlack, areaMask, areaFraction);
% For mask #2:
areaMask = nnz(mask2);
areaWhite = nnz(mask2 & binaryImage);
areaBlack = areaMask - areaWhite;
areaFraction = areaWhite / areaMask;
fprintf(' 2 %12d %10d %11d %12.3f\n', areaWhite, areaBlack, areaMask, areaFraction);
% For mask #3:
areaMask = nnz(mask3);
areaWhite = nnz(mask3 & binaryImage);
areaBlack = areaMask - areaWhite;
areaFraction = areaWhite / areaMask;
fprintf(' 3 %12d %10d %11d %12.3f\n', areaWhite, areaBlack, areaMask, areaFraction);
% For mask #4:
areaMask = nnz(mask4);
areaWhite = nnz(mask4 & binaryImage);
areaBlack = areaMask - areaWhite;
areaFraction = areaWhite / areaMask;
fprintf(' 4 %12d %10d %11d %12.3f\n', areaWhite, areaBlack, areaMask, areaFraction);
% For mask #5:
areaMask = nnz(mask5);
areaWhite = nnz(mask5 & binaryImage);
areaBlack = areaMask - areaWhite;
areaFraction = areaWhite / areaMask;
fprintf(' 5 %12d %10d %11d %12.3f\n', areaWhite, areaBlack, areaMask, areaFraction);
Here are the images that the code makes:
and here is the output that it computes for each of those masks:
Mask # Num White, Num Black, Num Mask, Area Fraction
----------------------------------------------------------
1 14605 1978 16583 0.881
2 22081 37074 59155 0.373
3 20845 41233 62078 0.336
4 22098 67985 90083 0.245
5 21893 103508 125401 0.175
So, again, which boundary do you want?
  19 个评论
Image Analyst
Image Analyst 2021-6-22
@RAKESH KUCHANA, evidently you overlooked where I asked you to start your own question in a new thread. So I'm not sure you're reading my responses, but regardless, I did it for you anyway. If you do read this, please vote for my answer above if this worked for you. Thanks in advance. Otherwise, if it didn't, then explain what went wrong IN A NEW POST (NOT HERE in @TRK's post). I'm assuming the red is burned into the image (not in the overlay), just like the example image you posted.
% Demo by Image Analyst for RAKESH. June 22, 2021.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
%-----------------------------------------------------------------------------------------------------------------------------------
% Read in image. This is a horrible image. NEVER use JPG format for image analysis. Use PNG, TIFF, or BMP instead.
folder = [];
baseFileName = 'image.png';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display the test image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
caption = sprintf('Original RGB Image : "%s", %d rows by %d columns', baseFileName, rows, columns);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
% Create a binary image of the red circle.
threshold = 128;
binaryImage = rgbImage(:, :, 1) >= threshold & rgbImage(:, :, 2) <= threshold & rgbImage(:, :, 3) <= threshold;
% Display the image.
subplot(2, 2, 2);
imshow(binaryImage, []);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
caption = sprintf('Initial, Red Mask Image : %d rows by %d columns', rows, columns);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Get the INSIDE of the red circle.
binaryImage = imclearborder(~binaryImage);
% Fill holes
binaryImage = imfill(binaryImage, 'holes');
% Take largest blob only
binaryImage = bwareafilt(binaryImage, 1);
% Display the image.
subplot(2, 2, 3);
imshow(binaryImage, []);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
title('Final Mask Image -- Inside the Red Ring', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Now mask the image. Use the blue channel to get the white stuff inside the red circle.
maskedImage = rgbImage(:, :, 3) >= threshold; % Extract blue channel and apply threshold.
maskedImage(~binaryImage) = 0;
% Count the pixels
numberOfPixels = nnz(maskedImage)
% Display the image.
subplot(2, 2, 4);
imshow(maskedImage, []);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
caption = sprintf('Number of pixels inside red ring = %d', numberOfPixels);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
message = sprintf('Done!\nThe number of pixels inside the red ring = %d.', numberOfPixels);
msgbox(message);
RAKESH KUCHANA
RAKESH KUCHANA 2021-6-22
I am using MATLAB R2013a version. There is no bwfiltarea() function. How to solve issue?

请先登录,再进行评论。

更多回答(1 个)

RAKESH KUCHANA
RAKESH KUCHANA 2021-6-22
Hello sir, I need only 4th image and the pixel count in 4th image of your code. Can you provide short code?
  1 个评论
Image Analyst
Image Analyst 2021-6-22
No, I will not do that here (in your answer to @TRK), but, like I've said twice already, I will in your new question. You can reply here only to give the link to your new question.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Image Segmentation and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by