박민혀기

Capture to the score frame in streaming video game (Template Match) for Python 본문

OpenCV

Capture to the score frame in streaming video game (Template Match) for Python

박민혀기 2023. 12. 14. 16:13
import cv2
import numpy as np

cap = cv2.VideoCapture('Watermelon_Rec.mp4')
if not cap.isOpened():
    print("Error: Could not open video file.")
    exit()

template = cv2.imread('Watermelon_Score_ROI.PNG')
if template is None:
    print("Error: Could not open or read the template image.")
    exit()
template = cv2.resize(template, (0, 0), fx=0.5, fy=0.5)

total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
start_frame = int(9 * total_frames / 10)

cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)

while True:
    ret, frame = cap.read()
    if not ret:
        break
    frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)

    result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    threshold = 0.7
    if max_val > threshold:
        top_left = max_loc
        bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
        cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)

        accuracy_text = f"Accuracy: {round(max_val, 2)}"
        cv2.putText(frame, accuracy_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

 

'OpenCV' 카테고리의 다른 글

Install OpenCV Lite 4.5 on Raspberry Pi  (2) 2024.11.08
Capture to the score frame in streaming video game (Template Match) for Python  (0) 2023.12.20
MeanShitf 예제  (0) 2023.06.23
OpenCV selectROI() API  (0) 2023.06.23
OpenCV Include, Lib, PATH  (0) 2023.02.03