16.OpenCV的图像轮廓——绘制轮廓
前言
图像轮廓是指由位于边缘、连续的、具有相同颜色和强度的点构成的曲线,它可以用于形状分析以及对象检测和识别。
一、绘制轮廓
cv2.drawContours()函数用于绘制图像轮廓,其基本格式如下:
imgae = cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLeve[, offset]]]]])
imgae为在其中绘制轮廓的图像
contours为要绘制的的轮廓
contourIdx为要绘制的轮廓的索引, 大于或等于0时绘制对应的轮廓, 负数(通常为-1)表示绘制所有轮廓
color为轮廓的颜色, 颜色为BGR格式
thickness为可选参数, 表示绘制轮廓时画笔的粗细
lineType为可选参数, 表示绘制轮廓时使用的线型
hierarchy为可选参数, 对应cv2.findContours()函数返回的轮廓层次
offset为可选参数, 表示绘制轮廓的偏移位置
img = cv2.imread('bee.jpg')
cv2.imshow('originag', img)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', img_gray)
ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)
cv2.imshow('threshold', thresh)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_L1)
img2 = np.zeros((img.shape[0], img.shape[1], 3), np.uint8) + 255
img2 = cv2.drawContours(img2, contours, -1, (0,0,0), 2)
cv2.imshow('Contours', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
二、OpenCV-Python资源下载
OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码
总结
以上内容介绍了OpenCV-Python的绘制轮廓操作,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。