Code for image comparison in MATLAB pt. 2

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

  1. Tek_Knowledge

    Tek_Knowledge Thread Starter New Member

    Joined:
    Apr 23, 2008
    Messages:
    6
    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

    Dave Retired Moderator

    Joined:
    Nov 17, 2003
    Messages:
    6,961
    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
  3. Tek_Knowledge

    Tek_Knowledge Thread Starter New Member

    Joined:
    Apr 23, 2008
    Messages:
    6

    function
    rgb2gray
  4. Dave

    Dave Retired Moderator

    Joined:
    Nov 17, 2003
    Messages:
    6,961
    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:
    % I is your image from imread or other image read function
    
    J = rgb2gray(I);
    
    numblkpxl = 0;
    for n = 1:(size(J,2))
    
    for m = 1:(size(J,1))
    if isequal(0,J(m,n))
    numblkpxl = numblkpxl + 1;​
    end​
    end​
    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
Similar Threads
Forum Title Date
Programmer's Corner Divide in C code for PIC Sep 21, 2014
Programmer's Corner HELP! Passcode enabled blinking LEDs w/ arduino uno Aug 21, 2014
Programmer's Corner EEPROM test code problem. Jul 29, 2014
Programmer's Corner Hide C# Code Jul 1, 2014
Programmer's Corner large c programming project code examples for microcontrollers needed Jun 23, 2014

Share This Page