Search code examples
matlabimage-processingplotimage-rotation

Incorrect rotation of image - Matlab


How can I plot the rotated crop images in separated figure and what is the problem that I do not get the rotation correct (e.g, k= 3 or 6)?

code:

clear;
clc;

RGB = imread('pillsetc.png');
I = rgb2gray(RGB);
bw = imbinarize(I);
bw = bwareaopen(bw,30);
bw = imfill(bw,'holes');

imshow(bw)

[B,L] = bwboundaries(bw,'noholes');

imshow(bw)

[labeledImage, numBlobs] = bwlabel(bw);


for k = 1 : numBlobs
  thisObject = ismember(labeledImage, k);
  measurements = regionprops(thisObject, 'Orientation', 'BoundingBox');
  croppedImage = imcrop(RGB, measurements.BoundingBox);
  angle = measurements.Orientation
  uprightImage = imrotate(croppedImage, angle);
  imshow(uprightImage);
  hold on
end  

Solution

  • The problem is that as you get the angle of the object, if you want to have them horizontal you must do:

    uprightImage = imrotate(croppedImage, -angle);
    

    and not:

    uprightImage = imrotate(croppedImage, angle);
    

    If I run this code on Mario:

    Original Mario

    clear;
    clc;
    
    RGB = imread('Small-mario.png');
    I = rgb2gray(RGB);
    bw = imbinarize(I);
    bw = bwareaopen(bw,30);
    bw = imfill(bw,'holes');
    
    figure;
    imshow(bw)
    
    [B,L] = bwboundaries(bw,'noholes');
    
    figure;
    imshow(bw)
    
    [labeledImage, numBlobs] = bwlabel(bw);
    
    
    for k = 1 : numBlobs
      thisObject = ismember(labeledImage, k);
      measurements = regionprops(thisObject, 'Orientation', 'BoundingBox');
      croppedImage = imcrop(RGB, measurements.BoundingBox);
      angle = measurements.Orientation;
      uprightImage = imrotate(croppedImage, -angle);
      figure;
      imshow(uprightImage);
    end
    

    After that, Mario's head is horizontal:

    Horizontal Mario