본문 바로가기

메이커활동/HW&SW

OpenCV 사용을 위한 Python 개인스터디 03 - 비디오

1. Capture video from camera


import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
# Capture frame-by-frame
ret, frame = cap.read()

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()



2. Saving a video

저장을 위해 필요한 코덱이 미리 설치되어 있어야 한다. 모니터화면을 동영상으로 저장하는 oCam 을 설치하면 Xvid 코덱이 설치된다. 일반 동영상플레이어 설치시 설치되는 Xvid 코덱은 읽기용 코덱이라 여기에서 사용되는 것과 다르다. Xvid 쓰기용 코덱을 설치한다. ( http://goo.gl/v63QJ5 )


import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)

# write the flipped frame
out.write(frame)

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

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()



3. Playing video from file


import numpy as np
import cv2

cap = cv2.VideoCapture('output.avi')

while(cap.isOpened()):
ret, frame = cap.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

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

cap.release()
cv2.destroyAllWindows()