用 OpenCV 检测图像中各物体大小

我们需要定义一个比值,它测量每个给定指标的像素个数。
我将其称为「像素/度量」比率,在下一节中我将更正式地定义它。

1.「像素/度量」比率
为了确定图像中物体的大小,我们首先需要使用一个参考物体进行「校准」
参考物体应该有两个重要的属性:
• 属性 1:我们应该在一个可测量的单位(如毫米、英寸等)内,知道这个物体的尺寸(根据宽度或高度)。
• 属性 2:我们应该能够在图像中轻松地找到这个参考物体,要么基于物体的位置(如参考物体总是被放置在图像的左上角)或通过表象(像一个独特的颜色或形状,独特且不同于其他物体的物体)。在任何一种情况下,我们的参考都应该以某种方式具有惟一的可识别性。
在本例中,我们将使用一个两角五分的美元硬币作为参考物体,并在所有示例中确保它始终是图像中最左的物体:
在这里插入图片描述
通过保证该硬币是最左的物体,我们可以从左到右对物体轮廓进行排序,获取硬币(这将始终是排序列表中的第一个轮廓),并使用它来定义我们的 pixels_per_metric ,我们将其定义为:
pixels_per_metric = object_width / know_width
一个两角五分的美元硬币是 0.955 英寸。现在假设我们的 object_width (以像素为单位)被计算为 150 像素宽(基于它的相关边框)。
因此,pixels_per_metric 为:
pixels_per_metric = 150px / 0.955in = 157px
因此,在我们的图像中,每 0.955 英寸大约有 157 个像素。利用这个比率,我们可以计算图像中物体的大小。
【固定摄像机到物体的位置,确定参考标尺的长度】

2.基于计算机视觉的物体尺寸检测
既然我们知道「像素/度量」比率 ,就可以实现用于测量图像中物体大小的 Python 驱动程序脚本。
新建一个文件,将其命名为 object_size.py ,插入以下代码:

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

def midpoint(ptA, ptB):
	return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
	
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
			help="path to the input image")
ap.add_argument("-w", "--width", type=float, required=True,
			help="width of the left-most object in the image (in inches)")
args = vars(ap.parse_args())

第 2 行到第 8 行导入我们需要的 Python 包。在该例中,我们将充分利用 imutils package ,所以如果你没有安装这个包,确保在继续下一步之前安装这个包。如果你确实安装了 imutils ,请确保你有最新的版本,本文的版本为 0.3.6。【已安装0.5.3】

第 10 行和第 11 行定义一个称为中点的辅助方法,顾名思义,用于计算(x, y)-坐标的两组之间的中点。

第 14 行到第 19 解析我们的命令行参数。我们需要两个参数:一个是图像,该图像为包含我们想测量物体的输入图像的路径,第二个是参照物的宽度(以英寸为单位),假定参照物在我们图像中的最左端。

现在,我们能加载我们的图像并对其进行预处理:

# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread(args["image"])
gray = 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 edges
edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

# find contours in the edge map
cnts = 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

第 2 行到第 4 行:从磁盘中加载我们的图像,将该图像灰度化,并利用高斯过滤器将其平滑化。
第 8 行到第 10 行:对其进行边缘检测,并通过膨胀和腐蚀使边缘过渡得更加平滑。
第 13 行到第 15 行:在边缘检测后的图中寻找与物体一致的边缘(例如轮廓)。
imutils.grab_contours经常搭配 cv2.findContours一起使用, imutils.grab_contours的作用,返回cnts中的countors(轮廓)
第 19 行:将这些边缘从左到右排序(允许我们提取参照物)。
第 20 行:初始化 pixelsPerMetric 值

下一步就是检测每个轮廓:

# loop over the contours individually
for c in cnts:
	# if the contour is not sufficiently large, ignore it
	if cv2.contourArea(c) < 100:
		continue
		
	# compute the rotated bounding box of the contour
	orig = image.copy()
	box = cv2.minAreaRect(c)
	box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else 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
	# box
	box = perspective.order_points(box)
	cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)
	
	# loop over the original points and draw them
	for (x, y) in box:
		cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)

