【问题标题】:How can I draw two contours on an image given a contour distance of 100 pixels between them using python and opencv如何使用python和opencv在图像上绘制两个轮廓,它们之间的轮廓距离为100像素
【发布时间】:2020-02-14 10:42:54
【问题描述】:

我尝试的是使用以下几行绘制外部轮廓

cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(orig, cnts, -1, (0, 255, 0), 3) # this draws the external contour

参考以下 [![在此处输入图片描述][1]][1]

我怎样才能得到下面的答案?

[![在此处输入图片描述][2]][2]

【问题讨论】:

标签: python opencv


【解决方案1】:

我不知道它是如何在链接中解决的,但您可以使用空白蒙版在其上绘制轮廓,然后使用 cv2.dilate 使用所需像素数的内核大小来扩展它他们。完成后,在蒙版上找到轮廓并将第二个轮廓绘制到原始图像上。

import cv2
import numpy as np

img = cv2.imread('contour.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, cnts, -1, (0, 255, 0), 3)
mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.drawContours(mask, cnts, -1, 255, 1)
kernel = np.ones((100, 100), np.uint8)
mask = cv2.dilate(mask, kernel, iterations = 1)
cnts, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, cnts, 1, (255, 0, 0), 3)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

  • 感谢您的解决方案,但我仍有一些问题要问。我怎样才能平滑两个轮廓? @Vardan Agarwal
  • 抱歉,我没有完全理解平滑的意思。我猜你不希望有这样的锯齿状边缘,你可以简单地应用模糊。
  • 我应用了去毛刺,但结果看起来与上面的结果相似?当然,那些锯齿状的线条/边缘应该是清晰的(没有噪音)
猜你喜欢
  • 1970-01-01
  • 2019-02-12
  • 2021-09-07
  • 2014-03-20
  • 1970-01-01
  • 2017-06-09
  • 2020-11-24
  • 1970-01-01
  • 2012-11-06
相关资源
最近更新 更多