python - 测量图像中线段的长度(以像素为单位)
问题描述
我有很多图像,如下图所示。我正在尝试从使用 OpenCV-Python 成功实现的透射电子显微镜图像中检测纳米粒子。该图像只是较大透射电子显微镜图像左下角的一部分。我想提取“100 nm”下白色线段的长度。目前,我正在手动测量这条线的长度,我想自动化它。我认为这可以用 OpenCV-Python 通过轮廓来完成,但我还有很多其他特征也在图像中轮廓。我是 Python 新手,我不太确定如何实现这一点,或者这是否可以实现。我对代码应该做什么的想法:
- 加载图像
- 找到白线段
- 返回它的长度(以像素为单位)。
- 如果它检测到该行上方的数字并将其也返回,那也很好。
非常欢迎和赞赏任何建议、方向或“从哪里开始”的评论。
线段的特征非常独特,每张图像中只有一条线。
解决方案
您可以对图像进行二值化以找到比例段的轮廓:
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。
推荐阅读
- excel - 表格单元格中的 Word VBA 格式编号 - 单元格文本无法识别
- r - 使用 R 中的行名创建公式
- c# - 如何根据条件告诉 JsonWriter 什么都不做?
- python - 如何构建自定义 lxml 解析器?
- ruby-on-rails - 更快地使用数据表和嵌套模型?
- python - Python ElementTree find() 使用命名空间
- android - Metro Bundler 和 Expo 需要证书,两者都出现错误,无法找到请求目标的有效证书路径
- java - 提示 HINT_PASS_DISTINCT_THROUGH 将 PageRequest 的每页返回的实体数量减少到配置的页面大小以下 (PostgreSQL)
- html - 我的 github 页面没有默认加载 index.html
- java - 我正在尝试在 java 中打印一个数组,我需要同时使用 public void intArray() 作为方法