原图:
效果图:
代码:
'''
画出轮廓
'''
import cv2
import os
src_path = './Fold_1/masks/fold1/change_background/'#源文件路径
save_path = './Fold_1/masks/fold1/edge/'#保存路径
img_ids = sorted(os.listdir(src_path))#给文件排序,方便取出名字
print(len(img_ids))
for img_id in img_ids:
dataFile = src_path + img_id # 单个的文件
img = cv2.imread(dataFile,1)
# cv2.imshow('src',img)
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转换成灰度图
ret,thresh = cv2.threshold(img_gray,127,255,0)#设定阈值
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# cv2.imshow('image',image)
image = (image > 0)*0.#只保留轮廓,如果需要连轮廓内部也保留,则去掉这一行
cv2.drawContours(image,contours,contourIdx=-1,color=(255,255,255),thickness=2)
# cv2.imshow('contours',image)
cv2.imwrite(save_path+img_id,image)
if cv2.waitKey(0)&0xFF == 27:#按ESC键退出
cv2.destroyAllWindows()
其中,cv2.drawContours()函数里,color=(255,255,255)表示轮廓颜色是白色,thickness表示轮廓粗细。