Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 866
gosr Avatar asked Feb 19 '23 08:02

gosr


1 Answers

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
like image 81
gnovice Avatar answered Feb 28 '23 00:02

gnovice