1

In the code below I rotated an image. How can I get a single background color (white or black)?

code:

close all;
clear;
clc;

url='http://www.clker.com/cliparts/T/i/o/c/X/Q/airplane-md.png';
RI = imread(url);
I = rgb2gray(RI);

BI = imbinarize(I);

LI = bwlabel(BI);
mea = regionprops(LI, 'All');
RI = imrotate(RI, -mea(1).Orientation,'loose');
imshow(RI);
jane
  • 567
  • 2
  • 12

2 Answers2

2

Given that the image is a simple logo (as opposed to a photo for instance) you can likely use logical indexing to change all of the black pixels added by imrotate to white pixels.

I don't have the image processing toolbox so I couldn't run your code, but the sample below should illustrate:

%Load RBG image to test on
RI = imread('peppers.png');
%Create black region to remove
RI(100:150,100:150,:) = 0;

figure()
imshow(RI)
title('Original Image')

%Replace all black pixels with white
inds = sum(RI,3)==0;
RI_new = RI;
RI_new(repmat(inds,1,1,3))=255;

figure()
imshow(RI_new)
title('New Image')

In comparison to the answer from @SardarUsama, this has the weakness of assuming there are no black pixels in your original image but the advantage of using built-in Matlab functions only.

Edit: Updated to show example on RGB image rather than grayscale

JMikes
  • 572
  • 4
  • 12
  • The line `BI = imbinarize(I);` guarantees that the image is of type logical (all 0's or 1's) so the data-type is known rather than assumed. This also ensures that black is strictly black and white is strictly white. – JMikes Jul 06 '19 at 16:17
  • My mistake, thank you. I didn't notice RI and BI were different variables and, because of the toolboxes used, couldn't run the code myself. I will clarify accordingly. As for black being strictly black, because the black being removed was added by imrotate and will be exactly 0, this assumption should hold. – JMikes Jul 06 '19 at 16:24
1

Your original image has white background. When you rotate it, you get black pixels in the background to fill up the image matrix. This may be due to that the preallocation of the rotated image matrix is done with zeros which then translates to black (implemented probably in imrotatemex and in the lines 116 and 118 of imrotate). You can use these alternate implementations of imrotate but preallocate the matrix with ones (for double data) or 255 (for uint8 data).

For example, in line 31 of Rody's implementation, i.e.:

imagerot = zeros([max(dest) p],class(image));

Change this line to:

imagerot = 255*ones([max(dest) p],'uint8');   %Your image is uint8 in this case

Result:
result

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58