# coding=utf-8
# 导入一些后续需要使用到的python包
# 可能需要 pip install imutils
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)
# 设置一些需要改变的参数
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 centimeter)")
ap.add_argument("-a", "--area", type=float, required=True,
help="area of the left-most object in the image (in centimeter)")
args = vars(ap.parse_args())
# 读取输入图片
# 输入图片灰度化
# 对灰度图片执行高斯滤波
# 对滤波结果做边缘检测获取目标
image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
edged = cv2.Canny(gray, 50, 100)
# 使用膨胀和腐蚀操作进行闭合对象边缘之间的间隙
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# 在边缘图像中寻找物体轮廓(即物体)
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# 对轮廓按照从左到右进行排序处理
(cnts, _) = contours.sort_contours(cnts)
# 初始化 'pixels per metric'
pixelsPerMetric = None
pixelsPerArea = None
# 循环遍历每一个轮廓
for c in cnts:
# 如果当前轮廓的面积太少,认为可能是噪声,直接忽略掉
if cv2.contourArea(c) < 100:
continue
# 根据物体轮廓计算出外切矩形框
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")
# 按照top-left, top-right, bottom-right, bottom-left的顺序对轮廓点进行排序,并绘制外切的BB,用绿色的线来表示
box = perspective.order_points(box)
cv2.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)
# 绘制BB的4个顶点,用红色的小圆圈来表示
for (x, y) in box:
cv2.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)
# 分别计算上左tl和上右tr的中心点和下左bl和下右br的中心点坐标
(tl, tr, br, bl) = box
(X1, Y1) = midpoint(tl, tr) # 上中
(X2, Y2) = midpoint(bl, br) # 下中
# 分别计算上左tl和下左bl的中心点和上右tr和下右br的中心点坐标
(X3, Y3) = midpoint(tl, bl) # 左中
(X4, Y4) = midpoint(tr, br) # 右中
# 绘制BB的4条边的中心点,用蓝色的小圆圈来表示
cv2.circle(orig, (int(X1), int(Y1)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(X2), int(Y2)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(X3), int(Y3)), 5, (255, 0, 0), -1)
cv2.circle(orig, (int(X4), int(Y4)), 5, (255, 0, 0), -1)
# 在中心点之间绘制直线,用紫红色的线来表示
cv2.line(orig, (int(X1), int(Y1)), (int(X2), int(Y2)),
(255, 0, 255), 2)
cv2.line(orig, (int(X3), int(Y3)), (int(X4), int(Y4)),
(255, 0, 255), 2)
# 计算两个中心点之间的欧氏距离,即图片距离
dA = dist.euclidean((X1, Y1), (X2, Y2))
dB = dist.euclidean((X3, Y3), (X4, Y4))
# 初始化测量指标值,参考物体在图片中的宽度已经通过欧氏距离计算得到,参考物体的实际大小已知
if pixelsPerMetric is None:
pixelsPerMetric = dB / args["width"]
hull = cv2.convexHull(c)
epsilon = 0.00000001 * cv2.arcLength(hull, True)
approx = cv2.approxPolyDP(hull, epsilon, True)
cv2.drawContours(orig, [approx], -1, (0, 255, 0), 3)
area = cv2.contourArea(approx)
# 计算目标的实际大小(宽和高),用英尺来表示
if pixelsPerArea is None:
pixelsPerArea = area / args["area"]
dimA = dA / pixelsPerMetric
dimB = dB / pixelsPerMetric
true_area = area / pixelsPerArea
# 在图片中绘制结果
cv2.putText(orig, "{:.2f}cm".format(dimA),
(int(X2 - 15), int(Y2 - 10)), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (0, 0, 0), 2)
cv2.putText(orig, "{:.2f}cm".format(dimB),
(int(X4 + 10), int(Y4)), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (0, 0, 0), 2)
#x1, y1 = approx[0][0]
x1, y1 =int(X1),int(Y1)
cv2.putText(orig, "{:.2f}cm2".format(true_area),
(x1, y1), cv2.FONT_HERSHEY_SIMPLEX,
0.65, (0, 0, 0), 2)
# 显示结果
img_resized = cv2.resize(orig, (800, 800))
cv2.imshow("Image", img_resized)
cv2.waitKey(0)
自己用的面积计算
于 2025-02-19 16:47:30 首次发布