import cv2import numpy as npimport timefrom ultralytics import YOLO# 加载YOLO模型def load_yolo(model_path): yolo = YOLO(model_path) return yolo# 车辆检测def detect_vehicles(yolo, frame): classes, scores, boxes = yolo(frame) vehicles = [] for i in range(len(classes)): if classes[i] == 'car' or classes[i] == 'truck': vehicles.append(boxes[i]) return vehicles# 时速估计def estimate_speed(prev_frame, curr_frame, vehicles): speed = [] for vehicle in vehicles: x1, y1, x2, y2 = vehicle prev_vehicle_roi = prev_frame[y1:y2, x1:x2] curr_vehicle_roi = curr_frame[y1:y2, x1:x2] prev_gray = cv2.cvtColor(prev_vehicle_roi, cv2.COLOR_BGR2GRAY) curr_gray = cv2.cvtColor(curr_vehicle_roi, cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prev_gray, curr_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0) flow_mean = np.mean(flow) speed.append(flow_mean * 30) # 假设每帧间隔为1/30秒 return speed# 绘制检测结果def draw_results(frame, vehicles, speeds): for i in range(len(vehicles)): x1, y1, x2, y2 = vehicles[i] cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.putText(frame, 'Vehicle ' + str(i+1) + ': ' + str(speeds[i]) + ' km/h', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# 主函数def main(): # 加载YOLO模型 yolo = load_yolo("yolov8n.pt") # 打开视频或摄像头 cap = cv2.VideoCapture(0) # 如果要打开视频,请将0改为视频文件的路径 # 初始化 prev_frame = None while True: # 读取当前帧 ret, frame = cap.read() if not ret: break # 车辆检测 vehicles = detect_vehicles(yolo, frame) # 时速估计 if prev_frame is not None: speeds = estimate_speed(prev_frame, frame, vehicles) else: speeds = [0] * len(vehicles) # 绘制检测结果 draw_results(frame, vehicles, speeds) # 显示检测结果 cv2.imshow('Vehicle Detection', frame) # 保存检测结果 cv2.imwrite('result.jpg', frame) # 按下q键退出 if cv2.waitKey(1) == ord('q'): break # 更新上一帧 prev_frame = frame.copy() # 释放资源 cap.release() cv2.destroyAllWindows()if __name__ == '__main__': main()整理好代码
时间: 2023-12-15 19:03:45 浏览: 192
keras读取h5文件load_weights、load代码操作
以下是整理好的代码,实现了车辆检测和时速估计,并且可以在视频或摄像头中实时显示检测结果:
```python
import cv2
import numpy as np
import time
from ultralytics import YOLO
# 加载YOLO模型
def load_yolo(model_path):
yolo = YOLO(model_path)
return yolo
# 车辆检测
def detect_vehicles(yolo, frame):
classes, scores, boxes = yolo(frame)
vehicles = []
for i in range(len(classes)):
if classes[i] == 'car' or classes[i] == 'truck':
vehicles.append(boxes[i])
return vehicles
# 时速估计
def estimate_speed(prev_frame, curr_frame, vehicles):
speed = []
for vehicle in vehicles:
x1, y1, x2, y2 = vehicle
prev_vehicle_roi = prev_frame[y1:y2, x1:x2]
curr_vehicle_roi = curr_frame[y1:y2, x1:x2]
prev_gray = cv2.cvtColor(prev_vehicle_roi, cv2.COLOR_BGR2GRAY)
curr_gray = cv2.cvtColor(curr_vehicle_roi, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prev_gray, curr_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
flow_mean = np.mean(flow)
speed.append(flow_mean * 30) # 假设每帧间隔为1/30秒
return speed
# 绘制检测结果
def draw_results(frame, vehicles, speeds):
for i in range(len(vehicles)):
x1, y1, x2, y2 = vehicles[i]
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, 'Vehicle ' + str(i+1) + ': ' + str(speeds[i]) + ' km/h', (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 主函数
def main():
# 加载YOLO模型
yolo = load_yolo("yolov8n.pt")
# 打开视频或摄像头
cap = cv2.VideoCapture(0) # 如果要打开视频,请将0改为视频文件的路径
# 初始化
prev_frame = None
while True:
# 读取当前帧
ret, frame = cap.read()
if not ret:
break
# 车辆检测
vehicles = detect_vehicles(yolo, frame)
# 时速估计
if prev_frame is not None:
speeds = estimate_speed(prev_frame, frame, vehicles)
else:
speeds = [0] * len(vehicles)
# 绘制检测结果
draw_results(frame, vehicles, speeds)
# 显示检测结果
cv2.imshow('Vehicle Detection', frame)
# 按下q键退出
if cv2.waitKey(1) == ord('q'):
break
# 更新上一帧
prev_frame = frame.copy()
# 释放资源
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
```
阅读全文