zoukankan      html  css  js  c++  java
  • 探究cv2.findContours函数找到的轮廓

    源图片:

    实验1.直接findContours:

    import cv2
    
    img = cv2.imread('lala.png', 0)
    # img = img[100:, :]
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    print(len(contours))
    colored_img = cv2.imread('lala.png')
    # colored_img = colored_img[100:, :, :]
    for i in range(len(contours)):
        cv2.drawContours(colored_img, contours, i, (255, 255, 0), 5)
        cv2.imshow('contour-%d'%i, colored_img)
        cv2.waitKey()
        colored_img = cv2.imread('lala.png')
        # colored_img = colored_img[100:, :, :]
    cv2.destroyAllWindows()
    

    结果如下图所示,值得注意的是整张图片的框也算进轮廓里:

    实验2.截取部分图片findContours(取消上述代码的注释)

    结果图示,基本同实验1:

    实验3.先使用Canny算法得到边缘图,找边缘图中的轮廓。

    import cv2
    
    img = cv2.imread('lala.png', 0)
    # img = img[100:, :]
    img = cv2.Canny(img, 10, 20)
    cv2.imshow('canny', img)
    contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    print(len(contours))
    colored_img = cv2.imread('lala.png')
    # colored_img = colored_img[100:, :, :]
    for i in range(len(contours)):
        cv2.drawContours(colored_img, contours, i, (255, 255, 0), 5)
        cv2.imshow('contour-%d'%i, colored_img)
        cv2.waitKey()
        colored_img = cv2.imread('lala.png')
        # colored_img = colored_img[100:, :, :]
    cv2.destroyAllWindows()
    

    结果如图所示,我认为2和3边缘并不密封,有一些小缺口导致其内轮廓和外轮廓连成一条轮廓,于是不像1那样分别展示的是内轮廓和外轮廓,另由于Canny提取的边缘很细,内轮廓和外轮廓基本上是一条线。

    实验4.1的内轮廓和外轮廓是否基本是一条线

    import numpy as np
    print(len(contours[3]), len(contours[4]), len(np.unique(np.concatenate((contours[3], contours[4])), axis=0)))
    

    结果:209 205 217
    209+205-217=197可见内轮廓和外轮廓的大部分点都是重合的。

    实验5.Canny提取部分图像的边缘

    结果如图所示:

  • 相关阅读:
    virtualenv -- python虚拟沙盒
    python 多继承详解
    GCDAsyncSocket类库,IOS下TCP通讯使用心得
    TCP长连接与短连接的区别
    SOCKET类型定义及应用
    Ubuntu增加Swap分区大小
    log4j使用说明
    maven资料
    资料推荐
    Idea操作与问题解决
  • 原文地址:https://www.cnblogs.com/tellw/p/12956584.html
Copyright © 2011-2022 走看看