python-opencv尺寸测量

原文:python-opencv尺寸测量_Krasjet_Yu.的博客-CSDN博客_python尺寸测量
首先,利用机器视觉来测定零件尺寸,我们能够直接得到的是图片的像素,要想获得尺寸大小,我们必须找到像素和实际尺寸间的关系。

我们在这里定义一个比例概念:每度量比的像素(pixels per metric ratio)。
近似含义是每个单位指标中包含的像素数。例如,图表上的1厘米包含100张图像。

实际上,相当于引用对象的作用,例如已知地图上的引用材质,我们可以使用此引用对象将其转换为地图上其他对象的大小。

引用对象需要具有两个重要属性:

  1. 属性#1:我们应该以可测量的单位(例如毫米,英寸等)知道该对象的尺寸(在宽度或高度方面)。
  2. 属性#2:我们应该能够在图像中轻松找到这个参考对象,或者根据对象的 位置(例如参考对象总是放在图像的左上角),或者通过外观(如是独特的颜色或形状,独特且与图像中的所有其他物体不同)。在任何一种情况下,我们的参考应该 以某种方式唯一可识别。

这里我选择的参照对象是美国硬币(0.9in x 1.0in),单位为英寸,并且保证它一直在照片的最左侧。并使用它来定义 pixel_per_metric,我们定义为:

pixels_per_metric = object_width / know_width

现在,假设我们的 object_width(以像素为单位)计算为150像素宽(基于其关联的边界框)。

因此 pixels_per_metric是:

pixels_per_metric = 150px / 0.955in = 157px

因此暗示在我们的图像中每0.955英寸大约有157个像素。使用此比率,我们可以计算图像中对象的大小。

然而我们还遇到一个问题是:要想每张照片上都有一个参照对象——美国硬币,这对我们来说是很麻烦的一件事,因为我们在工厂处理大批量的零件时不可能在每个零件旁都放置一枚硬币。因此,我采用了图像混合方法来处理图像,将硬币图片人为混合在零件图片上。

在这里插入图片描述

引入各种需要的库,没有相应的库在写代码前及时安装。本人使用的Anaconda,可以直接在Anaconda Prompt中直接pip即可。

pip install imutils

确保是最新版本

pip install --upgrade imutils

若是Pycharm,可以在setting中编译器里面安装

from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
#import argparse
import imutils
import numpy as np
import cv2


图像混合处理

coin_img = cv2.imread("standard_object.png")
image = cv2.imread("example_03.png")
if not image.data:print("read image wrong!")
if not coin_img.data:print("read coin_img wrong")imageROI = np.ones((100, 88, 3))
imageROI =  coin_img[0:100, 0: 88]image[10:98, 10:98] = imageROI


对图像进行预处理
从磁盘加载我们的图像,将其转换为灰度,然后使用高斯滤波器对其进行平滑处理。然后,我们进行边缘检测以及扩张+侵蚀,以封闭边缘图中边缘之间的任何间隙
找到与我们的边缘图中的对象相对应的轮廓(即轮廓)
从左到右(允许我们提取参考对象)对这些轮廓进行排序 。
初始化 pixelPerMetric 值

# load the image, convert it to grayscale, and blur it slightlygray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)gray = cv2.GaussianBlur(gray, (7, 7), 0)# perform edge detection, then perform a dilation + erosion to# close gaps in between object edgesedged = cv2.Canny(gray, 50, 100)edged = cv2.dilate(edged, None, iterations=1)edged = cv2.erode(edged, None, iterations=1)# find contours in the edge mapcnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)# sort the contours from left-to-right and initialize the# 'pixels per metric' calibration variable(cnts, _) = contours.sort_contours(cnts)pixelsPerMetric = None
width = 3.5


检查每一个轮廓
我们开始在每个轮廓上循环。如果轮廓不够大,我们丢弃该区域,假设它是边缘检测过程遗留的噪声
如果轮廓区域足够大,我们计算图像的旋转边界框
然后,我们将旋转的边界框坐标排列在左上角,右上角,右下角和左下角
最后, 以绿色绘制对象的轮廓,然后以小的红色圆圈绘制边界框矩形的顶点。

