gpt4 book ai didi

python - minAreaRect OpenCV [Python] 返回的裁剪矩形

转载 作者:太空狗 更新时间:2023-10-29 18:13:33 45 4
gpt4 key购买 nike

OpenCV 中的

minAreaRect 返回一个旋转的矩形。如何裁剪矩形内的这部分图像?

boxPoints 返回旋转矩形角点的坐标,因此可以通过循环遍历框内的点来访问像素,但是在 Python 中是否有更快的裁剪方法?

编辑

请参阅下面我的回答中的代码

最佳答案

这里是执行此任务的函数:

import cv2
import numpy as np

def crop_minAreaRect(img, rect):

# rotate img
angle = rect[2]
rows,cols = img.shape[0], img.shape[1]
M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
img_rot = cv2.warpAffine(img,M,(cols,rows))

# rotate bounding box
rect0 = (rect[0], rect[1], 0.0)
box = cv2.boxPoints(rect0)
pts = np.int0(cv2.transform(np.array([box]), M))[0]
pts[pts < 0] = 0

# crop
img_crop = img_rot[pts[1][1]:pts[0][1],
pts[1][0]:pts[2][0]]

return img_crop

这里是一个例子

# generate image
img = np.zeros((1000, 1000), dtype=np.uint8)
img = cv2.line(img,(400,400),(511,511),1,120)
img = cv2.line(img,(300,300),(700,500),1,120)

# find contours / rectangle
_,contours,_ = cv2.findContours(img, 1, 1)
rect = cv2.minAreaRect(contours[0])

# crop
img_croped = crop_minAreaRect(img, rect)

# show
import matplotlib.pylab as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(img)
plt.subplot(1,2,2)
plt.imshow(img_croped)
plt.show()

这是输出

original and croped image

关于python - minAreaRect OpenCV [Python] 返回的裁剪矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37177811/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com