Python 图像处理:检测圆形孔并计算尺寸
这段代码是用 Python 实现的,主要功能是检测一张图片中的圆形孔,并计算孔的数量和孔径等信息。具体实现步骤如下:
- 加载图片并将其转换为灰度图像。
- 使用高斯滤波器对图像进行平滑处理。
- 对图像进行形态学操作,以去除噪声。
- 对图像进行边缘检测。
- 让用户标出两个点,计算它们之间的距离,以便后续计算像素当量。
- 应用 Hough 圆变换算法,以检测图像中的圆形。
- 计算检测到的圆的数量和孔径等信息,并输出结果。
- 显示结果。
这段代码需要用到 OpenCV 和 NumPy 两个 Python 库,其中 OpenCV 用于图像处理和圆形检测,NumPy 用于数学计算。
import cv2
import numpy as np
def mouse_callback(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
param.append((x, y))
# 加载图像并将其转换为灰度图像
img = cv2.imread('circle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用高斯滤波器对图像进行平滑处理
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 对图像进行形态学操作
kernel = np.ones((5, 5), np.uint8)
closing = cv2.morphologyEx(blur, cv2.MORPH_CLOSE, kernel)
# 对图像进行边缘检测
edges = cv2.Canny(closing, 10, 50)
# 显示图像并要求用户标出两个点
points = []
cv2.namedWindow('Reference points')
cv2.setMouseCallback('Reference points', mouse_callback, points)
while len(points) < 2:
cv2.imshow('Reference points', img)
cv2.waitKey(100)
cv2.destroyAllWindows()
# 计算用户标记的两点之间的距离
pixel_distance = np.sqrt((points[0][0] - points[1][0]) ** 2 + (points[0][1] - points[1][1]) ** 2)
pixel_to_mm_ratio = pixel_distance / 10 # 10 mm
pixel_equivalent = 1 / pixel_to_mm_ratio
print('像素当量为1像素对应', pixel_equivalent)
# 应用 Hough 圆变换算法,以检测图像中的圆形
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 20,
param1=10, param2=24, minRadius=20, maxRadius=100)
# 计算检测到的圆的数量
if circles is not None:
circles = np.round(circles[0, :]).astype('int')
num_circles = circles.shape[0]
print('孔的数量:', num_circles)
max_distance = 0
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
diameter = 2 * r
diameter_mm = diameter / pixel_to_mm_ratio
print('孔径:', diameter_mm)
for (x2, y2, r2) in circles:
distance = np.sqrt((x - x2) ** 2 + (y - y2) ** 2)
max_distance = max(max_distance, distance)
max_distance_mm = max_distance / pixel_to_mm_ratio
print('外围孔圆心组成的圆的直径:', max_distance_mm)
# 显示结果
cv2.imshow('Circle detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
原文地址: http://www.cveoy.top/t/topic/jucP 著作权归作者所有。请勿转载和采集!