CV_AG/Test_video.py

52 lines
1.5 KiB
Python

import os
import pandas as pd
from ultralytics import YOLO
import cv2
video_path = r'D:\AIM\lemon\test.mp4'
video_path_out = r'D:\AIM\lemon\test_out.mp4'
cap = cv2.VideoCapture(video_path)
ret, frame = cap.read()
H, W, _ = frame.shape
out = cv2.VideoWriter(video_path_out, cv2.VideoWriter_fourcc(*'MP4V'), int(cap.get(cv2.CAP_PROP_FPS)), (W, H))
model_path = os.path.join('.', 'runs', 'detect', 'train', 'weights', 'last.pt')
# Load a model
model = YOLO(r"D:\AIM\lemon\YOLO-Training\YOLOv11_finetune\weights\best.pt") # load a custom model
threshold = 0.5
classifications = []
while ret:
results = model(frame)[0]
for result in results.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = result
if score > threshold:
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 4)
cv2.putText(frame, results.names[int(class_id)].upper(), (int(x1), int(y1 - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 1.3, (0, 255, 0), 3, cv2.LINE_AA)
# percentage =
# if results.names[int(class_id)] in classifications:
# else:
classifications.append(results.names[int(class_id)])
out.write(frame)
ret, frame = cap.read()
# Create a new DataFrame from the classifications
new_df = pd.DataFrame(classifications)
# Write the new DataFrame to an Excel file
new_df.to_excel('output_classifications.xlsx', index=False)
cap.release()
out.release()
cv2.destroyAllWindows()