python用opencv实现图像旋转_如何在python中使用opencv拉直图像的旋转矩形区域?

本文介绍如何使用Python的OpenCV库围绕指定中心旋转图像,并根据需要裁剪旋转后的图像。通过调用`cv2.getRotationMatrix2D`创建旋转矩阵,然后应用`cv2.warpAffine`进行旋转,最后根据提供的宽度和高度进行裁剪。示例代码展示了读取图像,执行旋转和裁剪,并保存结果的操作。
摘要由CSDN通过智能技术生成

可以使用^{}函数围绕定义的中心点旋转图像。可以使用^{}(其中theta在度中)生成合适的旋转矩阵。

import cv2

import numpy as np

def subimage(image, center, theta, width, height):

'''

Rotates OpenCV image around center with angle theta (in deg)

then crops the image according to width and height.

'''

# Uncomment for theta in radians

#theta *= 180/np.pi

shape = ( image.shape[1], image.shape[0] ) # cv2.warpAffine expects shape in (length, height)

matrix = cv2.getRotationMatrix2D( center=center, angle=theta, scale=1 )

image = cv2.warpAffine( src=image, M=matrix, dsize=shape )

x = int( center[0] - width/2 )

y = int( center[1] - height/2 )

image = image[ y:y+height, x:x+width ]

return image

记住dsize是输出图像的形状。如果面片/角度足够大,如果使用原始形状(为了简单起见)执行上述操作,则边缘将被截断(比较上面的图像)。在这种情况下,可以将缩放因子引入到shape(放大输出图像)和切片的参考点(这里是center)。

上述功能可以使用如下:image = cv2.imread('owl.jpg')

image = subimage(image, center=(110, 125), theta=30, width=100, height=200)

cv2.imwrite('patch.jpg', image)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值