使用OpenCV对旋转矩形区域的内容进行裁剪

知道旋转矩形四个顶点的坐标,如何用opencv实现旋转矩形的裁剪


再做OCR的时候,我想单独把矩形的区域裁剪出来,因此对这个问题进行了一些探索,最后得到的具体步骤如下:

  • 使用cv2.minAreaRect()函数获取旋转矩形的中心点、宽度、高度和旋转角度信息。
  • 使用cv2.getRotationMatrix2D()函数获取旋转矩阵。
  • 使用cv2.warpAffine()函数根据旋转矩阵进行旋转。
  • 使用cv2.getRectSubPix()函数将旋转矩形区域裁剪出来
def crop(image,pos,show=False):
    points = np.array(pos,dtype="int32")
    # 获取旋转矩形的中心点、宽度、高度和旋转角度信息
    rect = cv2.minAreaRect(points)
    center, size, angle = rect
    print(angle)
    print(image.shape)
    # 获取旋转矩阵
    rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1)

    # 根据旋转矩阵进行旋转
    rotated_image = cv2.warpAffine(image, rotation_matrix, (image.shape[1],image.shape[0]))

    # 将旋转矩形区域裁剪出来
    cropped_image = cv2.getRectSubPix(rotated_image, tuple(map(lambda x:int(x),size)), tuple(map(lambda x:int(x),center)))
    
    
    if show:
        plt.figure(dpi=100)
        plt.subplot(1,3,1)
        plt.imshow(image)
        plt.axis('off')
        
        plt.subplot(1,3,2)
        plt.imshow(rotated_image)
        plt.axis('off')
        
        plt.subplot(1,3,3)
        plt.imshow(cropped_image)
        plt.axis('off')
        
        plt.show()
    return cropped_image
    
crop(img,result[12][0],show=True)
#[[332.0, 75.0], [432.0, 95.0], [422.0, 146.0], [322.0, 127.0]]

输出结果如下:

达到了我们的目的

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年7月15日
下一篇 2023年7月16日

相关推荐