import cv2import numpy as npfrom skimage.measure import find_contoursimg_path = "D://001.jpg"img_bgr = cv2.imread(img_path) #读取图像rows = img_bgr.shape[0] #图像的宽度cols = img_bgr.shape[1] #图像的长度img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) #转为灰度图_, thres = cv2.threshold(img_gray, 80, 255, cv2.THRESH_BINARY) #阈值二值化cv2.imwrite("D://001_thres.jpg", thres) #保存阈值化后的图mask = np.zeros((rows, cols), dtype=np.uint8)mask[:, :] = np.where(thres[:, :] == 0, 0, 1) #构建二值图掩码contours = find_contours(mask, 0.5) #寻找二值图的轮廓verts = np.fliplr(contours[0]) - 1 #物体的外轮廓通常是最长的一个,这里只找物体的外轮廓for k in range(len(verts) - 1): spos = (int(verts[k][0]), int(verts[k][1])) epos = (int(verts[k + 1][0]), int(verts[k + 1][1])) cv2.line(img_bgr, spos, epos, (0, 0, 255), 2) #将外轮廓用红色的线绘制到原图上 cv2.imwrite("D://001_contour.jpg", img_bgr) #保存绘制了红色外轮廓的图
每步的效果图如下:原图二值化图绘制红色轮廓后的图涉及的函数介绍:(图片来源网络,侵删)
0 评论