代码之家  ›  专栏  ›  技术社区  ›  Whoami

无法正确获取轮廓

  •  1
  • Whoami  · 技术社区  · 6 年前

    我正在玩opencv并做下面的简单任务。

    1)读取图像

    2)阈值

    3)寻找轮廓。

    4)在空白图像中绘制所有轮廓。

    5)绘制单个轮廓。

    在虚拟图像上绘制所有等高线看起来不错,而绘制单个等高线会生成分散的等高线,如下图所示。

    原件:

    enter image description here

    所有轮廓:

    enter image description here

    单轮廓:

    enter image description here

    请在下面找到代码。

    import  cv2
    import numpy as np
    
    #Reading Image.
    srcImg = cv2.imread("./bottle.jpeg")
    
    #Color Conversion.
    
    grayedImg = cv2.cvtColor(srcImg,cv2.COLOR_RGB2GRAY)
    __, thresholdedImg = cv2.threshold(grayedImg, 240, 255, cv2.THRESH_BINARY)
    
    #Noice Removal
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    erodeImage = cv2.erode(thresholdedImg,kernel, iterations=1)
    dilatedImg = cv2.dilate(erodeImage,kernel, iterations=1)
    _, contours, _ = cv2.findContours(dilatedImg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    
    #draw All Contours.
    
    dummyImg = np.zeros(grayedImg.shape, dtype=grayedImg.dtype)
    cv2.drawContours(dummyImg, contours, -1, 255, 1)
    cv2.imshow("All Contours", dummyImg)
    cv2.imwrite("allContours.jpeg",dummyImg)
    
    #draw Individual Contours.
    
    mask =  np.zeros(dummyImg.shape[:2], dtype= dummyImg.dtype)
    isolatedImg = cv2.drawContours(mask, contours[9], -1, 255, 1)
    
    cv2.imshow("Indivial Contours.", isolatedImg)
    cv2.imwrite("single.jpeg",isolatedImg)
    
    cv2.waitKey(0)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Jeru Luke    6 年前

    您必须将另一组方括号括起来:

    isolatedImg = cv2.drawContours(mask, [contours[9]], -1, 255, 1)
    

    预期结果:

    enter image description here

    如果你挖深, cv2.findContours() 返回A list 数组的现在每个 array 包含关于构成轮廓的点的数量的细节。