以下是使用OpenCV库计算目标的长、宽和面积的代码:

import cv2

# 读取图像
image = cv2.imread('target.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 二值化处理
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 遍历所有轮廓
for contour in contours:
    # 计算轮廓的矩
    moments = cv2.moments(contour)

    # 计算目标的面积
    area = moments['m00']

    # 计算目标的中心坐标
    cx = int(moments['m10'] / area)
    cy = int(moments['m01'] / area)

    # 计算目标的长和宽
    x, y, w, h = cv2.boundingRect(contour)
    width = w
    height = h

    # 打印结果
    print('目标的长: ', width)
    print('目标的宽: ', height)
    print('目标的面积: ', area)

# 在图像上绘制轮廓
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

# 显示图像
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

请确保将代码中的'target.jpg'替换为您的目标图像的文件路径。运行代码后,将会输出目标的长、宽和面积,并在图像上绘制出轮廓。同时,会弹出一个窗口显示图像。


原文地址: http://www.cveoy.top/t/topic/o2Kq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录