Rich's Wordpress

又一个WordPress站点

OpenCV 6: Contours

Choose an image:

import cv2 as cv
import numpy as np

img = cv.imread('/Users/richzha/Desktop/CV/Image/Cat.jpg')

cv.imshow('Image', img)

Method 1: Canny Edges

# Method 1:
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

blur = cv.GaussianBlur(gray, (5,5), cv.BORDER_DEFAULT)
cv.imshow('Blur', blur)

canny = cv.Canny(blur, 125,175)
cv.imshow('Canny Edges', canny)

contours, hierarchies = cv.findContours(canny, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
print(f'{len(contours)} contours found')

Method 2: Threshold & Contours

# Method 2:

blank = np.zeros(img.shape, dtype='uint8')
cv.imshow('Blank', blank)

ret, thresh = cv.threshold(gray, 125, 255, cv.THRESH_BINARY)
cv.imshow('Thresh', thresh)

contours, hierarchies = cv.findContours(thresh, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
print(f'{len(contours)} contours found')

cv.drawContours(blank, contours, -1, (0,0,255), 1)
cv.imshow('Contours Drawn', blank)

cv.waitKey(0)
OpenCV 6: Contours
Scroll to top