3. 비디오 입력 출력
3.1 VideoCapture
opencv에서 동영상 입력 부분을 관리하는 함수 입니다. 모든 디바이스의 입출력은 파일 처리와
비슷하기 때문에 파일 처리를 해보았다면 사용되는 method등이 좀 다를 뿐 작업 방식도 비슷합니다.
cv2.VideoCapture() → <VideoCapture
object>
VideoCapture() 함수를 사용 했을 때 리턴되는 오브젝트
인데 양이 너무 많아 지면 낭비이니 심심하실 때 ‘VideoCapture class’로 검색하면 자료를
찾을 수 있습니다.
cv2.VideoCapture(filename) →
<VideoCapture object>
cv2.VideoCapture(device) → <VideoCapture
object>
parameter |
내용 |
filename |
동영상 파일
명 또는 이미지 파일명 |
device |
연결된 영산
장치 index (하나만 있는 경우 0) |
VideoCapture() 함수에 파일 명을 넣으면 저장된 비디오를
불러오고 0, 1 등을 넣으면
입력 디바이스 순서(한개인 경우 0)에 따라 실시간 촬영
frame을 받아 올 수 있습니다.
- 비디오 파일 읽기
기존 동영상 파일을 읽어와 창을 생성하고 frame이 끝날 때 까지
보여주는 예제 입니다.
import cv2
videoFile1 = 'F:/Python/images/video001.mp4
cap = cv2.VideoCapture(videoFile1)
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
cv2.imshow('video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows() |
![opencv_video](https://t1.daumcdn.net/cfile/tistory/99602D355CA599321F)
- 디바이스 읽기
디바이스 장치로 부터 frame을 하나씩 읽어와 생성된 창에 보여줍니다. 디바이스로 부터 읽은 영상은 화면 크기를
조절할 수 있습니다.
import cv2
cap = cv2.VideoCapture(0)
# 화면 크기 설정
cap.set(3,320)
cap.set(4,240)
while True:
ret, frame = cap.read()
if ret:
cv2.imshow('video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows() |
![opencv_video](https://t1.daumcdn.net/cfile/tistory/995BDE355CA5993329)
3.2 VideoCapture Method
cv2.VideoCapture.open(filename) → retval
비디오 파일을 불러오는 경우 파일명을 사용하여 오픈 합니다.
cv2.VideoCapture.open(device) → retval
영상 장치를 이용하는 경우 디바이스 index 값으로 오픈 합니다.
cv2.VideoCapture.isOpened() → retval
파일이 정상적으로 open 되었는가 여부를 알아보는 것으로 사용 가능
하면 True를 리턴합니다.
cv2.VideoCapture.release() → None
open된 비디오 파일이나 영상 장치를 닫습니다.
cv2.VideoCapture.grab() → retval
비디오 파일이나 영상 장치로 부터 다름 frame을 가져옵니다. 성공 시 True를 리턴 합니다.
cv2.VideoCapture.retrieve([image[, flag]])
→ retval, image
grab한 frame을
decode해서 돌려 줍니다. frame이 없을 경우 False를
리턴 합니다.
cv2.VideoCapture.read([image]) → retval,
image
grab()과 retrieve() 함수와
같이 사용되며 decode frame을 읽어 옵니다. frame이 없을 경우 False를
리턴 합니다.
cv2.VideoCapture.get(propId) → retval
캡처한 영상의 속성을 리턴 합니다.
parameter
|
내용
|
cv2.CAP_PROP_POS_MSEC
|
Current position of the video file in milliseconds
or video capture timestamp
|
cv2.CAP_PROP_POS_FRAMES
|
0-based index of the frame to be decoded/captured
next
|
cv2.CAP_PROP_POS_AVI_RATIO
|
Relative position of the video file: 0 - start of
the film, 1 - end of the film
|
cv2.CAP_PROP_FRAME_WIDTH
|
Width of the frames in the video stream
|
cv2.CAP_PROP_FRAME_HEIGHT
|
Height of the frames in the video stream
|
cv2.CAP_PROP_FPS
|
Frame rate
|
cv2.CAP_PROP_FOURCC
|
4-character code of codec
|
cv2.CAP_PROP_FRAME_COUNT
|
Number of frames in the video file
|
cv2.CAP_PROP_FORMAT
|
Format of the Mat objects returned by retrieve()
|
cv2.CAP_PROP_MODE
|
Backend-specific value indicating the current
capture mode
|
cv2.CAP_PROP_BRIGHTNESS
|
Brightness of the image (only for cameras)
|
cv2.CAP_PROP_CONTRAST
|
Contrast of the image (only for cameras)
|
cv2.CAP_PROP_SATURATION
|
Saturation of the image (only for cameras)
|
cv2.CAP_PROP_HUE
|
Hue of the image (only for cameras)
|
cv2.CAP_PROP_GAIN
|
Gain of the image (only for cameras)
|
cv2.CAP_PROP_EXPOSURE
|
Exposure (only for cameras)
|
cv2.CAP_PROP_CONVERT_RGB
|
Boolean flags indicating whether images should be
converted to RGB
|
cv2.CAP_PROP_WHITE_BALANCE
|
Currently not supported
|
cv2.CAP_PROP_RECTIFICATION
|
Rectification flag for stereo cameras (note: only
supported by DC1394 v 2.x backend currently)
|
cv2.VideoCapture.set(propId, value) →
retval
캡처한 영상의 속성값을 설정 합니다.
parameter | 내용 |
propId | get() 속성 값과 같음 |
value | 속성 값 |
- method 사용 예
import cv2
videoFile1 =
'F:/Python/images/video001.avi'
cap = cv2.VideoCapture(videoFile1)
# get()
frame_width =
cap.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(frame_width, frame_height, end=',')
# grab(), retrieve(), read()
if cap.grab():
flg, frame = cap.retrieve()
if flg:
cv2.imshow('video', frame)
flg2, frame2 = cap.read()
if flg2:
cv2.imshow('video2', frame2)
cap.release()
cv2.waitKey(0)
cv2.destroyAllWindows() |
- cv2.VideoCapture.get() 실습 해보기
![cv2 VideoCapture get opencv](https://t1.daumcdn.net/cfile/tistory/99343D3A5D548AB311)
cv2.VideoCapture.get()은 cap = cv2.VideoCapture(videoFile1) 이렇게 해서 cap
변수에 File을 받아오고 cap.get()으로
파일에 대한 설정 값을 얻어 옵니다. 하단에
print문을 이용하여 cap.get()으로 받아온 동영상의 size 852, 480을 출력해 보았습니다. 아래는 video 출력
결과입니다.
![cv2 VideoCapture get opencv](https://t1.daumcdn.net/cfile/tistory/99348F3A5D548AB411)
3.3 VideoWriter
VideoWriter() 함수를 이용하여 frame을 파일에 출력 합니다.
cv2.VideoWriter([filename, fourcc, fps,
frameSize[, isColor]]) → <VideoWriter object>
parameter
|
내용
|
filename
|
저장할 동영상 파일명
|
fourcc
|
frame 압축 관련 4자리 code
|
fps
|
초당 저장할 frame
|
frameSize
|
frame size (가로, 세로)
|
isColor
|
컬러 저장 여부.
|
cv2.VideoWriter.open(filename, fourcc, fps,
frameSize[, isColor]) → retval
VideoWriter() 함수를 초기화 하거내 재 초기화를 진행 합니다.
cv2.VideoWriter.isOpened() → retval
비디오 저장의 초기화 유무를 리턴 합니다. (True, False)
cv2.VideoWriter.write(image) → None
저장 파일에 다음 frame을 기록 합니다.
cv2.VideoWriter_fourcc(c1, c2, c3, c4) →
retval
fourcc code를 리턴 합니다.
- Device frame 저장
import cv2
videoFile1 =
'F:/Python/images/video001.avi'
cap = cv2.VideoCapture(0)
# 화면 크기 설정
cap.set(3,320)
cap.set(4,240)
# 파일 쓰기
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter(videoFile1, fourcc,
25.0, (320,240))
while True:
ret, frame = cap.read()
if ret:
out.write(frame)
cv2.imshow('video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows() |
- 도형 그리기 저장
꼭 동영상이나 디바이스 입력을 출력하는건 아닙니다. frame을 생성할 수 있는 것이면 출력이 가능 합니다. 도형을 회전시키면서 저장을 해보겠습니다.
import numpy as np
import cv2
import time
videoFile1 =
'F:/Python/images/video003.avi'
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter(videoFile1, fourcc,
25.0, (384,384))
#cv2.VideoWriter.open(filename, fourcc,
fps, frameSize[, isColor])
# color 설정
blue_color = (255, 0, 0)
green_color = (0, 255, 0)
red_color = (0, 0, 255)
white_color = (255, 255, 255)
# 모두 0으로 되어 있는
빈 Canvas(검정색)
img = np.zeros((384, 384, 3), np.uint8)
for i in range(0, 90):
pt1
= cv2.ellipse2Poly((200, 200), (100, 160), i, 0, 360, 50)
img = cv2.ellipse(img, (200, 200), (100, 160), 0, 0, 360, white_color,
2)
img = cv2.polylines(img, [pt1], False, green_color, 2)
out.write(img)
time.sleep(0.5) # 너무 빨리 진행되지
않도록
print('end')
out.release()
cv2.waitKey(0)
cv2.destroyAllWindows() |
![opencv_video](https://t1.daumcdn.net/cfile/tistory/99FF85355CA599332C)