[python] Python-비디오 프레임 추출 및 저장

그래서 저는 이 튜토리얼을 따랐 지만 아무것도하지 않는 것 같습니다. 단순히 아무것도. 몇 초간 기다렸다가 프로그램을 닫습니다. 이 코드에 어떤 문제가 있습니까?

import cv2
vidcap = cv2.VideoCapture('Compton.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  success,image = vidcap.read()
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
  if cv2.waitKey(10) == 27:                     # exit if Escape is hit
      break
  count += 1

또한 댓글에서 프레임을 1000으로 제한한다고 말합니다. 왜?

편집 : 나는 success = True먼저 시도했지만 도움이되지 않았습니다. 0 바이트 인 이미지를 하나만 만들었습니다.



답변

에서 여기 이 다운로드 비디오를 우리가 시험 같은 비디오 파일을 그래서. 파이썬 코드와 같은 디렉토리에 mp4 파일이 있는지 확인하십시오. 그런 다음 동일한 디렉토리에서 파이썬 인터프리터를 실행해야합니다.

그런 다음 코드를 수정 waitKey하고 시간을 낭비하는 도랑 도 창 없이는 키보드 이벤트를 캡처 할 수 없습니다. 또한 success프레임을 성공적으로 읽고 있는지 확인하기 위해 값을 인쇄합니다 .

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1

어떻게 되나요?


답변

누군가가 모든 프레임을 추출하고 싶지 않지만 1 초마다 프레임을 추출하려는 경우 약간 다른 경우에 대해이 질문 (@ user2700065의 답변)을 확장합니다. 따라서 1 분짜리 동영상은 60 프레임 (이미지)을 제공합니다.

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    count = 0
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    success = True
    while success:
        vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))    # added this line 
        success,image = vidcap.read()
        print ('Read a new frame: ', success)
        cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
        count = count + 1

if __name__=="__main__":
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)


답변

이것은 @GShocked의 python 3.x에 대한 이전 답변의 조정입니다. 댓글에 게시하지만 충분한 평판이 없습니다.

import sys
import argparse

import cv2
print(cv2.__version__)

def extractImages(pathIn, pathOut):
    vidcap = cv2.VideoCapture(pathIn)
    success,image = vidcap.read()
    count = 0
    success = True
    while success:
      success,image = vidcap.read()
      print ('Read a new frame: ', success)
      cv2.imwrite( pathOut + "\\frame%d.jpg" % count, image)     # save frame as JPEG file
      count += 1

if __name__=="__main__":
    print("aba")
    a = argparse.ArgumentParser()
    a.add_argument("--pathIn", help="path to video")
    a.add_argument("--pathOut", help="path to images")
    args = a.parse_args()
    print(args)
    extractImages(args.pathIn, args.pathOut)


답변

이것은 대부분의 비디오 형식을 비디오에있는 프레임 수로 변환하는 기능입니다. 그것은 Python3함께 작동합니다OpenCV 3+

import cv2
import time
import os

def video_to_frames(input_loc, output_loc):
    """Function to extract frames from input video file
    and save them as separate frames in an output directory.
    Args:
        input_loc: Input video file.
        output_loc: Output directory to save the frames.
    Returns:
        None
    """
    try:
        os.mkdir(output_loc)
    except OSError:
        pass
    # Log the time
    time_start = time.time()
    # Start capturing the feed
    cap = cv2.VideoCapture(input_loc)
    # Find the number of frames
    video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print ("Number of frames: ", video_length)
    count = 0
    print ("Converting video..\n")
    # Start converting the video
    while cap.isOpened():
        # Extract the frame
        ret, frame = cap.read()
        # Write the results back to output location.
        cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
        count = count + 1
        # If there are no more frames left
        if (count > (video_length-1)):
            # Log the time again
            time_end = time.time()
            # Release the feed
            cap.release()
            # Print stats
            print ("Done extracting frames.\n%d frames extracted" % count)
            print ("It took %d seconds forconversion." % (time_end-time_start))
            break

if __name__=="__main__":

    input_loc = '/path/to/video/00009.MTS'
    output_loc = '/path/to/output/frames/'
    video_to_frames(input_loc, output_loc)

그것은 지원 .mts및 일반 파일 좋아 .mp4하고 .avi. .mts파일 에 대해 시도하고 테스트했습니다 . 매력처럼 작동합니다.


답변

프레임을 비디오로 변환하는 방법에 대한 많은 연구 끝에이 기능이 도움이되기를 바랍니다. 이를 위해 opencv가 필요합니다.

import cv2
import numpy as np
import os

def frames_to_video(inputpath,outputpath,fps):
   image_array = []
   files = [f for f in os.listdir(inputpath) if isfile(join(inputpath, f))]
   files.sort(key = lambda x: int(x[5:-4]))
   for i in range(len(files)):
       img = cv2.imread(inputpath + files[i])
       size =  (img.shape[1],img.shape[0])
       img = cv2.resize(img,size)
       image_array.append(img)
   fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
   out = cv2.VideoWriter(outputpath,fourcc, fps, size)
   for i in range(len(image_array)):
       out.write(image_array[i])
   out.release()


inputpath = 'folder path'
outpath =  'video file path/video.mp4'
fps = 29
frames_to_video(inputpath,outpath,fps)

자신의 로컬 위치에 따라 fps (초당 프레임 수), 입력 폴더 경로 및 출력 폴더 경로 값을 변경하십시오.


답변

이전 답변은 첫 번째 프레임을 잃었습니다. 그리고 이미지를 폴더에 저장하는 것이 좋습니다.

# create a folder to store extracted images
import os
folder = 'test'
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__)  # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
    success,image = vidcap.read()
    if not success:
        break
    cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image)     # save frame as JPEG file
    count += 1
print("{} images are extacted in {}.".format(count,folder))

덧붙여서 VLC로 프레임 래트를 확인할 수 있습니다 . 창-> 미디어 정보-> 코덱 세부 정보로 이동합니다.


답변

이 코드는 비디오에서 프레임을 추출하고 프레임을 .jpg 형식으로 저장합니다.

import cv2
import numpy as np
import os

# set video file path of input video with name and extension
vid = cv2.VideoCapture('VideoPath')


if not os.path.exists('images'):
    os.makedirs('images')

#for frame identity
index = 0
while(True):
    # Extract images
    ret, frame = vid.read()
    # end of frames
    if not ret:
        break
    # Saves images
    name = './images/frame' + str(index) + '.jpg'
    print ('Creating...' + name)
    cv2.imwrite(name, frame)

    # next frame
    index += 1