일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- Statistics
- node.js
- MongoDB
- 김양재 목사님
- 우리들교회
- nodeJS
- Deep learning
- 빅데이터
- probability
- No SQL
- openCV
- 김양재 목사
- 통계
- data science
- 빅데이타
- 김양재
- Artificial Intelligence
- 주일설교
- 데이터 과학
- Big Data
- 몽고디비
- c++
- Machine Learning
- 딥러닝
- 확률
- 빅 데이터
- 빅 데이타
- R
- 인공지능
- WebGL
- Today
- Total
Scientific Computing & Data Science
[Programming / OpenCV] OpenCV Video Processing 본문
Written by Geol Choi |
이번 포스팅에서는 Python-OpenCV를 이용한 Video Processing 방법에 대하여 알아보도록 하겠습니다.
Python-OpenCV 설치방법은 이 링크를 참고해 주시기 바랍니다.
1. Video Frame Capture
Video 경로(파일명 포함)를 지정하여 해당 비디오를 Frame-by-Frame으로 출력하는 코드입니다. 코드는 Self-explanatory하므로 따로 코드 설명을 추가하지는 않습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import cv2 ############################################################################### # parameters defined by user PATH_TO_INPUT_VIDEO_PATH = {YOUR_VIDEO_FILE_PATH} ############################################################################### def main(): # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name capture = cv2.VideoCapture(PATH_TO_INPUT_VIDEO_PATH) # Check if VideoCapture object is vliad if (capture.isOpened()== False): print("Error opening video stream or file") # Read until video is completed while(capture.isOpened()): # Capture frame-by-frame ret, frame = capture.read() if ret == True: # Display the resulting frame cv2.imshow('Frame', frame) # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break capture.release() # Closes all the frames cv2.destroyAllWindows() if __name__ == '__main__': main() | cs |
다만, 주의할 점은, {YOUR_VIDEO_FILE_PATH}는 대상 Video File의 경로(파일명 포함)를 넣어 주셔야 합니다. 만약, Video Path가 ../video/my_video.mp4
이라면,
PATH_TO_INPUT_VIDEO_PATH = '../video/my_video.mp4'
capture = cv2.VideoCapture(PATH_TO_INPUT_VIDEO_PATH)
capture = cv2.VideoCapture(0)
2. Video to Image Sequences
다음 코드는 비디오 파일을 이미지 시퀀스 파일로 저장하는 코드입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | # -*- coding: utf-8 -*- """ Created on Fri Oct 27 18:35:16 2017 Video to Image Sequence @author: Dr.Geol Choi """ import os import cv2 from matplotlib import pyplot as plt ############################################################################### # parameters defined by user PATH_TO_INPUT_VIDEO_PATH = {YOUR_VIDEO_FILE_PATH} PATH_TO_OUTPUT_IMAGES_DIR = {OUTPUT_IMAGE_SEQUENCES_PATH} ############################################################################### def main(): # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name cap = cv2.VideoCapture(PATH_TO_INPUT_VIDEO_PATH) # Check if camera opened successfully if (cap.isOpened()== False): print("Error opening video stream or file") # Read until video is completed cnt = 0 while(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if ret == True: OUTPUT_IMAGE_PATH = os.path.join(PATH_TO_OUTPUT_IMAGES_DIR, 'image_%09d.jpg' % (cnt)) print("Now %d-th images being processed..." % (cnt)) # save image plt.imsave(OUTPUT_IMAGE_PATH, frame) # Break the loop else: break cnt += 1 # When everything done, release the video capture object cap.release() if __name__ == '__main__': main() | cs |
마찬가지로, 코드가 간단하기 때문에 코드 설명은 생략합니다. 다만, {YOUR_VIDEO_FILE_PATH}에 대상 Video File의 경로를, {OUTPUT_IMAGE_SEQUENCES_PATH}에 이미지 시퀀스가 저장될 경로를 입력하시면 됩니다.
3. Image Sequences to Video
마지막으로, 이미지 시퀀스를 비디오 파일로 한데 뭉쳐 주는 코드입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | # -*- coding: utf-8 -*- """ Image Sequence to Video Created on Mon Oct 30 12:43:54 2017 @author: Dr.Geol Choi """ import os, errno import cv2 import numpy as np ############################################################################### # parameters defined by user PATH_TO_INPUT_IMAGES_PATH = {YOUR_INPUT_IMAGE_PATH} PATH_TO_OUTPUT_VIDEO_DIR = {YOUR_OUTPUT_VIDEO_DIRECTORY} VIDEO_FILE = {YOUR_OUTPUT_VIDEO_FILENAME} ############################################################################### def main(): ## make result directory if not exist try: if(os.path.isdir(PATH_TO_INPUT_IMAGES_PATH)): for root, dirs, files in os.walk(PATH_TO_INPUT_IMAGES_PATH, topdown=False): bIsFirst = True for name in files: cur_file = os.path.join(PATH_TO_INPUT_IMAGES_PATH, name) cur_img = cv2.imread(cur_file) print("Currently %s being processed..." % (cur_file)) if (type(cur_img) == np.ndarray): if (bIsFirst): frame_height = cur_img.shape[0] frame_width = cur_img.shape[1] # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file. video_file = os.path.join(PATH_TO_OUTPUT_VIDEO_DIR, VIDEO_FILE) out = cv2.VideoWriter(video_file, cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width, frame_height)) # record the current image frame to video file out.write(cur_img) bIsFirst = False except OSError as e: if e.errno != errno.EEXIST: raise # When everything done, release the video capture and video write objects out.release() if __name__ == '__main__': main() | cs |
앞의 코드들과 마찬가지로, {YOUR_INPUT_IMAGE_PATH}는 입력 이미지 시퀀스 경로(이미지 파일명 제외)를, {YOUR_OUTPUT_VIDEO_DIRECTORY}는 출력 비디오 디렉터리 경로를, {YOUR_OUTPUT_VIDEO_FILENAME}는 출력 비디오 파일명으로 대체하여 작성하시면 되겠습니다.
Useful Tips
1. 특정 Frame Number 이미지 얻어오기
1 2 3 4 | cap = cv2.VideoCapture(PATH_TO_INPUT_VIDEO_PATH) # Where frame_no is the frame you want cap.set(1, frame_no); | cs |
2. 영상의 Frame 전체 길이 얻어오기
1 2 3 4 | cap = cv2.VideoCapture(PATH_TO_INPUT_VIDEO_PATH) # total frame numbers frame_len = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) | cs |
이것으로 이번 포스팅을 마칩니다. Python-OpenCV를 이용하여 Video Processing에 유용하게 사용하시기 바랍니다.
'Programming > OpenCV' 카테고리의 다른 글
[Programming / OpenCV] Windows 환경에 Python-OpenCV 설치하기 (2) | 2017.10.28 |
---|---|
[Programming / OpenCV] 1초마다 지정 폴더에 이미지 저장하기 (1) | 2017.07.26 |
[OpenCV] Color를 Grayscale로 변환하기 (0) | 2016.08.07 |
[OpenCV] Histogram (0) | 2015.10.03 |
[OpenCV] Custom Color Map (0) | 2015.09.28 |