Toygan
Toygan

Reputation: 422

MATLAB: RGB to white and black image

I have an image which is 160x64x3. This image has gray points and other colors. What I want is to convert the gray parts to 0 and the other parts to 1.

The image is below:

Image

what I did is below but I think it is not certain because maybe there are some points which are the same for all red, green and blue. Is there a special function for this?

~((image(:,:,1)==image(:,:,2))&(image(:,:,1)==image(:,:,3))&(image(:,:,2)==image(:,:,3))) 

Upvotes: 1

Views: 573

Answers (1)

Rotem
Rotem

Reputation: 32084

I don't know any special function, but the solution is pretty straightforward:

I = imread('sLUp2.png'); %Read source image.

%Initialize all destination pixels to 1
J = ones(size(I,1), size(I,2));

%Set to zero pixels which are gray in I (where Red==Green and Red==Blue).
J((I(:,:,1) == I(:,:,2)) & (I(:,:,1) == I(:,:,3))) = 0;

In the above solution all source gray-scale pixels with R=G=B, are considered gray.
For example: black pixel: (0,0,0), white pixel (255,255,255) and (x,x,x) are considered gray...


In case you want to find only the single common gray level (not all "gray-scale" pixels), you can do (something) as follows:

R = I(:, :, 1); %Red color plane.
Gray = R((I(:,:,1) == I(:,:,2)) & (I(:,:,1) == I(:,:,3))); %All values in which R=G=B.
H = imhist(Gray, 256); %Collect histogram of Gray.
common_gray = find(H == max(H)) - 1; %Find the most common gray value in histogram.

%Now, set only common_gray pixels to zero in destination image J.
J = ones(size(I,1), size(I,2));
J(R == common_gray) = 0;

In your image the common gray level ("gray points") equals 128.

enter image description here

Upvotes: 3

Related Questions