步骤
- 读取图像为灰度图像。
- 使用cv2.threshold()函数获取阈值图像。
- 使用cv2.findContours()并传递阈值图像和必要的参数。
- findContours()返回轮廓。您可以将其绘制在原始图像或空白图像上。
import cv2 import numpy as np img = cv2.imread('original.png', cv2.IMREAD_UNCHANGED) #convert img to grey img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #set a thresh thresh = 100 #get threshold image ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY) #find contours img2, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #create an empty image for contours img_contours = np.zeros(img.shape) # draw the contours on the empty image cv2.drawContours(img_contours, contours, -1, (0,255,0), 3) #save image cv2.imwrite('contours.png',img_contours) import cv2 import numpy as np img = cv2.imread('original.png', cv2.IMREAD_UNCHANGED) #convert img to grey img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #set a thresh thresh = 100 #get threshold image ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY) #find contours img2, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #create an empty image for contours img_contours = np.zeros(img.shape) # draw the contours on the empty image cv2.drawContours(img_contours, contours, -1, (0,255,0), 3) #save image cv2.imwrite('contours.png',img_contours)
原图
输出图