在第 2 行,我们开始对每个轮廓进行循环。
如果轮廓不够大,我们丢弃该区域,假设它是边缘检测过程中遗留下来的噪声(第 4 行和第 5 行)。
如果轮廓区域足够大,我们在第 9-11 行计算图像的旋转边界框,特别注意使用 OpenCV 2.4 的 cv2.cv.BoxPoints 函数和 OpenCV 3 的 cv2.boxPoints 方法。
在第 17 行,我们在左上方、右上方、右下方和左下方的顺序排列我们旋转的边界框坐标,如上周的博客文章所说的那样。
最后,第 18-21 行以绿色绘制物体的轮廓,然后将边界框矩形的顶点绘制成红色的小圆圈。

既然我们已经将边界矩形框排好序了,就能计算出一系列的中点:

# 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 bottom-left points,
# followed by the midpoint between the top-right and bottom-right
(tlblX, tlblY) = midpoint(tl, bl)
(trbrX, trbrY) = midpoint(tr, br)

# draw the midpoints on the image
cv2.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 midpoints
cv2.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)

第 4-6 行打开我们的有序边界框,计算左上角和右上角之间的中点,然后计算左下角和右下角之间的中点。
我们还将分别计算左上+左下, 右上+右下之间的中点(第 10 行和第 11 行)。
第 14-17 行在图像上绘制蓝色中间点,然后将中间点与紫色线连接。

接下来,我们需要通过调查参照物来初始化 pixelsPerMetric 变量:

# compute the Euclidean distance between the midpoints
dA = 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 / args["width"]

首先,我们计算出我们的中点集合之间的欧氏距离(第 2 和 3 行)。dA 变量将包含高度距离(以像素为单位),而 dB 将保留宽度距离。
然后在第 8 行进行检查,看看我们的 pixelsPerMetric 变量是否被初始化了,如果没有初始化,我们将 dB 除以我们提供的宽度,从而得到(近似的)像素/英寸。

既然我们的 pixelsPerMetric 变量已经被定义,我们就可以测量图像中物体的大小:

# compute the size of the object
dimA = dA / pixelsPerMetric
dimB = dB / pixelsPerMetric

# draw the object sizes on the image
cv2.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 image
cv2.imshow("Image", orig)
cv2.waitKey(0)

第 2 行和 3 行通过将各自的欧几里得距离除以像素值来计算物体的尺寸(以英寸为单位)。
第 6-11 行绘制图像上物体的尺寸,第 14 行和第 15 行显示输出结果。

为了测试我们 object_size.py 脚本,只需用以下命令:
$ python Measuring_size_OpenCV.py --image images/image.jpg --width 0.955
实际是打开terminal,输入:
(py38) D:\Master_project_TJH\test_wzy\python_code>
python Measuring_size_OpenCV.py --image images/image3.jpg --width 3.7

不准确的原因:
原因是双重的:
1. 首先,我较为匆忙的用 iPhone 拍了这张照片。这个角度当然不是完全 90 度地「向下看」物体(就像鸟瞰一样)。如果不是完全 90 度视角(或者尽可能接近90°),物体的尺寸可能会显得扭曲。
2. 其次,我没有使用相机的内部和外部参数来校准我的 iPhone 。如果不确定这些参数,照片很容易出现径向和切向镜头畸变。为了找到这些参数而执行额外的校准步骤,可以「不扭曲」我们的图像,并导致更好的对象大小近似(但我将把失真校正的讨论作为未来博客文章的主题)。
与此同时,在拍摄物体时,尽量接近 90 度的视角 —— 这将有助于提高你对物体大小的估计的准确性。

全部源代码:

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


