opencv 图像轮廓特征 图像面积,轮廓周长,外接矩形、最小外接矩形、最小外接圆、拟合椭圆

找出图像轮廓
contours, hierarchy = cv.findContours(thresh, 3, 2)

画出图像轮廓
cnt = contours[1]
cv.drawContours(img_color1, [cnt], 0, (0, 0, 255), 2)

计算轮廓面积
area = cv.contourArea(cnt) #cnt:轮廓
print(area)

计算轮廓周长
perimeter = cv.arcLength(cnt, True) #参数2:表示轮廓是否封闭
print(perimeter)

图像矩
M = cv.moments(cnt)
print(M)
print(M[‘m00’]) # 轮廓面积
cx, cy = M[‘m10’] / M[‘m00’], M[‘m01’] / M[‘m00’] # 轮廓质心
print(cx, cy)

图像外接矩形
x, y, w, h = cv.boundingRect(cnt) # 外接矩形
cv.rectangle(img_color1, (x, y), (x + w, y + h), (0, 255, 0), 2)

最小外接矩形
rect = cv.minAreaRect(cnt) # 最小外接矩形
box = np.int0(cv.boxPoints(rect)) # 矩形的四个角点并取整
cv.drawContours(img_color1, [box], 0, (255, 0, 0), 2)

最小外接圆
(x, y), radius = cv.minEnclosingCircle(cnt)
(x, y, radius) = map(int, (x, y, radius)) # 这也是取整的一种方式噢
cv.circle(img_color2, (x, y), radius, (0, 0, 255), 2)

拟合椭圆
ellipse = cv.fitEllipse(cnt)
cv.ellipse(img_color2, ellipse, (0, 255, 0), 2)

实验:计算下图中数字1的面积、轮廓周长,绘制数字1的外接矩形、最小外接矩形、最小外接圆、拟合椭圆

实验用图

import cv2 as cv
import numpy as np

# 载入手写数字图片
img = cv.imread('handwriting.jpg', 0)
# 将图像二值化
_, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
contours, hierarchy = cv.findContours(thresh, 3, 2)

# 创建出两幅彩色图用于绘制
img_color1 = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
img_color2 = np.copy(img_color1)
# 创建一幅彩色图像用作结果对比
img_color = np.copy(img_color1)

# 计算数字1的轮廓特征
cnt = contours[1]
cv.drawContours(img_color1, [cnt], 0, (0, 0, 255), 2)

# 1.轮廓面积
area = cv.contourArea(cnt)  # 6289.5
print(area)

# 2.轮廓周长
perimeter = cv.arcLength(cnt, True)  # 527.4041
print(perimeter)

# 3.图像矩
M = cv.moments(cnt)
print(M)
print(M['m00'])  # 轮廓面积
cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00']  # 轮廓质心
print(cx, cy)

# 4.图像外接矩形和最小外接矩形
x, y, w, h = cv.boundingRect(cnt)  # 外接矩形
cv.rectangle(img_color1, (x, y), (x + w, y + h), (0, 255, 0), 2)

rect = cv.minAreaRect(cnt)  # 最小外接矩形
box = np.int0(cv.boxPoints(rect))  # 矩形的四个角点并取整
cv.drawContours(img_color1, [box], 0, (255, 0, 0), 2)

# 5.最小外接圆
(x, y), radius = cv.minEnclosingCircle(cnt)
(x, y, radius) = map(int, (x, y, radius))  # 这也是取整的一种方式噢
cv.circle(img_color2, (x, y), radius, (0, 0, 255), 2)

# 6.拟合椭圆
ellipse = cv.fitEllipse(cnt)
cv.ellipse(img_color2, ellipse, (0, 255, 0), 2)

result = np.hstack((img_color,img_color1,img_color2))
cv.imshow('result',result)
cv.waitKey(0)
cv.destroyAllWindows()

实验结果

程序控制台输出
程序图像绘制结果

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值