python - 包围图像的所有黑色像素的最小角度矩形
问题描述
我需要获得包含图像所有黑色像素的最小角度矩形。
目标图像是扫描的单色漫画/漫画页面,可以在任何位置(平移和旋转)。
当连接所有黑色像素时,所需的结果类似于以下代码段:
_, 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 做到这一点?
解决方案
要使用 找到的轮廓来保持您的想法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
----------------------------------------
推荐阅读
- python - ValueError:层顺序的输入 0 与层不兼容(神经网络)
- amazon-web-services - 我如何使用 Aws amplify 和 s3 存储私下存储项目,但允许管理员访问所有文件
- python - 如何根据满足特定条件的列过滤多索引数据框?
- python - 用于 POST 的 Django API 框架不起作用?
- java - System.out.println("帮助" + 帮助);
- plasticscm - 复制 Plastic Cloud Repo
- flutter - 如何为 google_maps_flutter 设置缩放级别
- jenkins - 如何在 jenkins 中不使用 smtp 服务器发送邮件
- php - 如何获取所有对象记录列表
- stream - 如何在scala的BroadcastProcessFunction中使用Map?