python实现图形旋转,在Python中围绕指定原点旋转2D图像

I have a 2D image of 512x512 pixels that I would like to rotate with a certain angle at a certain origin (rotation center). All this time, I uses Scipy to rotate images with its rotate method. But, I got stumbled because the rotation always done around the center of the image. With 512x512 pixels the rotation center should be around point (x,y) 128,128. How can I rotate the image with a custom rotation center, let's say around (x,y) 20,128?

解决方案

If OpenCV is not an option, you can do image rotation around a so called pivot point with NumPy (import numpy as np) and SciPy (from scipy import ndimage) the following way:

Pad the image img such that the pivot point is in the image center and the image size is doubled:

padX = [img.shape[1] - pivot[0], pivot[0]]

padY = [img.shape[0] - pivot[1], pivot[1]]

imgP = np.pad(img, [padY, padX], 'constant')

(While the image shape is in row-column order, pivot is in X-Y or column-row order here. You might want to define it differently.)

Rotate the image around its center (here the rotation angle is 45 degrees):

imgR = ndimage.rotate(imgP, 45, reshape=False)

Note that we disallow reshaping the image, since we'll crop the image ourselves.

Crop the image such that the pivot point is at its original position. Therefore, we simply reverse the padding from step 1:

imgC = imgR[padY[0] : -padY[1], padX[0] : -padX[1]]

You can see the different steps in the following plot (original image, padded, rotated, cropped; 45 degrees around (100, 300)).

aRlmf.png

Wrapping it up in a handy function yields:

def rotateImage(img, angle, pivot):

padX = [img.shape[1] - pivot[0], pivot[0]]

padY = [img.shape[0] - pivot[1], pivot[1]]

imgP = np.pad(img, [padY, padX], 'constant')

imgR = ndimage.rotate(imgP, angle, reshape=False)

return imgR[padY[0] : -padY[1], padX[0] : -padX[1]]

Update

For colored images you'd have to avoid adding more channels while padding (zero padding in 3rd dimension):

imgP = np.pad(img, [padY, padX, [0, 0]], 'constant')

Don't forget to use a 0 for both "before" and "after" padding. Otherwise you get a ValueError.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值