Search code examples
matlabbounding-box

How to separate and save a part of an image?


I'm trying to save each rectangle in an image as a separate jpeg image to be able to train a neural network. this is how I draw a rectangle over trucks:

function hdl = BBox(img, samp)

I = imread(img);
hdl = imshow(img);
hold on;

s = size(samp,1);

for i=1:s

bbox = samp(i,:);

X = [bbox(3)-(bbox(5)), bbox(3)-(bbox(5)), bbox(3)-(bbox(5))+2*bbox(5), bbox(3)-(bbox(5))+2*bbox(5), bbox(3)-(bbox(5))];
Y = [bbox(4)-(bbox(6)), bbox(4)-(bbox(6))+2*bbox(6), bbox(4)-(bbox(6))+2*bbox(6), bbox(4)-(bbox(6)), bbox(4)-(bbox(6))];

Cx = bbox(3);
Cy = bbox(4);

H = [X;Y;ones(1,5)]; %// points as 3D homogeneous coordinates
Tc = [1 0 -Cx; 0 1 -Cy; 0 0 1]; %// translation as a matrix
Tr = [cosd((-bbox(7))) -sind((-bbox(7))) 0; sind((-bbox(7))) cosd((-bbox(7))) 0; 0 0 1]; %// rotation
Hr = inv(Tc) * Tr * Tc * H; %// all transformations as matrix products

plot( Hr(1,:), Hr(2,:) ); %// the rotated rect
disp(Hr);

end

I don't think the imcrop command works for rotated rectangles.

How can I save each rectangle as a different image?

enter image description here


Solution

  • I guess an easy way would be to use the extractRotatedPatch File Exchange Submission

    rpatch = extractRotatedPatch(img, center, width, height, angle)
    

    Sidenote:

    Though this is not a Matlab issue, I just want to give you a heads up that you may need to train it on millions of images before machinelearning would start to give decent results.