# loop over the contours individuallyfor c in cnts:# if the contour is not sufficiently large, ignore itif cv2.contourArea(c) < 100:continue# compute the rotated bounding box of the contourorig = image.copy()box = cv2.minAreaRect(c)box = cv2.boxPoints(box)box = np.array(box, dtype="int")# order the points in the contour such that they appear# in top-left, top-right, bottom-right, and bottom-left# order, then draw the outline of the rotated bounding# boxbox = perspective.order_points(box)cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)# loop over the original points and draw themfor (x, y) in box:cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)


现在我们已经获得了边界框,我们可以计算出一系列中点:
打开我们获得的边界框,然后计算左上角和右上角之间的中点,然后是右下角之间的中点
我们还将分别计算左上角 + 左下角 和 右上角 + 右下角之间的中点。
在我们的图像上绘制蓝色中点 ,然后用紫色线连接中点 。

# unpack the ordered bounding box, then compute the midpoint# between the top-left and top-right coordinates, followed by# the midpoint between bottom-left and bottom-right coordinates(tl, tr, br, bl) = box(tltrX, tltrY) = midpoint(tl, tr)(blbrX, blbrY) = midpoint(bl, br)# compute the midpoint between the top-left and top-right points,# followed by the midpoint between the top-righ and bottom-right(tlblX, tlblY) = midpoint(tl, bl)(trbrX, trbrY) = midpoint(tr, br)# draw the midpoints on the imagecv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)# draw lines between the midpointscv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)),(255, 0, 255), 2)cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)),(255, 0, 255), 2)


接下来,我们需要通过调查我们的引用对象来初始化 pixelPerMetric变量:
首先,我们计算我们的中点集之间的欧几里德距离。该 DA 变量将包含高度距离(以像素为单位),而分贝将保存我们的宽度的距离。

然后,看看我们的 pixelsPerMetric 变量已经初始化,如果没有,我们把 分贝 由我们提供 - 宽度 ,从而使我们每英寸我们的(近似)的像素。

# compute the Euclidean distance between the midpointsdA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))# if the pixels per metric has not been initialized, then# compute it as the ratio of pixels to supplied metric# (in this case, inches)if pixelsPerMetric is None:pixelsPerMetric = dB / width


现在我们 已经定义了 pixelPerMetric变量,我们可以测量图像中对象的大小:
通过将相应的欧几里德距离除以pixelsPerMetric 值来计算对象的尺寸(以英寸为单位)
在图像上绘制对象的尺寸
显示输出结果

# compute the size of the objectdimA = dA / pixelsPerMetricdimB = dB / pixelsPerMetric# draw the object sizes on the imagecv2.putText(orig, "{:.1f}in".format(dimA),(int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,0.65, (255, 255, 255), 2)cv2.putText(orig, "{:.1f}in".format(dimB),(int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,0.65, (255, 255, 255), 2)# show the output imagecv2.imshow("Image", orig)cv2.waitKey(0)


最后给上完整代码:

