반응형

웹캠 / 비디오 파일에서 가져온 이미지에 fps 표시하여 화면에 출력하는 OpenCV Python 예제 코드입니다. 

 

2022. 03. 06  최초작성

 

2023. 09. 10 웹캠/비디오 파일을 성공적으로 열었는지 여부를 체크






# 참고
# https://github.com/dgseten/bad-cv-tfm/blob/2ada9b71f85aa5eb75c1f4a039cb14d697ee2f69/tools/video/video-player-wait-fps.py
# https://stackoverflow.com/a/65146731

import cv2
import time


# 이미지에 텍스트를 출력하는 함수
def draw_text(img, text, x, y):
    font = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 1
    font_thickness = 2
    text_color=(255, 0, 0)
    text_color_bg=(0, 0, 0)

    text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness)
    text_w, text_h = text_size
    offset = 5

    cv2.rectangle(img, (x - offset, y - offset), (x + text_w + offset, y + text_h + offset), text_color_bg, -1)
    cv2.putText(img, text, (x, y + text_h + font_scale - 1), font, font_scale, text_color, font_thickness)


# 웹캠 사용시
cap = cv2.VideoCapture(0)
# 비디오 파일 사용시
# cap = cv2.VideoCapture('test.mp4')

if not cap.isOpened():
    print("웹캠/비디오 파일을 열 수 없습니다.")
    exit(0)
else:
    print("웹캠/비디오 파일을 성공적으로 열었습니다.")

# 웹캠에서 fps 값 획득
fps = cap.get(cv2.CAP_PROP_FPS)
print('fps', fps)

if fps == 0.0:
    fps = 30.0

time_per_frame_video = 1/fps
last_time = time.perf_counter()


while True:

    # 웹캠에서 이미지 읽어옴
    ret,img_color = cap.read()

    if ret == False:
        print('웹캠에서 영상을 읽을 수 없습니다.')
        break


    # fsp 계산
    time_per_frame = time.perf_counter() - last_time
    time_sleep_frame = max(0, time_per_frame_video - time_per_frame)
    time.sleep(time_sleep_frame)

    real_fps = 1/(time.perf_counter()-last_time)
    last_time = time.perf_counter()


    x = 30
    y = 50
    text = '%.2f fps' % real_fps

    # 이미지의 (x, y)에 텍스트 출력
    draw_text(img_color, text, x, y)
    cv2.imshow("Color", img_color)


    # ESC키 누르면 중지
    if cv2.waitKey(1)&0xFF == 27:
        break

cap.release()
cv2.destroyAllWindows()


반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts