如何在opencv中使用python将不规则图形轮廓括起来并用5px点填充?

2024-04-24 12:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的

Input Image

我想要这个

Output Image

但问题是我不能把轮廓围起来,我应该如何添加这些点? Open cv是否具有处理此问题的功能? 所以基本上, 第一个问题是如何将此图像括起来 第二,如何添加点

多谢各位


Tags: 图像功能opencv轮廓
1条回答
网友
1楼 · 发布于 2024-04-24 12:30:22

在Python/OpenCV中有一种方法可以做到这一点。但是,如果不连接单独的区域,我无法关闭虚线轮廓。但它会让你知道如何继续做你想做的大部分事情

如果在有较大间隙的输入图像中手动添加更多的点,则形态学内核可以变小,以便它可以连接区域,而无需合并应保持隔离的单独部分

  • 读取输入
  • 转换为灰度
  • 二进制阈值
  • 应用形态学关闭以尝试关闭虚线轮廓。不幸的是,它连接了不同的区域
  • 获取外部轮廓
  • 在黑色背景上绘制白色填充轮廓作为遮罩
  • 在白色背景上画一个黑色圆圈
  • 将圆形图像平铺到输入的大小
  • 使用填充轮廓图像遮罩平铺圆图像
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np
import math

# read input image
img = cv2.imread('island.png')
hh, ww = img.shape[:2]

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold 
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# use morphology to close figure
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (35,35))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, )

# find contours and bounding boxes
mask = np.zeros_like(thresh)
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cntr in contours:
    cv2.drawContours(mask, [cntr], 0, 255, -1)

# create a single tile as black circle on white background
circle = np.full((11,11), 255, dtype=np.uint8)
circle = cv2.circle(circle, (7,7), 3, 0, -1)

# tile out the tile pattern to the size of the input
numht = math.ceil(hh / 11)
numwd = math.ceil(ww / 11)
tiled_circle = np.tile(circle, (numht,numwd))
tiled_circle = tiled_circle[0:hh, 0:ww]

# composite tiled_circle with mask
result = cv2.bitwise_and(tiled_circle, tiled_circle, mask=mask)

# save result
cv2.imwrite("island_morph.jpg", morph)
cv2.imwrite("island_mask.jpg", mask)
cv2.imwrite("tiled_circle.jpg", tiled_circle)
cv2.imwrite("island_result.jpg", result)

# show images
cv2.imshow("morph", morph)
cv2.imshow("mask", mask)
cv2.imshow("tiled_circle", tiled_circle)
cv2.imshow("result", result)
cv2.waitKey(0)

形态学连接图像:

enter image description here

轮廓遮罩图像:

enter image description here

平铺圆:

enter image description here

结果:

enter image description here

相关问题 更多 >