yolov8 如何计算FPS
时间: 2024-01-04 10:20:33 浏览: 234
根据提供的引用内容,以下是使用YOLOv8计算FPS的示例代码:
```python
import cv2
from datetime import datetime
# 加载YOLOv8模型
net = cv2.dnn.readNetFromDarknet("yolov3.cfg", "yolov3.weights")
# 获取输入层、输出层和类别标签
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
classes = ["person", "car", "bike"] # 根据你的实际类别进行修改
# 加载视频
cap = cv2.VideoCapture("video.mp4")
# 初始化计时器
start_time = datetime.now()
frame_count = 0
while True:
# 读取视频帧
ret, frame = cap.read()
if not ret:
break
# 对帧进行预处理
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# 解析检测结果
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5: # 设置置信度阈值
# 计算边界框的位置
center_x = int(detection[0] * frame.shape[1])
center_y = int(detection[1] * frame.shape[0])
width = int(detection[2] * frame.shape[1])
height = int(detection[3] * frame.shape[0])
left = int(center_x - width / 2)
top = int(center_y - height / 2)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# 绘制边界框和类别标签
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示帧
cv2.imshow("YOLOv8", frame)
if cv2.waitKey(1) == ord('q'):
break
# 更新计时器
frame_count += 1
if frame_count == 30: # 每30帧计算一次FPS
end_time = datetime.now()
elapsed_time = (end_time - start_time).total_seconds()
fps = frame_count / elapsed_time
print(f"FPS: {fps:.2f}")
frame_count = 0
start_time = datetime.now()
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
请注意,上述代码中的模型权重文件和配置文件需要根据你的实际情况进行修改。此外,你还需要安装OpenCV和numpy库。
阅读全文