過程圖解
第一步
讀取要進行處理的原圖:
origin_pic = './pic/6.jpg' save_folder = './generated_pics' img = cv2.imread(origin_pic)
此時原圖如下:
第二步
將原圖轉換成單通道圖(例如本例中用cv2.cvtColor
轉換成灰度圖):
imgray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)
轉換後的單通道圖如下:
第三步
對得到的單通道圖進行閥值處理:
_, thresh = cv2.threshold(src=imgray, thresh=150, maxval=200, type=0)
得到閥值圖片如下:
第四步
尋找輪廓並記錄在返回的 contours列表
中:
image, contours, _1 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
第五步
根據輪廓數據表,在三通道彩色圖片上繪製輪廓:
contoured_colored_img = cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
結果圖如下:
也可以在黑白三通道圖片上繪製輪廓:
thresh_expanded = np.expand_dims(thresh, axis=2) gray_img = np.concatenate([thresh_expanded, thresh_expanded, thresh_expanded], axis=2) contoured_gray_img = cv2.drawContours(gray_img, contours, -1, (0, 0, 255), 2)
結果圖如下:
完整源碼
我自己寫的完整源碼如下:
# coding=utf-8 import numpy as np import cv2 origin_pic = './pic/6.jpg' save_folder = './generated_pics' import shutil try: shutil.rmtree(save_folder) except OSError: pass import os os.makedirs(save_folder) img = cv2.imread(origin_pic) imgray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(src=imgray, thresh=150, maxval=200, type=0) image, contours, _1 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) thresh_expanded = np.expand_dims(thresh, axis=2) gray_img = np.concatenate([thresh_expanded, thresh_expanded, thresh_expanded], axis=2) contoured_gray_img = cv2.drawContours(gray_img, contours, -1, (0, 0, 255), 2) contoured_colored_img = cv2.drawContours(img, contours, -1, (0, 0, 255), 2) cv2.imwrite(os.path.join(save_folder, 'imgray.jpg'), imgray) cv2.imshow('imgray', imgray) cv2.waitKey(2000) cv2.imwrite(os.path.join(save_folder, 'thresh.jpg'), thresh) cv2.imshow('thresh', thresh) cv2.waitKey(2000) cv2.imwrite(os.path.join(save_folder, 'image.jpg'), image) cv2.imshow('image', image) cv2.waitKey(2000) cv2.imwrite(os.path.join(save_folder, 'contoured_gray_img.jpg'), contoured_gray_img) cv2.imshow('contoured_gray_img', contoured_gray_img) cv2.waitKey(2000) cv2.imwrite(os.path.join(save_folder, 'contoured_colored_img.jpg'), contoured_colored_img) cv2.imshow('', contoured_colored_img) cv2.waitKey(2000) cv2.destroyAllWindows()