探究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提取部分圖像的邊緣

結果如圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM