Python OpenCV - 대화형 모드 설정하기

BANG·2020년 11월 28일
0

OpenCV

목록 보기
7/16

대화형 모드 설정(interactive-on / interactive-off)

import cv2
import matplotlib.pyplot as plt
 
########### 카메라 대신 youtube영상으로 대체 ############
import pafy
url = 'https://www.youtube.com/watch?v=u_Q7Dkl7AIk'
video = pafy.new(url)
print('title = ', video.title)
print('video.rating = ', video.rating)
print('video.duration = ', video.duration)
 
best = video.getbest(preftype='mp4')     # 'webm','3gp'
print('best.resolution', best.resolution)
 
cap=cv2.VideoCapture(best.url)
#########################################################
 
#1
def handle_key_press(event):	# 키보드가 눌린 이벤트
    if event.key == 'escape':	# esc키가 눌렸는지 조건 확인
        cap.release()
        plt.close()       
        
def handle_close(evt):	# 어떻게든 종료하면 아래 내용이 출력되게 하기
    print('Close figure!')
    cap.release()
 
#2 프로그램 시작    
#cap = cv2.VideoCapture(0) # 0번 카메라
 
plt.ion() # 대화모드 설정(interactive-on), 동영상이 실행중이나, esc키나 닫기버튼 등을 인식
 
# 그림(frame)의 크기 설정
fig = plt.figure(figsize=(10, 6)) # fig.set_size_inches(10, 6)
plt.axis('off')	# 그림(frame)의 눈금 표시 안하기
 
#ax = fig.gca()
#ax.set_axis_off()
 
fig.canvas.set_window_title('Video Capture')	# 창의 제목
 
# 이벤트를 이벤트 핸들러에 연결
# 연결을 끊을 때까지 이벤트를 듣기 시작
# key_press_event(키를 누르는 이벤트)를 handle_key_press란 이벤트 핸들러에 연결
fig.canvas.mpl_connect('key_press_event', handle_key_press)
fig.canvas.mpl_connect('close_event', handle_close)	# 창을 close하는 이벤트를 연결
 
retval, frame = cap.read() # 첫 프레임 캡처(읽어오기)
 
# 컬러 변환을 한 후, 이미지 보여주기
im = plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
 
#3
while True:
    retval, frame = cap.read() # 프레임 캡처(읽어오기)
    if not retval:	# 카메라 종료 및 영상의 끝이면
        break    
        
#    plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    im.set_array(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    fig.canvas.draw()	# 이미지(frame) 보여주기
#   fig.canvas.draw_idle()
 
	# 프레임(플롯, 그래프 등)을 업데이트
    # 버퍼에 있는 최신 것까지 내보내기
    fig.canvas.flush_events()  # plt.pause(0.001)
    
if cap.isOpened():
    cap.release()
profile
Record Everything!!

0개의 댓글