python通过摄像头参数和图片计算物体距离

python通过摄像头参数和图片计算物体距离

要从图像中计算摄像头到物体的距离,您需要知道一些额外信息,如物体的实际尺寸、相机的内参等

import cv2
import numpy as np

def calculate_distance(focal_length, known_width, pixel_width):
    # 计算距离
    distance = (known_width * focal_length) / pixel_width
    return distance

def estimate_focal_length(known_distance, known_width, pixel_width):
    # 估计相机焦距
    focal_length = (pixel_width * known_distance) / known_width
    return focal_length

def detect_object(image_path):
    # 读取图像
    image = cv2.imread(image_path)

    # 进行对象检测,例如使用Haar级联分类器或YOLO等算法
    # 检测到对象后,获取对象的边界框宽度(以像素为单位)

    # 假设我们已经检测到物体并获取了边界框宽度
    object_width_pixels = 100

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

    # 已知的相机焦距(单位:像素)
    known_focal_length_pixels = 1000

    # 估计相机焦距
    estimated_focal_length = estimate_focal_length(known_distance, known_width_cm, object_width_pixels)

    # 计算物体到相机的距离
    distance_cm = calculate_distance(estimated_focal_length, known_width_cm, object_width_pixels)

    return distance_cm

# 调用函数进行距离估计
distance = detect_object("image.jpg")
print(f"物体与摄像头的距离为:{distance} 厘米")

你可能感兴趣的:(opencv,python,开发语言)