OpenCV图像距离检测

代码实现:

import cv2

import numpy as np

def calculate_distance(p1, p2, focal_length, known_width):

    """

    计算两点之间的实际距离

    :param p1: 点1坐标

    :param p2: 点2坐标

    :param focal_length: 相机焦距

    :param known_width: 已知物体的实际宽度

    :return: 两点之间的实际距离

    """

    # 计算像素距离

    pixel_distance = np.linalg.norm(np.array(p1) - np.array(p2))

   

    # 计算实际距离

    distance = (known_width * focal_length) / pixel_distance

    return distance

def detect_distance(image_path, focal_length, known_width):

    """

    检测图像中物体之间的距离

    :param image_path: 图像路径

    :param focal_length: 相机焦距

    :param known_width: 已知物体的实际宽度

    """

    # 读取图像

    image = cv2.imread(image_path)

    if image is None:

        print("无法读取图像")

        return

    # 创建窗口

    cv2.namedWindow("Distance Detection")

    points = []

    def mouse_callback(event, x, y, flags, param):

        if event == cv2.EVENT_LBUTTONDOWN:

            if len(points) < 2:

                points.append((x, y))

                cv2.circle(image, (x, y), 5, (0, 255, 0), -1)

                if len(points) == 2:

                    # 计算距离

                    distance = calculate_distance(points[0], points[1], focal_length, known_width)

                    cv2.line(image, points[0], points[1], (255, 0, 0), 2)

                    cv2.putText(image, f"Distance: {distance:.2f} cm",

                               (10, 30), cv2.FONT_HERSHEY_SIMPLEX,

                               1, (0, 0, 255), 2)

            cv2.imshow("Distance Detection", image)

    cv2.setMouseCallback("Distance Detection", mouse_callback)

    while True:

        cv2.imshow("Distance Detection", image)

        key = cv2.waitKey(1) & 0xFF

        if key == ord('q') or key == 27:  # 按q或ESC退出

            break

    cv2.destroyAllWindows()

if __name__ == "__main__":

    # 示例参数

    image_path = "example.jpg"  # 替换为实际图像路径

    focal_length = 1000  # 相机焦距(需要根据实际情况调整)

    known_width = 10  # 已知物体的实际宽度(单位:厘米)

    detect_distance(image_path, focal_length, known_width)

你可能感兴趣的:(计算机视觉项目,opencv,计算机视觉,人工智能,python)