基于OpenCV的摄像头测距(2022-1-1)

基于OpenCV的摄像头测距

前言

去年暑假参加了一个比赛,比赛内容中需要确定目标的位置 本来想全用图像完成的,最后发现不是很符合要求。比完赛之后,就忙别的事了。直到现在突然想试试摄像头测距。就来了

基于OpenCV的摄像头测距(2022-1-1)

; 一、测距原理

摄像头单目测距原理及实现

空间的深度或距离等数据的摄像头。

人的眼睛长在头部的前方,两只眼的视野范围重叠,两眼同时看某一物体时,产生的视觉称为双眼视觉。

双眼视觉的优点是可以弥补单眼视野中的盲区缺损,扩大视野,并产生立体视觉。

基于OpenCV的摄像头测距(2022-1-1)
f为摄像头的焦距,c为镜头光心

模型的主要依据公式为f/d=h/H,设物体所在平面与相机平面的距离为d,物体实际高度为H,在传感器上的高度为h
根据这个模型,我们就能求出目标物体与我们的摄像头平面的距离。

分两种情况,但是这两种情况的条件都是假设实际物体与摄像机所在平面平行。

一种是当物体主线段过光心的情况,这种情况是最容易计算的, 即 h=sqrt ((横坐标之差Dx)2+(纵坐标之差Dy)2), Dx为每个像素的宽度,Dy为每个像素的高度,

二、代码

1.引入库

代码如下(示例):

import cv2
from cvzone.HandTrackingModule import HandDetector
import math
import numpy as np
import cvzone

2.读入数据

调用电脑摄像头,或者外接别的摄像头也可以
调用 cvzone 自带的手部检测器

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)
detector = HandDetector(detectionCon=0.8, maxHands=1)

编写函数,转化为距离循环打印显示

while True:
    success, img = cap.read()
    hands = detector.findHands(img, draw=False)

    if hands:
        lmList = hands[0]['lmList']
        x, y, w, h = hands[0]['bbox']
        x1, y1 = lmList[5]
        x2, y2 = lmList[17]

        distance = int(math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2))
        A, B, C = coff
        distanceCM = A * distance ** 2 + B * distance + C

        print(distanceCM, distance)

        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 3)
        cvzone.putTextRect(img, f'{int(distanceCM)} cm', (x+5, y-10))

    cv2.imshow("Image", img)
    cv2.waitKey(1)

完整代码

import cv2
from cvzone.HandTrackingModule import HandDetector
import math
import numpy as np
import cvzone

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = HandDetector(detectionCon=0.8, maxHands=1)

x = [300, 245, 200, 170, 145, 130, 112, 103, 93, 87, 80, 75, 70, 67, 62, 59, 57]
y = [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
coff = np.polyfit(x, y, 2)

while True:
    success, img = cap.read()
    hands = detector.findHands(img, draw=False)

    if hands:
        lmList = hands[0]['lmList']
        x, y, w, h = hands[0]['bbox']
        x1, y1 = lmList[5]
        x2, y2 = lmList[17]

        distance = int(math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2))
        A, B, C = coff
        distanceCM = A * distance ** 2 + B * distance + C

        print(distanceCM, distance)

        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 3)
        cvzone.putTextRect(img, f'{int(distanceCM)} cm', (x+5, y-10))

    cv2.imshow("Image", img)
    cv2.waitKey(1)

效果图:
在这里插入图片描述

基于OpenCV的摄像头测距(2022-1-1)

总结

通过简单的几行代码,就可以实现视频测距。我是以手为检测目标测距,当然你也可以,调用别的分类检测器,搭配目标检测网络实现各种物体的检测 测距。(建议备一个,高清的摄像头。)
本项目的视频测距的 误差 大概在±2cm左右。

Original: https://blog.csdn.net/pidzhengding/article/details/122271109
Author: 天涯尽头黄鹤楼
Title: 基于OpenCV的摄像头测距(2022-1-1)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/648966/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球