【问题标题】:cv2.drawContours doesn't display all the contourscv2.drawContours 不显示所有轮廓
【发布时间】:2021-07-19 04:15:00
【问题描述】:

我有一个图像,我想使用 cv.drawContours 显示所有轮廓,但它错过了两个重叠单元格之间的一个,即使 cv2.Canny 清楚地显示了所有轮廓,我也不知道为什么。 这是我使用的代码:

import cv2
import imageio
from skimage import io, color
import numpy as np
from google.colab.patches import cv2_imshow


image = imageio.imread(path+'3.png')
print(image.shape)
image = color.gray2rgb(image)
print(image.shape)

cv2_imshow(image)
cv2.waitKey(0)

# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)

# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged.copy(),
    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

cv2_imshow(edged)
cv2.waitKey(0)

print("Number of Contours found = " + str(len(contours)))

# Draw all contours
# -1 signifies drawing all contours
img2=cv2.drawContours(image, contours, -1, (100,0,0), 2)
print(len(contours))
print(img2.shape)
cv2_imshow(image)
cv2.waitKey(0)
cv2.destroyAllWindows()

这是输入图像:input image,这是精巧磨边后的图像edged,这是 img2 在 cv2.drawCONtours img2 之后的最终图像,你可以看到它错过了 2 之间的轮廓中间有重叠的单元格。如果您能帮我解决这个问题,我将不胜感激。

【问题讨论】:

  • canny也有差距。我不明白这个问题。

标签: python opencv


【解决方案1】:

尝试将 cv2.RETR_EXTERNAL 更改为 cv2.RETR_TREE

(我也建议你少用依赖)

import cv2
import numpy as np

image = cv2.imread('d:/python/X9S40.png')
cv2.imshow("",image)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Find Canny edges
edged = cv2.Canny(gray, 30, 200)

# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged.copy(),
    cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

cv2.imshow("1",edged)

print("Number of Contours found = " + str(len(contours)))

# Draw all contours
# -1 signifies drawing all contours
img2=cv2.drawContours(image, contours, -1, (0,255,0), 2)
print(len(contours))
print(img2.shape)
cv2.imshow("2",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多