python opencv

本文介绍如何使用OpenCV库处理图片,包括通过旋转矩阵裁剪图片中的旋转矩形区域,以及应用透视变换将任意四边形转换为长方形。详细展示了计算旋转和透视变换参数的方法,并提供了具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 获得图片中某一块旋转矩形区域

1.1 将原始图片旋转到水平矩形位置进行裁剪

M = cv2.getRotationMatrix2D((x_center, y_center), float(theta)*180/math.pi, 1)
cols,rows,_ = img.shape
dst = cv2.warpAffine(img, M, (rows,cols))
crop_img = dst[y0:y0 + int(hight),x0:x0 + int(width)]

1.2 采用透视变换

可以用来变换任意四边形到一个长方形

height_left = int(np.sqrt(np.power(x1-x4,2) + np.power(y1-y4,2)))
height_right = int(np.sqrt(np.power(x3-x2,2) + np.power(y3-y2,2)))
width_top = int(np.sqrt(np.power(x1-x2,2)+np.power(y1-y2,2)))
width_bottom = int(np.sqrt(np.power(x3-x4,2)+np.power(y3-y4,2)))
max_height = max(height_left, height_right)
max_width = max(width_top, width_bottom)
orig_coord = np.float32([[x1,y1], [x2,y2], [x3,y3], [x4,y4]])
res_coord = np.float32([[0, 0], [max_width, 0],\
    [max_width, max_height], [0, max_height]])
bound = cv2.getPerspectiveTransform(orig_coord, res_coord)
box = cv2.warpPerspective(img, bound,(max_width, max_height))

cv2.imwrite(os.path.join(cropDir, boxName), box)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值