YOLOv5+单目测量物体尺寸
时间: 2023-11-22 19:50:43 浏览: 491
YOLOv5+单目实现测距(python),原理比较简单
5星 · 资源好评率100%
以下是YOLOv5+单目测量物体尺寸的步骤:
1.相关配置
首先,需要安装YOLOv5和OpenCV库。可以使用以下命令安装:
```shell
!git clone https://github.com/ultralytics/yolov5.git
!pip install opencv-python
```
2.测距原理
单目测距是通过计算物体在图像上的像素大小和实际物体大小之间的比例来实现的。这个比例可以通过相机标定来获得。
3.相机标定
相机标定是通过拍摄已知大小的物体来确定相机的内部参数和外部参数。这里介绍两种标定方法。
3.1:标定方法1(针对图片)
首先,需要准备一组已知大小的棋盘格图片。然后,使用以下代码进行标定:
```python
import numpy as np
import cv2
# 准备棋盘格图片
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)
objpoints = [] # 存储物体点
imgpoints = [] # 存储图像点
images = glob.glob('*.jpg') # 图片路径
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
cv2.drawChessboardCorners(img, (7, 6), corners, ret)
cv2.imshow('img', img)
cv2.waitKey(500)
cv2.destroyAllWindows()
# 标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
```
3.2:标定方法2(针对视频)
首先,需要准备一段包含已知大小的棋盘格的视频。然后,使用以下代码进行标定:
```python
import numpy as np
import cv2
# 准备棋盘格图片
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)
objpoints = [] # 存储物体点
imgpoints = [] # 存储图像点
cap = cv2.VideoCapture('calibration_video.mp4') # 视频路径
while True:
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
cv2.drawChessboardCorners(frame, (7, 6), corners, ret)
cv2.imshow('frame', frame)
cv2.waitKey(500)
else:
break
cv2.destroyAllWindows()
# 标定
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
```
4.相机测距
4.1 测距添加
在YOLOv5的detect.py文件中添加以下代码:
```python
def get_distance(bbox, focal_length):
# 计算物体在图像上的像素大小
pixel_width = bbox[2] - bbox[0]
pixel_height = bbox[3] - bbox[1]
pixel_size = (pixel_width + pixel_height) / 2
# 计算物体在实际世界中的大小
real_size =
阅读全文