点击下方卡片,关注“机器视觉与AI深度学习”
视觉/图像重磅干货,第一时间送达!
背景介绍
在人工神经网络和计算机视觉领域,物体识别和跟踪是极其重要的技术,可以应用于无数的项目,其中许多可能不是很明显,例如使用这些算法来测量距离或物体的速度。因此,我向你介绍一个旨在使用 YOLOv8 测量高速公路上汽车速度的 Python 项目,目的是让你了解这些算法如何在日常解决方案中使用。
实现步骤
pip install ultralytics
pip install opencv-python
pip install --no-cache "lapx>=0.5.2"
https://docs.ultralytics.com/tasks/detect/#models
https://www.youtube.com/watch?v=-59Mr4UTgNg%27
完整代码:
from ultralytics import YOLO
from ultralytics.solutions import speed_estimation
import cv2
model = YOLO("yolov8s.pt")
names = model.model.names
cap = cv2.VideoCapture("src.mp4")
assert cap.isOpened(), "Error reading video file"
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
video_writer = cv2.VideoWriter("out.avi",
cv2.VideoWriter_fourcc(*'mp4v'),
fps,
(w, h))
line_pts = [(0, 400), (1280, 400)]
speed_obj = speed_estimation.SpeedEstimator()
speed_obj.set_args(reg_pts=line_pts,
names=names,
view_img=True)
while cap.isOpened():
success, im0 = cap.read()
if not success:
print("Video frame is empty or video processing has been successfully completed.")
break
tracks = model.track(im0, persist=True, show=False)
im0 = speed_obj.estimate_speed(im0, tracks)
video_writer.write(im0)
cap.release()
video_writer.release()
cv2.destroyAllWindows()
代码解释
model = YOLO("yolov8s.pt")
这里yolov8s 模型已足够。
tracks = model.track(im0, persist=True, show=False)
line_pts = [(0, 400), (1280, 400)] #绘制从屏幕一侧到另一侧的线
speed_obj.set_args(reg_pts=line_pts, names=names, view_img=True)
line_pts = [(0, 400), (1280, 400)]
speed_obj = speed_estimation.SpeedEstimator()
speed_obj.set_args(reg_pts=line_pts,
names=names,
view_img=True)
—THE END—
觉得有用,麻烦给个赞和在看