本文介绍了如何使用python在opencv中封闭不规则图形轮廓并用5px点填充它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的

我想要这个

但是问题是我无法封闭轮廓,应该如何添加这些点?Open cv是否具有任何此类功能来处理此问题?所以基本上第一个问题是如何封闭该图像其次,如何添加点.

but the problem is I am not able to enclose the contour and how should I add these dots?Does Open cv have any such function to handle this?So basically,The first problem is how to enclose this imageSecond, how to add Dots.

谢谢

推荐答案

这是在Python/OpenCV中执行此操作的一种方法.但是,如果不连接单独的区域,则无法关闭虚线轮廓.但这会给您一些思路,让您继续进行大部分的操作.

Here is one way to do that in Python/OpenCV. However, I cannot close your dotted outline without connecting separate regions. But it will give you some idea how to proceed with most of what you want to do.

如果在输入图像中存在较大间隙的位置上手动添加一些点,则可以使形态内核更小,以便可以连接区域而无需合并应保持隔离的单独部分.

If you manually add a few more dots to your input image where there are large gaps, then the morphology kernel can be made smaller such that it can connected the regions without merging separate parts that should remain isolated.

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

输入:

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)

形态连接图像:

轮廓蒙版图像:

倾斜的圈子:

结果:

这篇关于如何使用python在opencv中封闭不规则图形轮廓并用5px点填充它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 14:17