我正在尝试使用计算机视觉来获取一定长度内圆柱体不同点的直径,以取代光学测微计的使用。
如何使用 OpenCV python 计算该物体(圆柱体)沿其长度的多个点(蓝线)的直径,如图所示?
OpenCV 解决方案。主要思想是:
1.、2. 和 3. 可以根据您的用例通过单个阈值步骤来简化
import numpy as np
import cv2
src = cv2.imread('/path/to/src.jpg')
mask = np.zeros(src.shape, dtype=np.uint8)
w, h, c = src.shape
# edge detection
threshold = 100
gray = cv2.Canny(src, threshold, threshold * 2)
cv2.imshow('', gray)
cv2.waitKey(0)
# find contours
cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
threshold_area = 0.5
# fill area withing contours with white color
for c in cnts:
area = cv2.contourArea(c)
if area > threshold_area:
cv2.drawContours(mask, [c], -1, (255, 255, 255), -1)
cv2.imshow('', mask)
cv2.waitKey(0)
# get non zero values (height) of each column
column_pixels = [cv2.countNonZero(mask[:, i]) for i in range(0, w)]
print(column_pixels)
源图片:
精明的结果:
用白色填充轮廓后:
countNonZero 应用于每列的最后一张图像