如何裁剪和旋转图像到边框? [英] How to crop and rotate an image to bounding box?

查看:390
本文介绍了如何裁剪和旋转图像到边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我有一个包含手的数千个图像的数据集

  • 我也有.mat文件包含边界框四个角的坐标

  • 然而,这些边界框的边缘与x& y轴。例如,

  • I have a dataset of thousands of images containing hands
  • I also have .mat files which contain the coordinates of 4 corners of the bounding box
  • However, the edges of these bounding boxes are at an angle with the x & y axis. For example,

我想使用边界框坐标&然后旋转手,使其与x或y轴对齐。

I want to crop out the hands using the bounding box coordinates & then rotate the hands such that they are aligned with the x or y axis.

编辑:

手的表示如下:

但是,请记住矩形不是直的。

However, please keep in mind that the rectangle is NOT straight. So, I'll have to rotate it to straighten it out.

推荐答案

好的!

计算矩形的大小

 width = sqrt( sum( (b-a).^2 ) );
 height = sqrt( sum( (c-b).^2 ) );



第二步:



计算仿射从 a ... d 转换为直立图像

Second step:

Compute an affine transformation from a...d to an upright image

 Xin = [a(2) b(2) c(2) d(2)];
 Yin = [a(1) b(1) c(1) d(1)];
 Xout = [width 1 1 width];
 Yout = [1 1 height height];
 A = [Xin;Yin;ones(1,4)]';
 B = [Xout; Yout]';
 H = B \ A; % affine transformation

请注意,尽管我们允许fo H 是仿射的,角的选择(取决于 width height code> H 不会扭曲裁剪的矩形。

Note that despite the fact that we allow fo H to be affine, the choise of corners (depending on width and height) will acertain that H will not distort the cropped rectangle.

可以使用 cp2tform

 H2 = cp2tform( [Xin;Yin]', [Xout;Yout]', 'nonreflectivesimilarity' );



第三步



获取相关图片部分

Third step

Use the transformation to get the relevant image part

 thumb = tformarray( img, maketform( 'affine', H' ), ... %//'
                     makeresampler( 'cubic', 'fill' ), ...
                     1:2, 1:2, ceil( [height width] ), [], 0 );

可选择使用 imtransform

optionally use imtransform:

 thumb = imtransform( img, H2, 'bicubic' );






有关向量化的注意事项:



取决于如何存储角落的坐标( a ... d )前两个步骤可以很容易地向量化。


A note regarding vectorization:

depends on how the coordinates of the corners are stored (a...d) the first two steps can be easily vectorize.

这篇关于如何裁剪和旋转图像到边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