def midpoint(ptA, ptB):
    return (ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5


# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="path to the input image")
ap.add_argument("-w", "--width", type=float, required=True,
                help="width of the left-most object in the image (in inches)")
args = vars(ap.parse_args())

# load the image, convert it to grayscale, and blur it slightly 图像预处理
image = cv2.imread(args["image"])
gray = 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 edges #  canny边缘检测器+膨胀和腐蚀
edged = cv2.Canny(gray, 50, 100)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

# find contours in the edge map 寻找轮廓
cnts = 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 初始化pixelsPerMetric
(cnts, _) = contours.sort_contours(cnts)
pixelsPerMetric = None

# loop over the contours individually
for c in cnts:
    # if the contour is not sufficiently large, ignore it 太小的忽略
    if cv2.contourArea(c) < 100:
        continue

    # compute the rotated bounding box of the contour 计算图像的旋转边界框
    orig = image.copy()
    box = cv2.minAreaRect(c)
    box = cv2.cv.BoxPoints(box) if imutils.is_cv2() else 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
    # box 我们在左上方、右上方、右下方和左下方的顺序排列我们旋转的边界框坐标
    box = perspective.order_points(box)
    # 绿色绘制物体的轮廓
    cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)

    # loop over the original points and draw them ,然后将边界框矩形的顶点绘制成红色的小圆圈。
    for (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 image 绘制蓝色中间点
    cv2.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 midpoints,然后将中间点与紫色线连接
    cv2.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 midpoints
    dA = 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 / args["width"]

    # compute the size of the object
    dimA = dA / pixelsPerMetric
    dimB = dB / pixelsPerMetric

    # draw the object sizes on the image
    cv2.putText(orig, "{:.1f}cm".format(dimA),
                (int(tltrX - 15), int(tltrY - 10)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)
    cv2.putText(orig, "{:.1f}cm".format(dimB),
                (int(trbrX + 10), int(trbrY)), cv2.FONT_HERSHEY_SIMPLEX,
                0.65, (255, 255, 255), 2)

    # show the output image
    cv2.imshow("Image", orig)
    cv2.waitKey(0)

https://www.leiphone.com/news/201806/Y6jQz5ZIQlQqJMwS.html
原文:https://www.pyimagesearch.com/2016/03/28/measuring-size-of-objects-in-an-image-with-opencv/
Measuring size of objects in an image with OpenCV ——第二篇
2016年3月28日
在这里插入图片描述

第三篇——使用OpenCV测量图像中物体之间的距离
https://www.sohu.com/a/429829672_823210
原文链接:https: //www.pyimagesearch.com/2016/04/04/measuring-distance-between-objects-in-an-image-with-opencv/

在这里插入图片描述

在计算机视觉,可以使用Python和OpenCV库来识别物体的颜色。以下是实现物体颜色识别的步骤: 1.导入OpenCV库和其他必要的库: ``` import cv2 import numpy as np ``` 2.读取图像并进行预处理: ``` img = cv2.imread('object.jpg') hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) ``` 3.设置颜色范围: ``` lower_color = np.array([0, 100, 100]) upper_color = np.array([10, 255, 255]) ``` 这里的颜色范围是根据要识别的物体颜色设置的。HSV颜色空间,H表示色调,S表示饱和度,V表示亮度。 4.使用颜色范围进行掩膜操作: ``` mask = cv2.inRange(hsv, lower_color, upper_color) ``` 这里使用cv2.inRange()函数来创建一个掩膜,将在颜色范围内的像素设置为255,其他像素设置为0。 5.对掩膜进行形态学操作: ``` kernel = np.ones((5, 5), np.uint8) mask = cv2.erode(mask, kernel, iterations=1) mask = cv2.dilate(mask, kernel, iterations=1) ``` 这里使用形态学操作来去除噪点,使掩膜更加平滑。 6.查找物体的轮廓: ``` contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ``` 这里使用cv2.findContours()函数查找掩膜的轮廓。 7.遍历轮廓并绘制矩形框: ``` for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) ``` 这里遍历轮廓并使用cv2.boundingRect()函数获取每个轮廓的矩形框。然后使用cv2.rectangle()函数在原图像绘制矩形框。 8.显示结果: ``` cv2.imshow('result', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 以上就是使用Python和OpenCV识别物体颜色的基本步骤。需要注意的是,颜色范围的设置和形态学操作的参数需要根据实际情况进行调整,以达到最佳效果。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值