python - 填充一个轮廓的圆圈
问题描述
我有一组图像,其中一个圆圈绘制为白色轮廓。但是,我想用白色填充整个圆圈。什么是快速的方法?以下是图像示例:
我曾尝试使用嵌套循环来实现这一点,但这需要很长时间,而且我有大约 150 万张图像。以下是我的代码:
roundRobinIndex = 0
new_image = np.zeros((img_w, img_h))
for row in range(540):
for column in range(800):
if image[row,column] == 255:
roundRobinIndex = (roundRobinIndex + 1) % 2
if roundRobinIndex == 1:
new_image[row, column] = 255
解决方案
用于cv2.fillPoly()
填充圆形轮廓
import cv2
image = cv2.imread('1.png', 0)
thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cv2.fillPoly(image, cnts, [255,255,255])
cv2.imshow('image', image)
cv2.waitKey()
注意:由于输入图像已经是二值图像,可以去除 Otsu 的阈值以获得稍快的性能,您可以直接在灰度图像上找到轮廓
推荐阅读
- css - 将桌面中的多列转换为移动视图中的 2 列
- python - fig.set_figheight 和 fig.set_figwidth 不起作用
- c# - 带有两个表格的报告查看器
- swift - 为什么以这种方式使用 Alamofire 时没有发现任何价值?
- python - 使用适当的缓存和版本控制从 repo 安装 pip
- r - 反转 tidyverse 函数
- pytorch - 为什么 pytorch 的 F.sigmoid 中没有就地标志?
- c# - 如何在 sitecore RSS 提要中获取媒体链接
- node.js - 在 Storage 中获取图片 downloadURL 并将其保存在 Firestore 中
- r - 如何将 geom_smooth() 与 gganimate 一起使用