user3443200
user3443200

Reputation: 109

How does this MATLAB code make an image into a binary image?

v = videoinput('winvideo', 1, 'YUY2_320x240');
s = serial('COM1', 'BaudRate', 9600);
fopen(s);
while(1)
h = getsnapshot(v);
rgb = ycbcr2rgb(h);
for i = 1:240
    for j = 1:320
         if rgb(i,j,1) > 140 && rgb(i,j,2) < 100    % use ur own conditions
            bm(i, j) = 1;
        else
            bm(i, j) = 0;
        end
    end
end

This is the code i got from my senior regarding image processing using MATLAB. The above code is to convert the image to binary image, But in the code rgb(i, j, 1) > 140 I didn't understand that command. How to select that 140 and what does that rgb(i, j, 1) mean?

Upvotes: 0

Views: 206

Answers (1)

chappjc
chappjc

Reputation: 30589

You have an RGB image rgb where the third dimension are the RGB color planes. Thus, rgb(i,j,1) is the red value at row i, column j.

By doing rgb(i,j,1)>140 it tests if this red value is greater than 140. The value 140 appears to be ad hoc, picked for a specific task.

The code is extremely inefficient as there is no need for a loop:

bm = rgb(:,:,1)>140 & rgb(:,:,2)<100;

Note the change from && to the element-wise operator &. Here I'm assuming that the size of rgb is 240x320x3.


Edit: The threshold values you choose completely depend on the task, but a common approach to automatic thresholding is is Otsu's method, graythresh. You can apply it to a single color plane to get a threshold:

redThresh = graythresh(rgb(:,:,1)) * 255;

Note that graythresh returns a value on [0,1], so you have to scale that by the data range.

Upvotes: 3

Related Questions