CV_AG/Test_logic.py

53 lines
1.6 KiB
Python

import os
import pandas as pd
from ultralytics import YOLO
import cv2
# Input and output video paths
video_path = r'D:\AIM\pecan\GH014359.mp4'
video_path_out = r'D:\AIM\pecan\GH014359_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))
# Load the YOLO model
model = YOLO(r"D:\AIM\pecan\runs\detect\train2\weights\best.pt") # Load a custom model
threshold = 0.5
detected_cracked = False # Initialize a flag for detecting cracked pecans
while ret:
# Perform detection on the current frame
results = model(frame)[0]
for result in results.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = result
if score > threshold:
# Draw bounding boxes and labels
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 4)
label = results.names[int(class_id)].upper()
cv2.putText(frame, f"{label} {score:.2f}", (int(x1), int(y1 - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 1.3, (0, 255, 0), 3, cv2.LINE_AA)
# Check for the "cracked" label
if label == "CRACKED":
detected_cracked = True
# Write the processed frame to the output video
out.write(frame)
ret, frame = cap.read()
# Determine the final label based on detections
final_label = "CRACKED" if detected_cracked else "GOOD"
# Print the final label
print(f"Final Label: {final_label}")
# Release video resources
cap.release()
out.release()
cv2.destroyAllWindows()