首页 > 解决方案 > 测量图像中线段的长度(以像素为单位)

问题描述

我有很多图像,如下图所示。我正在尝试从使用 OpenCV-Python 成功实现的透射电子显微镜图像中检测纳米粒子。该图像只是较大透射电子显微镜图像左下角的一部分。我想提取“100 nm”下白色线段的长度。目前,我正在手动测量这条线的长度,我想自动化它。我认为这可以用 OpenCV-Python 通过轮廓来完成,但我还有很多其他特征也在图像中轮廓。我是 Python 新手,我不太确定如何实现这一点,或者这是否可以实现。我对代码应该做什么的想法:

  1. 加载图像
  2. 找到白线段
  3. 返回它的长度(以像素为单位)。
  4. 如果它检测到该行上方的数字并将其也返回,那也很好。

非常欢迎和赞赏任何建议、方向或“从哪里开始”的评论。

线段的特征非常独特,每张图像中只有一条线。

在此处输入图像描述

标签: pythonopencvimage-processingobject-detection

解决方案


您可以对图像进行二值化以找到比例段的轮廓:

加工

scale = cv2.imread('scalenanometer.png', cv2.IMREAD_COLOR)
scale_gray = cv2.cvtColor(scale, cv2.COLOR_BGR2GRAY)
# adjust the second value of the next line to tune the detection
ret, thresh = cv2.threshold(scale_gray, 210, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# filter noisy detection
contours = [c for c in contours if cv2.contourArea(c) > 100]
# sort from by (y, x)
contours.sort(key=lambda c: (cv2.boundingRect(c)[1], cv2.boundingRect(c)[0]))
# work on the segment
cv2.rectangle(scale, cv2.boundingRect(contours[-1]), (0,255,0), 2)
x,y,w,h = cv2.boundingRect(contours[-1])
print(x,y,w,h) # x,y: (39 152) w,h: [304 21]

如果要检测值,可以使用tesseract ocr。


推荐阅读