MATLAB: How to save the image WITHOUT the white background using imwrite (advanced problem)

backgroundimwritesave image

Hi
RGB = imread('bird1.png');
figure
imshow(RGB)
Then I get:
Then:
s = size(RGB);
rectangle('position',[1 1 s(2) s(1)], 'edgecolor', [1 0 0])
rectangle('position',[0 0 s(2) s(1)], 'edgecolor', [1 0 0])
I get:
Now I would like to save this image WITHOUT the white background, only the content within the red box (including the red box).
Imwrite needs to use 'RGB', however after the red box been added onto the image, RGB is no longer the original RGB. It WON'T be correct just to use
imwrite(RGB, 'bird1.png');
Could anyone provide correct solution to this question please?

Best Answer

Try this:
% To burn the color into the image itself.
[rows, columns, numberOfCOlorChannels] = size(RGB)
RGB(:, 1, 1:3) = repmat([255, 0, 0], rows, 1);
RGB(:, end, 1:3) = repmat([255, 0, 0], rows, 1);
RGB(1, :, 1:3) = repmat([255, 0, 0], columns, 1);
RGB(end, :, 1:3) = repmat([255, 0, 0], columns, 1);
imshow(RGB);
imwrite(RGB, filename);
It's much more robust than saving the bitmap in the overlay, which is subject to change whenever you resize the figure window.