gosr
gosr

Reputation: 4708

RGB image to binary image

I want to load an RGB image in MATLAB and turn it into a binary image, where I can choose how many pixels the binary image has. For instance, I'd load a 300x300 png/jpg image into MATLAB and I'll end up with a binary image (pixels can only be #000 or #FFF) that could be 10x10 pixels.

This is what I've tried so far:

load trees % from MATLAB
gray=rgb2gray(map); % 'map' is loaded from 'trees'. Convert to grayscale.
threshold=128;
lbw=double(gray>threshold);
BW=im2bw(X,lbw); % 'X' is loaded from 'trees'.
imshow(X,map), figure, imshow(BW)

(I got some of the above from an internet search.)

I just end up with a black image when doing the imshow(BW).

Upvotes: 4

Views: 27516

Answers (2)

gnovice
gnovice

Reputation: 125854

Your first problem is that you are confusing indexed images (which have a colormap map) and RGB images (which don't). The sample built-in image trees.mat that you load in your example is an indexed image, and you should therefore use the function ind2gray to first convert it to a grayscale intensity image. For RGB images the function rgb2gray would do the same.

Next, you need to determine a threshold to use to convert the grayscale image to a binary image. I suggest the function graythresh, which will compute a threshold to plug into im2bw (or the newer imbinarize). Here is how I would accomplish what you are doing in your example:

load trees;             % Load the image data
I = ind2gray(X, map);   % Convert indexed to grayscale
level = graythresh(I);  % Compute an appropriate threshold
BW = im2bw(I, level);   % Convert grayscale to binary

And here is what the original image and result BW look like:

enter image description here

enter image description here

For an RGB image input, just replace ind2gray with rgb2gray in the above code.

With regard to resizing your image, that can be done easily with the Image Processing Toolbox function imresize, like so:

smallBW = imresize(BW, [10 10]);  % Resize the image to 10-by-10 pixels

Upvotes: 8

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

It is because gray is in the scale of [0,1], whereas threshold is in [0,256]. This causes lbw to be a big array of false. Here is a modified code that solves the problem:

load trees % from MATLAB
gray=rgb2gray(map); % 'map' is loaded from 'trees'. Convert to grayscale.
threshold=128/256;
lbw=double(gray>threshold);
BW=im2bw(X,lbw); % 'X' is loaded from 'trees'.
imshow(X,map), figure, imshow(BW)

And the result is:

enter image description here

Upvotes: 0

Related Questions