Python OpenCV - matplotlib.animation

BANG·2020년 11월 28일
0

OpenCV

목록 보기
8/16

matplotlib.animation

  • 데이터가 너무 길어 한 화면에 담아보면 구분이 되지 않거나, 시간의 흐름에 대해 강조
  • FuncAnimation() 은 반복적으로 함수를 호출하여 애니메이션을 만듬
import cv2
import matplotlib.pyplot as plt
import matplotlib.animation as animation
 
########### 카메라 대신 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)	# VideoCapture 객체 생성
#########################################################
 
# 프로그램 시작    
#cap = cv2.VideoCapture(0)
fig = plt.figure(figsize=(10, 6)) # fig : 플롯(frame, 그래프)이 업데이트 될 객체
fig.canvas.set_window_title('Video Capture')	# 창 제목
plt.axis('off')
 
def init():
    global im
    retval, frame = cap.read() # 첫 프레임 캡처
    im = plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    # return im,
 
def updateFrame(k): 
    retval, frame = cap.read()	# 프레임 읽어오기
    if retval:	# 읽어온것이 성공(True)하면
        im.set_array(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))	# 프레임 정보를 가지고 색상 변환 작업 진행
 
# interval : ms단위의 프레임 간 지연 시간
# animation함수로 fig창에 init으로 초기화하고 50 msec마다 updateFrame을 읽어옴
ani = animation.FuncAnimation(fig, updateFrame, init_func=init, interval=50)
plt.show()	# 보여주기

if cap.isOpened():	# VideoCapture 객체 초기화 확인
    cap.release()	# VideoCapture 자원(resource) 반환하기

import cv2
import matplotlib.pyplot as plt
import matplotlib.animation as animation
 
########### 카메라 대신 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)
#########################################################
 
class Video:
    # 첫 프레임을 가져오기(맛보기용, 정보 확인용)
    def __init__(self, device=0):
        self.cap=cv2.VideoCapture(best.url)
        #self.cap = cv2.VideoCapture(device)	# 카메라로 영상 가져올 때 사용
        self.retval, self.frame = self.cap.read()
        self.im = plt.imshow(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB))
        print('start capture ...')
       
    def updateFrame(self, k):
        self.retval, self.frame = self.cap.read()
        self.im.set_array(cv2.cvtColor(camera.frame, cv2.COLOR_BGR2RGB))
        # return self.im,
 
    def close(self):
        if self.cap.isOpened():
            self.cap.release()
        print('finish capture.')
 
# 프로그램 시작 
fig = plt.figure()	# 플롯(frame, 그래프)이 업데이트 될 객체
fig.canvas.set_window_title('Video Capture')	# fig의 제목(타이틀)
plt.axis("off")	# 눈금 표시 안하기
 
camera = Video()	# Video 클래스 생성
ani = animation.FuncAnimation(fig, camera.updateFrame, interval=50)
plt.show()
camera.close()

import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
 
class Video(animation.FuncAnimation):	# FuncAnimation을 상속
    def __init__(self, device=0, fig=None, frames=None,
                       interval=80, repeat_delay=5, blit=False, **kwargs):
        if fig is None:
            self.fig, self.ax = plt.subplots(1, 2, figsize=(10,5))
            self.fig.canvas.set_window_title('Video Capture')
            self.ax[0].set_position([0, 0, 0.5, 1])
            self.ax[0].axis('off')
 
            self.ax[1].set_position([0.5, 0, 0.5, 1])
            self.ax[1].axis('off')
            # plt.subplots_adjust(left=0,bottom=0,right=1,top=1,
            #                     wspace=0.05,hspace=0.05)
          
        # super().메서드 : 자식 클래스에서 부모클래스의 내용을 사용하고 싶을경우 사용
        # super(현재클래스명, self) : 현재 클래스가 어떤 클래스인지 명확하게 표시
        super(Video, self).__init__(self.fig, self.updateFrame, init_func=self.init,
                                   frames=frames, interval=interval, blit=blit,
                                   repeat_delay=repeat_delay, **kwargs)        
        self.cap = cv2.VideoCapture(device)
        print('start capture ...')
        
    def init(self): 
        retval, self.frame = self.cap.read()
        if retval:
            self.im0 = self.ax[0].imshow(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB),
                                      aspect = 'auto')
            self.im1 = self.ax[1].imshow(np.zeros(self.frame.shape, self.frame.dtype),
                                      aspect = 'auto')                    
    def updateFrame(self, k):
        retval, self.frame = self.cap.read()
        if retval:
            self.im0.set_array(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB))
 
            gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
            self.im1.set_array(cv2.merge((gray,gray,gray)))
            
    def close(self):
        if self.cap.isOpened():
            self.cap.release()
        print('finish capture.')
 
 
# 프로그램 시작 
camera = Video()
plt.show()
camera.close()
profile
Record Everything!!

0개의 댓글