基于图像处理的螺母定位和半径检测

这篇文章起源是一个朋友的课后作业,因为觉得好玩就做了一下,过程中觉得学到了一些东西,所以在此记录
要求:采用机器视觉的方法对图像中的螺母进行定位,并把螺母圆的半径测量出来。
图片如下:
请添加图片描述
看到题目第一反应是采用图像处理的方法,基础思路是:灰度-边缘提取-滤波-霍夫变换
这里主要记录代码和调试以及用到的一些函数
1、准备工作

import cv2
import numpy as np

# 读取图片
img = cv2.imread('images/example_01.jpg')

2、灰度化

# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

灰度化图片:
在这里插入图片描述
3、边缘检测

# 边缘检测
edges = cv2.Canny(gray, 150, 300, apertureSize=3)

在这里插入图片描述

4、滤波
采用了去除小连通域的方法去除小噪点

# 获取连通区域
output = cv2.connectedComponentsWithStats(edges, 8, cv2.CV_32S)
# 获取连通区域个数
num_labels = output[0]
# 获取连通区域信息
labels = output[1]
stats = output[2]
centroids = output[3]

# 指定阈值
threshold_value = 15
# 遍历所有连通区域
for i in range(1, num_labels):
    # 判断连通区域大小是否小于阈值,如果小于则将该区域设置为背景色
    if stats[i, cv2.CC_STAT_AREA] < threshold_value:
        labels[labels == i] = 0
# 去除背景
labels[labels != 0] = 255
mg = np.array(labels,dtype=np.uint8)

在这里插入图片描述

# 霍夫变换
circles = cv2.HoughCircles(mg, cv2.HOUGH_GRADIENT, 1, 100, param1=50, param2=49, minRadius=0, maxRadius=0)

# 绘制圆
if circles is not None:
    circles = np.uint16(np.around(circles))
    for i in circles[0, :]:
        cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)  # 画圆i[0], i[1]中心点 i[2]是半径
        cv2.circle(img, (i[0], i[1]), 2, (255, 0, 0), 2)  # 画圆心
        cv2.line(img, (i[0], i[1]), (i[0]+i[2], i[1]), (255, 0, 0), 2)  # 画半径
        # 计算半径
        radius = int(np.ceil(i[2]))
        # 把半径打印在图片上
        cv2.putText(img, "{:.1f}".format(radius), (i[0], i[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)
        # print("Radius of the detected circle: ", radius)

# 显示结果
cv2.imshow('detected circles', img)

在这里插入图片描述
关于调参:
本程序一共有三处参数调整:1、边缘检测 2、连通域阈值大小 3、霍夫变换
1、边缘检测

edges = cv2.Canny(gray, 150, 300, apertureSize=3)
# edges = cv.Canny( image, threshold1, threshold2[, apertureSize[, L2gradient]])

threshold_value = 15

霍夫变换
circles = cv2.HoughCircles(mg, cv2.HOUGH_GRADIENT, 1, 100, param1=50, param2=49, minRadius=0, maxRadius=0)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值