过程图解
第一步
读取要进行处理的原图:
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()