from scipy.spatial import distance as dist
from imutils import perspective
from imutils import contours
#import argparse
import imutils
import numpy as np
import cv2def midpoint(A, B):return ((A[0] + B[0]) * 0.5, (A[1] + B[1]) * 0.5)coin_img = cv2.imread("standard_object.png")
image = cv2.imread("example_03.png")
if not image.data:print("read image wrong!")
if not coin_img.data:print("read coin_img wrong")imageROI = np.ones((100, 88, 3))
imageROI =  coin_img[0:100, 0: 88]image[10:98, 10:98] = imageROI
# load the image, convert it to grayscale, and blur it slightlygray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)gray = cv2.GaussianBlur(gray, (7, 7), 0)# perform edge detection, then perform a dilation + erosion to# close gaps in between object edgesedged = cv2.Canny(gray, 50, 100)edged = cv2.dilate(edged, None, iterations=1)edged = cv2.erode(edged, None, iterations=1)# find contours in the edge mapcnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = imutils.grab_contours(cnts)# sort the contours from left-to-right and initialize the# 'pixels per metric' calibration variable(cnts, _) = contours.sort_contours(cnts)pixelsPerMetric = None
width = 3.5# loop over the contours individuallyfor c in cnts:# if the contour is not sufficiently large, ignore itif cv2.contourArea(c) < 100:continue# compute the rotated bounding box of the contourorig = image.copy()box = cv2.minAreaRect(c)box = cv2.boxPoints(box)box = np.array(box, dtype="int")# order the points in the contour such that they appear# in top-left, top-right, bottom-right, and bottom-left# order, then draw the outline of the rotated bounding# boxbox = perspective.order_points(box)cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)# loop over the original points and draw themfor (x, y) in box:cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)# unpack the ordered bounding box, then compute the midpoint# between the top-left and top-right coordinates, followed by# the midpoint between bottom-left and bottom-right coordinates(tl, tr, br, bl) = box(tltrX, tltrY) = midpoint(tl, tr)(blbrX, blbrY) = midpoint(bl, br)# compute the midpoint between the top-left and top-right points,# followed by the midpoint between the top-righ and bottom-right(tlblX, tlblY) = midpoint(tl, bl)(trbrX, trbrY) = midpoint(tr, br)# draw the midpoints on the imagecv2.circle(orig, (int(tltrX), int(tltrY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(blbrX), int(blbrY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(tlblX), int(tlblY)), 5, (255, 0, 0), -1)cv2.circle(orig, (int(trbrX), int(trbrY)), 5, (255, 0, 0), -1)# draw lines between the midpointscv2.line(orig, (int(tltrX), int(tltrY)), (int(blbrX), int(blbrY)), (255, 0, 255), 2)cv2.line(orig, (int(tlblX), int(tlblY)), (int(trbrX), int(trbrY)), (255, 0, 255), 2)# compute the Euclidean distance between the midpointsdA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))# if the pixels per metric has not been initialized, then# compute it as the ratio of pixels to supplied metric# (in this case, inches)if pixelsPerMetric is None:pixelsPerMetric = dB / width# compute the size of the objectdimA = dA / pixelsPerMetricdimB = dB / pixelsPerMetric# draw the object sizes on the imagecv2.putText(orig, "{:.1f}in".format(dimA),(int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)cv2.putText(orig, "{:.1f}in".format(dimB),(int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2)# show the output imagecv2.imshow("Image", orig)cv2.waitKey(0)

但是测量不一定是100%准确的。为什么物体测量不是100%准确?

原因有两方面:

首先,用手机拍了照片。角度肯定 不是物体上“俯视”(如鸟瞰图)的完美90度角。如果没有完美的90度视图(或尽可能接近它),对象的尺寸可能会出现扭曲。

其次,没有使用相机的内在和外在参数来校准手机。在不确定这些参数的情况下,照片可能容易发生径向和切向镜头失真。执行额外的校准步骤来查找这些参数可以“扭曲”我们的图像并导致更好的对象大小近似。

同时,在拍摄物体照片时尽量获得尽可能接近90度的视角 - 这有助于提高物体尺寸估计的准确性。

总结

在本文中,我们学习了如何通过使用python和OpenCV来测量图片中的物体的大小。

我们首先对图像进行了混合处理。

我们需要确定pixels per metric比率(单位尺寸像素数),即在给定的度量(如英寸、毫米、米等)下,像素的数量。

为了计算这个比率,我们需要一个参考物体,它需要两点重要的性质:

1、参考物体需要有含测量单位(英寸、毫米等等)的尺寸

2、无论从物体的位置还是形状,参考物体都需要容易被找到。

加入上面的性质都能满足,你可以使用参考物体计算pixels per metric比率,并根据这个计算图片中物体的大小。

在这里插入图片描述

