How can I plot x and y RGB values of an image to analyze?

52 views (last 30 days)
I am analyzing the results of an optical test. In essence, the samples generate a halo as seen in the picture attached. Good samples are those that have mostly black in the middle and a green halo on the outside ( ring shape ).
I want to write a script that imports the image looks at the RGB ( in order to get color intensity). Then plots each image in a 3D plot. In my mind it would look something like valley since the exterior has the largest intenisty and the interior is black. The idea is to analyze a large enough set of data that I can then create a threshold for how much illumniation I can allow in the center before the product is considered bad.
I have tried using Imread to get the RGB values. Then taking the Green portion and plotting that using both surf and plot with no success. Any help and guidance is appreciated.
  3 Comments
SnooptheEngineer
SnooptheEngineer on 25 Jul 2022
@Walter Roberson Thank you for your answer. First of all the color map was in black only. Second of all, I wanted to plot the x,y cordinate for each pixel with green intensity so I can go about analyzing several images and eliminating those that have light in the center of the ring. The idea is to have the least amount of light inside the ring.
Walter Roberson
Walter Roberson on 25 Jul 2022
What is the mapping between row and columns to x and y, if the surf() is not the plot you need?

Sign in to comment.

Accepted Answer

William Rose
William Rose on 25 Jul 2022
Try the following:
im1=imread('knifetest1.jpg');
zr=im1(:,:,1); %get the red intensity array
zg=im1(:,:,2); %get the green intensity array
zb=im1(:,:,3); %get the blue intensity array
[r,c]=size(zg); %image dimensions
surf(1:c,1:r,zg,'EdgeColor','none'); %surface plot of green intensity
zlabel('Green Intensity')
This produces a 3D plot which you can rotate. It looks reasonable to me. You can also plot the red and blue intensities, zr and zb.
Good luck.
  14 Comments
Image Analyst
Image Analyst on 5 Aug 2022
Why can't you use a fixed template and look at the same part of the image all the time? Does your part move around in the field of view? Does it change size or shape? Does your camera move around? Is there anyway you can eliminate those things by using a jig to place your part and making your camera mounting brackets very rigid and secure?

Sign in to comment.

More Answers (2)

