Untitled

 avatar
unknown
python
2 months ago
5.8 kB
4
Indexable
import cv2
import numpy as np
from openvino.runtime import Core

# Load mô hình OpenVINO
ie = Core()
model_path = "openvino_model.xml"  # Đảm bảo đúng tên file XML đã lưu
compiled_model = ie.compile_model(model_path, "CPU")

# Đọc video đầu vào
video_path = r"C:\Users\Huy\Pictures\video1.mp4"  # Đường dẫn video của bạn
cap = cv2.VideoCapture(video_path)

# Kiểm tra video có mở được không
if not cap.isOpened():
    print(f"Không thể mở video: {video_path}")
    exit()

# Lấy thông tin video và in ra để kiểm tra
fps = cap.get(cv2.CAP_PROP_FPS)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"Video FPS: {fps}")
print(f"Video size: {frame_width}x{frame_height}")

# Lấy thông tin kích thước đầu vào của mô hình
input_blob = compiled_model.input(0).any_name
input_shape = compiled_model.input(0).shape  # (1, 3, 640, 640)
input_size = (input_shape[2], input_shape[3])  # (640, 640)

# Danh sách các class của YOLOv8 (80 class COCO)
class_names = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat",
               "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
               "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack",
               "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball",
               "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket",
               "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
               "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake",
               "chair", "couch", "potted plant", "bed", "dining table", "toilet", "TV", "laptop",
               "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster",
               "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
               "hair drier", "toothbrush"]

# Đọc từng frame của video
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        print("Không thể đọc tiếp frame. Thoát...")
        break

    try:
        # Kiểm tra frame có rỗng không
        if frame is None:
            print("Frame rỗng")
            continue

        # Kiểm tra kích thước frame
        print(f"Frame shape: {frame.shape}")

        # Resize & Chuẩn hóa ảnh về [0,1]
        resized_frame = cv2.resize(frame, input_size)
        normalized_frame = resized_frame.astype(np.float32) / 255.0
        input_tensor = np.expand_dims(normalized_frame.transpose(2, 0, 1), axis=0)

        # Chạy mô hình OpenVINO
        results = compiled_model([input_tensor])[compiled_model.output(0).any_name]
        
        # Debug thông tin
        print("Results shape:", results.shape)
        
        # Xử lý đầu ra YOLOv8
        boxes = []
        scores = []
        class_ids = []
        conf_threshold = 0.25

        # Lấy kích thước frame gốc
        img_h, img_w = frame.shape[:2]

        # Chuyển đổi kết quả (1, 84, 8400) -> (8400, 84)
        predictions = np.transpose(results[0])
        
        # Lấy scores và class_ids
        scores = np.max(predictions[:, 4:], axis=1)
        class_ids = np.argmax(predictions[:, 4:], axis=1)
        
        # Lọc các dự đoán có confidence > threshold
        mask = scores > conf_threshold
        boxes_detected = predictions[mask, :4]
        scores_detected = scores[mask]
        class_ids_detected = class_ids[mask]
        
        if len(boxes_detected) > 0:
            # Chuyển đổi xywh -> xyxy
            boxes_detected[:, 0] = boxes_detected[:, 0] - boxes_detected[:, 2] / 2  # x1
            boxes_detected[:, 1] = boxes_detected[:, 1] - boxes_detected[:, 3] / 2  # y1
            boxes_detected[:, 2] = boxes_detected[:, 0] + boxes_detected[:, 2]      # x2
            boxes_detected[:, 3] = boxes_detected[:, 1] + boxes_detected[:, 3]      # y2
            
            # Scale boxes về kích thước ảnh gốc
            boxes_detected[:, [0, 2]] *= img_w
            boxes_detected[:, [1, 3]] *= img_h
            
            # Chuyển về int
            boxes_detected = boxes_detected.astype(np.int32)
            
            # Áp dụng NMS
            indices = cv2.dnn.NMSBoxes(
                boxes_detected.tolist(), 
                scores_detected.tolist(),
                conf_threshold, 
                0.45
            )
            
            # Vẽ các box
            for i in indices:
                box = boxes_detected[i]
                x1, y1, x2, y2 = box
                
                # Vẽ box
                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
                
                # Vẽ label
                label = f"{class_names[class_ids_detected[i]]}: {scores_detected[i]:.2f}"
                cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # Hiển thị kết quả
        cv2.imshow("YOLOv8 OpenVINO Video Detection", frame)

        # Thêm độ trễ và kiểm tra phím thoát
        key = cv2.waitKey(1) & 0xFF  # Giảm độ trễ xuống 1ms
        if key == ord('q'):
            break

    except Exception as e:
        print(f"Lỗi xử lý frame: {str(e)}")
        import traceback
        traceback.print_exc()
        break

# Giải phóng tài nguyên
cap.release()
cv2.destroyAllWindows()
Editor is loading...
Leave a Comment