Opencv学习笔记(十)轮廓特征、轮廓近似

文章目录


轮廓特征包括面积、周长、重心、 边界框的等。
轮廓近似和凸包可以检测曲线是否具有凸性缺陷。凸性曲线是凸出来的曲线,如果某些部分凹进去作为凸性缺陷。

代码

import cv2
from matplotlib import pyplot as plt

src = cv2.imread(r'F:\OPENCV\Opencv\test2.png', cv2.IMREAD_COLOR)
if src is None:
    print('image is null')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(~thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
# CV2.moments()计算轮廓的矩,以字典的形式返回,利用矩可以得到图像的周长、面积、质心等
M = cv2.moments(cnt)
print(M)
print(M['m00'])  # M['m00']为轮廓的面积
# cv2.contourArea()也可以计算轮廓的面积
area = cv2.contourArea(cnt)
print(area)
# cv2.arcLength()计算轮廓的周长,第二个参数为True表示轮廓形状时闭合的,False表示为开放的曲线
perimeter = cv2.arcLength(cnt, True)
print(perimeter)

# 轮廓近似
img1 = src.copy()
epslion1 = 0.05 * perimeter
approx1 = cv2.approxPolyDP(cnt, epslion1, True)
img1 = cv2.drawContours(img1, [approx1], 0, (0, 0, 255), 2)

img2 = src.copy()
epslion2 = 0.01 * perimeter
approx2 = cv2.approxPolyDP(cnt, epslion2, True)
img2 = cv2.drawContours(img2, [approx2], 0, (0, 255, 0), 2)

# 凸包
img = src.copy()
hull = cv2.convexHull(cnt)
img = cv2.drawContours(img, [hull], 0,  (255, 0, 0), 2)

# 显示各个图像
plt.rcParams['font.sans-serif'] = ['SimHei']
titles = ['src', '近似轮廓1', '近似轮廓2', '凸包']
images = [src, img1, img2, img]
plt.figure(figsize=(2, 2))
for i in range(len(images)):
    plt.subplot(2, 2, i + 1)
    plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.show()

在这里插入图片描述

参考

1.OpenCV-Python官方教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值