2

Why I can not crop the rotated image based on the object (jet) bounding box and is there a more efficient way to do it? Based on previous question: Image single background color - Matlab

Code:

close all;
clear;
clc;

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

BI = imbinarize(I);
LI = bwlabel(BI);
mea = regionprops(LI, 'Orientation');
RI = imrotate(rgbImage, -mea(1).Orientation,'loose');
imshow(RI);

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

% Crop rotated image 
RI_newGray = rgb2gray(RI_new);
BI_newGray = imbinarize(RI_newGray);
LI_new = bwlabel(BI_newGray);
LI_new= bwareaopen(LI_new, 50);
bbmea = regionprops(LI_new, 'BoundingBox');
rect = bbmea.BoundingBox; 
RI_newGray = imcrop(RI_new, rect); 
imshow(RI_newGray);
title('crop RI new');
jane
  • 567
  • 2
  • 12
  • What happens when you run the code you posted? How does that behaviour differ from what you intended to happen? Please be specific about defining the problem. – JMikes Jul 07 '19 at 17:44

1 Answers1

2

Replace:

bbmea = regionprops(LI_new, 'BoundingBox');

With:

bbmea = regionprops(~LI_new, 'BoundingBox');

Explanation:

The problem is that regionprops calculates the group of the none-zero elements, in a black and white logical image the function calculates the groups of ones which are the white pixel. To calculate the bounding-box of the black pixels you can invert the image.

Using bbmea = regionprops(LI_new, 'BoundingBox');:

Using LI_new

Using bbmea = regionprops(~LI_new, 'BoundingBox');:

Using ~LI_new

Community
  • 1
  • 1
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37