如何利用图像像素计算物体多个点的直径?

问题描述 投票:0回答:1

我正在尝试使用计算机视觉来获取一定长度内圆柱体不同点的直径,以取代光学测微计的使用。

圆柱体图像:

如何使用 OpenCV python 计算该物体(圆柱体)沿其长度的多个点(蓝线)的直径,如图所示?

python opencv image-processing pixel contour
1个回答
1
投票

OpenCV 解决方案。主要思想是:

  1. 检测边缘
  2. 找到边缘的轮廓
  3. 填充轮廓区域
  4. 遍历图像中的每一列并计算非零像素

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 应用于每列的最后一张图像

© www.soinside.com 2019 - 2024. All rights reserved.