gpt4 book ai didi

python - 使用OpenCV获取外部轮廓(Python)

转载 作者:行者123 更新时间:2023-12-02 17:34:13 25 4
gpt4 key购买 nike

我正在尝试使用opencv和python获取图像的外部轮廓。

我在这里(Process image to find external contour)找到了解决此问题的方法,但是该方法对我不起作用-代替轮廓图像,它打开了两个新图像(一个全为黑色,另一个为黑白)。

这是我正在使用的代码:

import cv2 # Import OpenCV
import numpy as np # Import NumPy

# Read in the image as grayscale - Note the 0 flag
im = cv2.imread("img.jpg", 0)

# Run findContours - Note the RETR_EXTERNAL flag
# Also, we want to find the best contour possible with CHAIN_APPROX_NONE
_ ,contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Create an output of all zeroes that has the same shape as the input
# image
out = np.zeros_like(im)

# On this output, draw all of the contours that we have detected
# in white, and set the thickness to be 3 pixels
cv2.drawContours(out, contours, -1, 255, 3)

# Spawn new windows that shows us the donut
# (in grayscale) and the detected contour
cv2.imshow('Donut', im)
cv2.imshow('Output Contour', out)

# Wait indefinitely until you push a key. Once you do, close the windows
cv2.waitKey(0)
cv2.destroyAllWindows()

该图显示了我得到的两个窗口而不是轮廓。

enter code here

最佳答案

您正在犯一些会损害结果的错误。从documentation中读取的内容是:

  • 为了获得更高的准确性,请使用二进制图像(请参阅步骤3)。
  • 查找轮廓就像从黑色背景中查找白色物体(请参见步骤2)。

  • 您不遵守这些规则,因此不会获得良好的结果。另外,您正在将结果绘制为黑色图像,并且不可见。

    以下是针对您的案例的完整解决方案。

    我也使用 adaptive threshold以获得更好的结果。
    # Step 1: Read in the image as grayscale - Note the 0 flag
    im = cv2.imread("/home/jorge/Downloads/input.jpg", 0)
    cv2.imshow('Original', im)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # Step 2: Inverse the image to get black background
    im2 = im.copy()
    im2 = 255 - im2
    cv2.imshow('Inverse', im2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # Step 3: Get an adaptive binary image
    im3 = cv2.adaptiveThreshold(im2, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
    cv2.imshow('Inverse_binary', im3)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # Step 4: find contours
    _, contours, hierarchy = cv2.findContours(im3.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    # Step 5: This creates a white image instead of a black one to plot contours being black
    out = 255*np.ones_like(im)
    cv2.drawContours(out, contours, -1, (0, 255, 0), 3)
    cv2.drawContours(im, contours, -1, (0, 255, 0))

    关于python - 使用OpenCV获取外部轮廓(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880993/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com