# Code for image comparison in MATLAB pt. 2

Discussion in 'Programmer's Corner' started by Tek_Knowledge, Apr 27, 2008.

1. ### Tek_Knowledge Thread Starter New Member

Apr 23, 2008
6
0
All right, so i've developed my algorithm for spectral comparison in MATLAB. I read the images into matlab and convert them to grayscale. Now what i want to do have the program scan the images for black pixels. so basically

numbkpixels = 0;
while (in picture range)
if pixel = black
numbkpixels = numbxpixels + 1
else
go to next pixel
return numbkpixels

any ideas?

2. ### Dave Retired Moderator

Nov 17, 2003
6,960
147
If at all possible you need to avoid using loops in Matlab, particularly for large image sets. Can I ask what function (or argument from your image read function) you using to obtain the grayscale image? The reason I ask is that there might be a vectorised option built into Matlab, but this will depend on the functions used.

Dave

Apr 23, 2008
6
0

function
rgb2gray

4. ### Dave Retired Moderator

Nov 17, 2003
6,960
147
I cannot see a vectorisation option in Matlab for the output of the rgb2gray function so we are looking at loops.

Am I correct to assume the grayscale image is of datatype uint8? (You will be able to see this from the Matlab workspace). The important point is that datatype is unsigned, therefore the pure-black pixels will be of value 0.

What you are asking for is a function that will deduce the number of black pixels. If so, then the following loops will work (be sure to debug the syntax - I am writing this without Matlab to hand):

Code ( (Unknown Language)):
2.
3. J = rgb2gray(I);
4.
5. numblkpxl = 0;
6. for n = 1:(size(J,2))
7. [INDENT]for m = 1:(size(J,1))
8. [INDENT]if isequal(0,J(m,n))
9. [INDENT]numblkpxl = numblkpxl + 1;[/INDENT]
10. end[/INDENT]
11. end[/INDENT]
12. end
There is an important point to note here: depending on the formatting of your original image, when the grayscale thresholding is performed through rgb2gray, the deduction of the black intensity might not be exactly 0 - i.e. it may for all intents purposes be black on the original; however the thresholding pitches the grayscale intensity at a value of 1 or 2.

Dave