如何使用 scipy.ndimage.interpolation.affine_transform 围绕其中心旋转图像?

2022-01-16 00:00:00 python numpy scipy matplotlib rotation

问题描述

我对 <代码>scipy.ndimage.interpolation.affine_transform.从 this issue 来看,我不是唯一一个.我实际上想用 affine_transform 做更多有趣的事情,而不仅仅是旋转图像,但对于初学者来说,旋转就可以了.(是的,我很清楚 scipy.ndimage.interpolation.rotate,但弄清楚如何驱动 affine_transform 是我感兴趣的地方).

I am perplexed by the API to scipy.ndimage.interpolation.affine_transform. And judging by this issue I'm not the only one. I'm actually wanting to do more interesting things with affine_transform than just rotating an image, but a rotation would do for starters. (And yes I'm well aware of scipy.ndimage.interpolation.rotate, but figuring out how to drive affine_transform is what interests me here).

当我想在像 OpenGL 这样的系统中做这种事情时,我会考虑计算变换,它应用关于中心 cRcode>,因此考虑点 p 被转换 (pc)R+c = pR+c-cR,这给出了一个 c-cR 术语用作变换的翻译组件.然而,根据上面的问题,scipy 的 affine_transform 会offset first"所以我们实际上需要计算一个偏移量s 使得 (pc)R+c=(p+s)R 有一点重新排列给出 s=(c-cR)R' 其中 R'R 的倒数.

When I want to do this sort of thing in systems like OpenGL, I'm think in terms of computing the transform which applies a 2x2 rotation matrix R about a centre c, and therefore thinking of points p being transformed (p-c)R+c = pR+c-cR, which gives a c-cR term to be used as the translation component of a transform. However, according to the issue above, scipy's affine_transform does "offset first" so we actually need to compute an offset s such that (p-c)R+c=(p+s)R which with a bit of rearrangement gives s=(c-cR)R' where R' is the inverse of R.

如果我将它插入 ipython 笔记本(pylab 模式;下面的代码可能需要一些额外的导入):

If I plug this into an ipython notebook (pylab mode; code below maybe needs some additional imports):

img=scipy.misc.lena()
#imshow(img,cmap=cm.gray);show()
centre=0.5*array(img.shape)
a=15.0*pi/180.0
rot=array([[cos(a),sin(a)],[-sin(a),cos(a)]])
offset=(centre-centre.dot(rot)).dot(linalg.inv(rot))
rotimg=scipy.ndimage.interpolation.affine_transform(
    img,rot,order=2,offset=offset,cval=0.0,output=float32
)
imshow(rotimg,cmap=cm.gray);show()

我明白了

不幸的是,它没有围绕中心旋转.

which unfortunately isn't rotated about the centre.

那么我在这里缺少什么技巧?

So what's the trick I'm missing here?


解决方案

只是做一些快速&肮脏的测试我注意到你的偏移量的负值似乎围绕中心旋转.

Just doing some quick & dirty testing I noticed that taking the negative value of your offset seems to rotate about the centre.

相关文章