参考:
[干货」如何使用OpenCV测量图像中物体的尺寸大小
[Python图像处理] 三.获取图像属性、兴趣ROI区域及通道处理
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/1618555.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

用Cmake build OpenCV后,在VS中查看OpenCV源码的方法(环境VS2022+openCV4.8.0) Part III

用Cmake build OpenCV后&#xff0c;在VS中查看OpenCV源码的方法(环境VS2022openCV4.8.0) Part III 用Cmake build OpenCV后&#xff0c;在VS中查看OpenCV源码的方法&#xff08;环境VS2022openCV4.8.0&#xff09; Part I_松下J27的博客-CSDN博客 用Cmake build OpenCV后&…

理解HTTPS/TLS/SSL(一)基础概念+配置本地自签名证书

文章目录 没有HTTPS时的样子场景模拟WireShark的Capture Filter和Display Filter设置Capture Filter启动程序设置Display Filter过滤抓到的包 结论 关于为什么加密更简洁有力的回答对称加密和非对称加密和CA证书密钥交换对称加密非对称加密CA机构和证书如何解决客户端和CA机构之…

顺序表链表OJ题(1)——【LeetCode】

W...Y的主页 &#x1f60a; 代码仓库分享 &#x1f495; 前言&#xff1a; 今天我们来回顾一下顺序表与链表&#xff0c;针对这一块我们也有许多OJ题目供大家参考。当我们学习完顺序表链表后避免不了一些习题的练习&#xff0c;这样才能巩固我们学习的内容。 话不多说&#xf…

PCI/PCIE总线的宏观理解

1、pcie总线协议实现的效果 (1)像访问内存一样去访问外设&#xff1b; (2)当建立好CPU地址空间到PCI/PCIE地址空间的映射关系后&#xff0c;程序访问CPU地址空间就可以达到访问PCI/PCIE地址空间的效果&#xff1b; 2、芯片地址空间 (1)32位的CPU寻址范围是4G&#xff0c;64位的…

MySQL执行更新的流程

一、加载缓存数据 引擎要执行更新语句的时候 &#xff0c;比如对“id10”这一行数据&#xff0c;他其实会先将“id10”这一行数据看看是否在缓冲池里&#xff0c;如果不在的话&#xff0c;那么会直接从磁盘里加载到缓冲池里来&#xff0c;而且接着还会对这行记录加独占锁。 二…

Spring中Bean及@Bean的理解与new对象的区别

一直在纠结一个问题&#xff1a;new创建对象和用Bean创建对象有什么区别吗&#xff1f;为什么在spring中要使用Bean&#xff1f;Bean有什么作用&#xff1f; 一、Bean是啥 1、Java面向对象&#xff0c;对象有方法和属性&#xff0c;那么就需要对象实例来调用方法和属性&#x…

Spring Bean到底是什么?有什么用?

Spring Bean是什么?有什么用&#xff1f; 一、Bean到底是什么&#xff1f;二.怎么使用bean&#xff1f;三.Bean配置四.Bean的作用域 Bean在Spring和SpringMVC中随处可见,将这个概念内化很重要&#xff0c;下面分享一下我的想法&#xff1a; 一、Bean到底是什么&#xff1f; …

spring bean是什么

原文链接&#xff1a;https://www.awaimai.com/2596.html 歪麦博客 Spring有跟多概念&#xff0c;其中最基本的一个就是bean&#xff0c;那到底spring bean是什么? Bean是Spring框架中最核心的两个概念之一&#xff08;另一个是面向切面编程AOP&#xff09;。 是否正确理解…

Spring Bean的作用域

在Spring中&#xff0c;bean作用域用于确定哪种类型的bean实例应该从Spring容器中返回给调用者。 目前Spring Bean的作用域或者说范围主要有五种。 作用域描述singleton在spring IoC容器仅存在一个Bean实例&#xff0c;Bean以单例方式存在&#xff0c;bean作用域范围的默认值…

Spring bean是什么?

Spring有跟多概念&#xff0c;其中最基本的一个就是bean&#xff0c;那到底spring bean是什么? Bean是Spring框架中最核心的两个概念之一&#xff08;另一个是面向切面编程AOP&#xff09;。 是否正确理解 Bean 对于掌握和高效使用 Spring 框架至关重要。 遗憾的是&#xff0…

什么是bean

什么是bean&#xff1f; bean是计算机自动生成的类&#xff0c;bean是一个由Spring IoC容器实例化、组装和管理的对象。也就是说&#xff0c;bean并不是程序员编辑的&#xff0c;而是程序运行时&#xff0c;由spring通过反射生成的。在程序中&#xff0c;我们并不使用代码去ne…

Bean介绍

1.Bean 简介 在 Spring 中&#xff0c;所有被IOC 容器管理的&#xff0c;构成应用核心骨架的对象都被成为 Bean&#xff0c;它是由容器来实例化、装配、管理的对象。此外&#xff0c;它也是你应用中众多对象的一个。Bean 以及依赖的实例化和装配等工作全部是由容器中的配置元信…

Bean专题——什么是Bean?怎么注册、使用?生命周期?作用域?

1.什么是Bean&#xff1f; Bean是被实例的、组装的、及被Spring容器管理的Java对象。Spring容器会自动完成Bean对象的实例化。创建应用对象之间的协作关系的行为被称为&#xff1a;装配&#xff0c;这就是依赖注入的本质。 2.Spring三种装配方案 1.隐式的bean发现机制和自动…

【Spring第三篇】什么是Bean?

在Spring 中&#xff0c;构成应用程序主干并由Spring IoC容器管理的对象称为bean。bean是一个由Spring IoC容器实例化、组装和管理的对象。 我们总结如下&#xff1a; 1.bean是对象&#xff0c;一个或者多个不限定 2.bean由Spring中一个叫IoC的东西管理 3.我们的应用程序由一个…

大数据-玩转数据-Flink窗口函数

一、Flink窗口函数 前面指定了窗口的分配器, 接着我们需要来指定如何计算, 这事由window function来负责. 一旦窗口关闭, window function 去计算处理窗口中的每个元素. window function 可以是ReduceFunction,AggregateFunction,or ProcessWindowFunction中的任意一种. Reduc…

软考:中级软件设计师:网络类型与拓扑结构,网络规划与设计,ip地址与子网划分,特殊含义的IP地址

软考&#xff1a;中级软件设计师:网络类型与拓扑结构 提示&#xff1a;系列被面试官问的问题&#xff0c;我自己当时不会&#xff0c;所以下来自己复盘一下&#xff0c;认真学习和总结&#xff0c;以应对未来更多的可能性 关于互联网大厂的笔试面试&#xff0c;都是需要细心准…

Qt入门教程【Core篇】Layout布局(布局管理器、手动布局)

&#x1f608;「编程小鱼酱秘密基地」&#xff1a;传送门 &#x1f608;「CSDN主页」&#xff1a;传送门 &#x1f608;「Bilibil首页」&#xff1a;传送门 &#x1f608;「网易云课堂」&#xff1a;传送门 &#x1f608;「CSDN学院」&#xff1a;传送门 &#x1f608;「51CTO学…

前端布局 Flex(弹性)布局

1. flex布局优点 操作方便&#xff0c;布局极为简单&#xff0c;移动端应用很广泛 pc端浏览器支持情况较差 IE11或者更低版本&#xff0c;不支持或仅部分支持 2. flex布局原理 flex意为“弹性布局”&#xff0c;用来为盒状模型提供最大的灵活性&#xff0c;任何一个容器都…

Java BorderLayout(边框布局)布局管理器

BorderLayout BorderLayout 将容器分为 EAST 、 SOUTH 、 WEST 、 NORTH 、 CENTER五个区域&#xff0c;普通组件可以被放置在这 5 个区域的任意一个中 。 BorderLayout布局 管理器的布局示意图如图所示 。 当改变使用 BorderLayout 的容器大小时&#xff0c; NORTH 、 SOUTH …

java:布局方法(网格布局)

网格布局 一、简单说明二、关键代码三、流程图四、例子说明1. 有17个“按钮”排列&#xff08;1&#xff09;源码A&#xff08;2&#xff09;运行效果 2. 有36个“按钮”排列&#xff08;1&#xff09;源码B&#xff08;2&#xff09;源码B运行效果 3. 有12个“按钮”排列&…