python+opencv基础篇——应用轮廓获取数据

本文介绍了如何在PyCharm中使用OpenCV库进行图像处理,包括读取图像、灰度处理、二值化、去噪、轮廓检测,并计算轮廓的各种属性如面积、中心点、形状等。
摘要由CSDN通过智能技术生成

开发工具:pycharm

识别出图像中的轮廓后,我们可以利用轮廓来计算一些数据

在上一篇的提取轮廓的基础上实现下面代码:(被检测图像背景色为白色)

需要注意调整二值化阈值,如果是0,255会出现完全白色图像

import math
import cv2
import numpy

# 读取图像
img = cv2.imread('D:\\Demo2.TIF')
# 灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
# 去噪
# 卷积核
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# 腐蚀
eroded = cv2.erode(thresh, kernel)
# 膨胀
dilated = cv2.dilate(eroded, kernel)
# 轮廓检测
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

count = 0

font = cv2.FONT_HERSHEY_TRIPLEX

for cnt in range(len(contours)):
    area = cv2.contourArea(contours[cnt])  # 得到--面积

    if hierarchy[0][cnt][3] != -1: # 判断是否有上级
        print('有父级')
    else:
        print('无父级')

    M = cv2.moments(cnt)
    if M['m00'] != 0:
        print(M['m00'])
        cx = int(M['m10'] / M['m00']) # 得到--中心点x坐标
        cy = int(M['m01'] / M['m00']) # 得到--中心点y坐标

    length = cv2.arcLength(contours[cnt], True)  # 得到--周长

    # 找到包含轮廓的最小矩形框
    rect = cv2.minAreaRect(contours[cnt])
    width = float(rect[1][0])  # 得到--最大宽度
    height = float(rect[1][1])  # 得到--最大高度

    # 公式:e=(4π 面积)/(周长 * 周长)
    roundness = (4 * math.pi * area) / (length * length)  # 得到--圆形度

    rectangularity = area / (height * width)  # 得到--矩形度

    # 最大内切圆
    # 计算到轮廓的距离
    raw_dist = numpy.empty(gray.shape, numpy.float32)

    for x in range(gray.shape[0]):
        for j in range(gray.shape[1]):
            raw_dist[x, j] = cv2.pointPolygonTest(contours[cnt], (j, x), True)

    # 获取最大值即内接圆半径,中心点坐标
    minVal, maxVal, _, maxDistPt = cv2.minMaxLoc(raw_dist)

    # 半径:maxVal  圆心:maxDistPt
    # 转换格式
    maxVal = abs(maxVal)
    nradius = int(maxVal)  # 得到--最大内切换半径

    hull = cv2.convexHull(contours[cnt])  # 获取凸包
    hullArea = cv2.contourArea(hull)  # 得到--凸包面积

    # 外接圆
    center, wradius = cv2.minEnclosingCircle(contours[cnt])  # 得到--最小外接圆半径

    # 绘制轮廓
    cv2.drawContours(img, [contours[cnt]], 0, (0, 255, 0), 2)
    (x, y), radius = cv2.minEnclosingCircle(contours[cnt])
    center = (int(x - 50), int(y))
    # 在图片上添加字
    cv2.putText(img, str(count) + ":" + str(area), center, font, 2, (0, 255, 0))

# 绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 1)
# 显示图像
cv2.imshow('img', img)
# 等待程序终止
cv2.waitKey(0)
cv2.destroyAllWindows()

附加一些常用方法:

# 二值后,改变四个角连接的黑色区域变为白色,如果外边框是一个整体可只用其中一个
floodFill = cv2.floodFill(thresh, mask=None, seedPoint=(0, 0), newVal=(255, 255, 255))[1]
floodFill = cv2.floodFill(thresh, mask=None, seedPoint=(0, height - 1), newVal=(255, 255, 255))[1]
floodFill = cv2.floodFill(thresh, mask=None, seedPoint=(width - 1, height - 1), newVal=(255, 255, 255))[1]
floodFill  = cv2.floodFill(thresh, mask=None, seedPoint=(width - 1, 0), newVal=(255, 255, 255))[1]

# 二值后,翻转图像颜色,白色变为黑色,黑色变为白色
bitwise_not = cv2.bitwise_not(thresh)

# 二值后,可用中值滤波去除杂点
blur = cv2.medianBlur(thresh, 3)  # 中值滤波 只能是奇数 3最好用

# 二值后,可提取骨架
thresh[thresh == 255] = 1
skeleton = morphology.skeletonize(thresh)  # 骨架提取
skeleton_image = skeleton.astype(np.uint8) * 255 # 得到--骨架图


## 可根据情况自由选择 其中thresh是二值图像,但并不是只能用二值图像

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值