首页 > 解决方案 > 包围图像的所有黑色像素的最小角度矩形

问题描述

我需要获得包含图像所有黑色像素的最小角度矩形。

目标图像是扫描的单色漫画/漫画页面,可以在任何位置(平移和旋转)。

当连接所有黑色像素时,所需的结果类似于以下代码段:

_, mono = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(255-mono, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0])

换句话说,我需要得到minAreaRect所有轮廓的并集,而不仅仅是其中一个。

我怎样才能使用 Python OpenCV 做到这一点?

标签: pythonpython-3.xopencv

解决方案


要使用 找到的轮廓来保持您的想法cv2.findContours,您只需合并所有轮廓,例如使用np.vstack. 由于您只需要 的普通坐标cv2.minAreaRect,因此合并它们应该没问题。要获得旋转矩形的四个顶点,请使用cv2.boxPoints. 最后,绘图可以用cv2.polylines.

这是一些带有最小示例的简短代码片段:

import cv2
import numpy as np

# Some test image
image = 255 * np.ones((300, 300), np.uint8)
cv2.circle(image, (100, 60), 30, 0, 1)
cv2.circle(image, (200, 200), 60, 0, 1)

# Find contours (with respect to OpenCV version); merge them
cnts = cv2.findContours(255-image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = np.vstack(cnts)

# Calculate minAreaRect of merged contours; determine points
pts = np.int32(cv2.boxPoints(cv2.minAreaRect(cnts)))
cv2.polylines(image, [pts], True, 192)

cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

那将是图像:

输出

希望有帮助!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
OpenCV:      4.1.2
----------------------------------------

推荐阅读