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

标签 python image opencv image-processing

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/

相关文章:

c++ - 使用 OpenCV 和 OpenNI 测量两点之间的距离

python - SQLAlchemy 更新值时无法设置属性错误

python - 生物信息学 - "global name ' start'未定义”?

python - 我需要在 Kfold 循环中重置模型权重吗?

ios - Instagram 自动发布或通过第三方应用程序在 IOS 中一键分享

css - 如何在 div 元素内垂直居中图像?

java - 如何从 Java 服务器端发送图像,并在 JQuery 客户端处理它

在全局声明之前使用的 Python 3 SyntaxWarning 变量

c++ - OpenCV 构建正常,调试抛出错误,从 .exe 运行正常

c++ - OpenCV - 按宽度和高度过滤 Blob