Image Analyst
Image Analyst on 26 Jul 2022
Here is a quick and dirty way. It could be made better with more programming. Also if you knew the shape of the interior in advance then we could use that and locate it and align it with the image to get a better mask shape that doesn't depend on the threshold.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'knifetest.jpg';
folder = pwd;
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
%=======================================================================================
% Read in demo image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Crop off screenshot stuff
% rgbImage = rgbImage(132:938, 352:1566, :);
% Display image.
subplot(2, 3, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original Color Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% 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;
% Take one of the color channels, whichever one seems to have more contrast.
grayImage = max(rgbImage, [], 3);
% Display the image.
subplot(2, 3, 2);
imshow(grayImage, []);
title('Gray Scale Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
%=======================================================================================
% Show the histogram
subplot(2, 3, 3);
imhist(grayImage);
grid on;
caption = sprintf('Histogram of Gray Scale Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize)
ylabel('Count', 'FontSize', fontSize)
%=======================================================================================
% Threshold the image to get the disk.
lowThreshold = 85;
highThreshold = 255;
% Use interactive File Exchange utility by Image Analyst to to the interactive thresholding.
% https://www.mathworks.com/matlabcentral/fileexchange/29372-thresholding-an-image?s_tid=srchtitle
% [lowThreshold, highThreshold] = threshold(114, 255, grayImage);
mask = grayImage >= lowThreshold & grayImage <= highThreshold;
xline(lowThreshold, 'Color', 'r', 'LineWidth',2);
xline(highThreshold, 'Color', 'r', 'LineWidth',2);
% Find out the size of all the blobs so we know what size to use when filtering with bwareaopen.
props = regionprops(mask, 'Area');
allAreas = sort([props.Area]);
% Display the mask image.
subplot(2, 3, 4);
imshow(mask, []);
title('Initial Mask', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
% Now do clean up by hole filling, and getting rid of small blobs.
mask = ~bwareaopen(mask, 6); % Take blobs larger than 6 pixels only.
% Erode the mask so that we have an ROI within the outer boundaries.
se = strel('disk', 18, 0);
mask = imerode(mask, se);
% Hopefully there are two blobs at this point.
% Remove background
mask = imclearborder(mask);
% There should be only one at this point, but just to be sure, extract the largest blob.
mask = bwareafilt(mask, 1);
% Get the convex hull
mask = bwconvhull(mask, 'union');
% Display the mask image.
subplot(2, 3, 5);
imshow(mask, []);
title('Final Mask', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
% Plot the borders of all the blobs in the overlay above the original grayscale image
% using the coordinates returned by bwboundaries().
% bwboundaries() returns a cell array, where each cell contains the row/column coordinates for an object in the image.
% Here is where we actually get the boundaries for each blob.
boundaries = bwboundaries(mask);
% boundaries is a cell array - one cell for each blob.
% In each cell is an N-by-2 list of coordinates in a (row, column) format. Note: NOT (x,y).
% Column 1 is rows, or y. Column 2 is columns, or x.
numberOfBoundaries = size(boundaries, 1); % Count the boundaries so we can use it in our for loop
% Here is where we actually plot the boundaries of each blob in the overlay.
subplot(2, 3, 1);
hold on; % Don't let boundaries blow away the displayed image.
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k}; % Get boundary for this specific blob.
x = thisBoundary(:,2); % Column 2 is the columns, which is x.
y = thisBoundary(:,1); % Column 1 is the rows, which is y.
plot(x, y, 'r-', 'LineWidth', 2); % Plot boundary in red.
end
hold off;
caption = sprintf('Original image with %d Outlines, from bwboundaries()', numberOfBoundaries);
title(caption, 'FontSize', fontSize);
axis('on', 'image'); % Make sure image is not artificially stretched because of screen's aspect ratio.
% Mask the image and show the masked image.
subplot(2, 3, 6);
maskedImage = grayImage; % Initialize.
maskedImage(~mask) = 0; % Erase outside the mask.
imshow(maskedImage, [])
title('Masked Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
hold on;
plot(x, y, 'r-', 'LineWidth', 2); % Plot boundary in red.
% Find out the size of all the remaining blobs.
props = regionprops(mask, grayImage, 'Area', 'MeanIntensity');
caption = sprintf('Area = %d pixels. Mean Intensity = %.2f', props.Area, props.MeanIntensity)
title(caption, 'FontSize', fontSize);
uiwait(helpdlg('Done!'));
  2 Comments
SnooptheEngineer
SnooptheEngineer on 1 Aug 2022
Edited: SnooptheEngineer on 1 Aug 2022
Thank you very much for taking the time to help. I am sorry for going MIA. I got into a deep hole going over both your solutions.Honestly, your code was slightly overwhelming but nonethless very impressive. I tried running it for the other image but it didnt work.
As I mentioned earlier, I am looking for a way to use this script for a wide variety of parts. I tried to modify your approach by using a series of nested for loops to scan through the image and read pixel values to establish the edges of the image ( once a certain threshold is met)
We start scanning from the top left corner while reading the pixel value. Once I read a value above threshold it's set as reference. After that once, I read a value that is well below the first threshold I esablished, that pixel is assigned the xmin,ymax coordinate (top left corner of my rectangle).Setting that as reference, I read the pixel values on that same y axis (scan left to right) until I hit that threshold identifying the top right corner.
Then I repeat the process but starting my scan from the bottom of the image. 4 of the 6 points identified, would be used to create the rectangle for the region of interest.
That said, I was not successul in my appraoch as the code seems to skip the left side of the rectangle complete. Please ignore my draft code below. I am just trying to show the upper level thought process. I think my issue lies with establishing the threshold value. My goal is to create a rectangle inside the region of interest.
I see two ways forward:
  1. Using your appraoch of switching the image to a gray scale and trying to identify light vs no light then using these thresholds in a series of nested loops
2. Have the user somehow identify or select the region of interest. Then using @William Rose's approach to intergtate the intensity (Ask user to select four points to highlight rectangular region). However, I would probably need to divide the region of interest ( red rectangle) into a smaller set of squares and set a pass/fail threshold invididually
Thanks again for your help. I really appreicate your time and effort. Your insight will help me know assess how deep into the rabbit hole I need to go before making a decision on this approach
P.S: I inlcluded the old bad knife image sample that didnt work with your code.

Sign in to comment.


Image Analyst
Image Analyst on 25 Jul 2022
You don't need to do a surf plot of anything. Do you just want to determine the average R, G, and B values inside the halo? Or max values or standard deviation? Then just find the halo mask (not hard) and do
[r, g, b] = imsplit(rgbImage);
propsR = regionprops(haloMask, r, 'MeanIntensity');
propsG = regionprops(haloMask, g, 'MeanIntensity');
propsB = regionprops(haloMask, b, 'MeanIntensity');
Let me know if you can't figure out how to get the region of interest inside the halo boundary. You can probably threshold and then do some morphological clean up to get that shape.
  3 Comments
Image Analyst
Image Analyst on 26 Jul 2022
You didn't use the right variable. You used the filename, not the image. You need to do this:
rgbImage = imread('knifetest.jpg');
[r, g, b] = imsplit(rgbImage);
SnooptheEngineer
SnooptheEngineer on 26 Jul 2022
I did that and got a different error this time. Do I need to define HaloMask ? Thats the only thing I can think of. BTW, your posts on Matlab have been great to read and I appreciate your help :)
--------------------
Unrecognized function or variable 'haloMask'.
Error in knifeedgepractice (line 4)
propsR = regionprops(haloMask, r, 'MeanIntensity');

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!