def create_video(radio: Radio): if not os.path.exists(Video.output_dir): print("Folder", Video.output_dir, 'does not exist. Creating...') os.makedirs(Video.output_dir) video = VideoWriter(Video.output_dir + os.sep + str(radio.radio_id) + '_temp.mp4', Video.fourcc, Video.fps, (Video.width, Video.height)) clip_count = len(radio.timestamps) - 1 for i in range(clip_count): if (radio.timestamps[i] not in radio.timeline.keys()): print(radio.timestamps[i], "has no corresponding image, load cover as backup") frame = Frame.create_cover(radio) else: frame = Frame.create_page(radio.timeline[radio.timestamps[i]], radio) frame_count = (radio.timestamps[i + 1] - radio.timestamps[i]) * Video.fps for j in range(frame_count): video.write(frame) video.release() video_clip = VideoFileClip(Video.output_dir + os.sep + str(radio.radio_id) + '_temp.mp4') print(video_clip.duration) audio_clip = AudioFileClip(os.sep.join(['.', 'cache', str(radio.radio_id), 'audio', radio.audio.local_name])) video_clip.audio = audio_clip if config['test']: video_clip = video_clip.subclip(0, min(200, video_clip.duration)) video_clip.write_videofile(Video.output_dir +os.sep+ str(radio.radio_id)+" "+radio.title +".mp4", fps=Video.fps) print("{} finished!".format(radio.title)) os.remove(Video.output_dir+os.sep+str(radio.radio_id)+'_temp.mp4')
def jpg_to_video(char_image_path, FPS): video_fourcc = VideoWriter_fourcc( *"MP42") # 设置视频编码器,这里使用使用MP42编码器,可以生成更小的视频文件 char_img_path_list = [ char_image_path + r'/{}.jpg'.format(i) for i in range(1, number + 1) ] # 生成目标字符图片文件的路径列表 char_img_test = Image.open(char_img_path_list[1]).size # 获取图片的分辨率 if not os.path.exists('video'): os.mkdir('video') video_writter = VideoWriter('video/new_char_video.avi', video_fourcc, FPS, char_img_test) sum = len(char_img_path_list) count = 0 for image_path in char_img_path_list: img = cv2.imread(image_path) video_writter.write(img) end_str = '100%' count = count + 1 process_bar(count / sum, start_str='', end_str=end_str, total_length=15) video_writter.release() print('\n') print('=======================') print('The video is finished!') print('=======================')
def photo2video(videoName='./cache/output.mp4', fps=25, imgs='./cache/output_img'): '''将图片转换为视频,图片读取路径./cache/output_img.mp4,视频默认写入路径./movie/output.mp4,待合成图片默认文件夹路径./cache/output_img INPUTS videoName 视频写入路径 fps 视频帧率 imgs 待合成图片文件夹路径 OUTPUTS None ''' #获取图像分辨率 img = cv2.imread(imgs + '/1.jpg') sp = img.shape height = sp[0] width = sp[1] size = (width, height) fourcc = VideoWriter_fourcc(*'mp4v') videoWriter = VideoWriter(videoName, fourcc, fps, size) photos = os.listdir(imgs) for photo in range(len(photos)): frame = cv2.imread(imgs + '/' + str(photo) + '.jpg') videoWriter.write(frame) videoWriter.release() #合成新生成的视频和音频 if (os.path.exists('./movie/output.mkv')): os.remove('./movie/output.mkv') command = 'ffmpeg -i ./movie/output.mp4 -i ./cache/audio/audio.wav -c copy ./movie/output.mkv' subprocess.call(command, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) #os.remove('./cache/output.mp4') print('[*] 生成视频成功,路径为./cache/output.mkv')
def _write_frames_to_videofile(self, filename, path=None): '''Write frames to videofile ''' # Init openCV VideoWriter fourcc = VideoWriter_fourcc(*self.options["codec"]) if path is not None: filename_out = os.path.join( path, '{0}.{1}'.format(filename, self.options["container"])) else: filename_out = './{0}.{1}'.format(filename, self.options["container"]) # print(filename_out) video = VideoWriter( filename_out, fourcc, float(self.options["fps"]), (self.options["image_width"], self.options["image_height"]), isColor=False ) # path, codec, fps, size. Note, the isColor the flag is currently supported on Windows only # Write frames to videofile frame-by-frame for index in np.arange(self.frames.shape[2]): video.write(self.frames[:, :, index]) video.release()
def move_image_on_background(pattern, background): ''' The function creates a video of the pattern moving horizontally over a given background Parameters: ----------- pattern: <np.array, 35x35> The pattern supposed to move over the background background: <np.array, 260x346> A white background of the given size ''' fourcc = VideoWriter_fourcc(*'HFYU') video = VideoWriter('./videos/moving_pattern_for_sampling_exp.avi', fourcc, 30, (346, 260)) background[112:147, 0:35] = pattern frame = background count = 0 for _ in range(0, 346-34): cv2.imwrite("video_images/frame%04d.png" % count, cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)) video.write(cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)) shifted_frame = np.roll(frame, 1, axis=1) frame = shifted_frame video.write(frame) count+=1 cv2.destroyAllWindows() video.release()
def ult2vid(ult_data, dir_file, filename_no_ext, n_width, n_height, FramesPerSec): print(filename_no_ext + ' - ULT video started') output_file_no_ext = dir_file + filename_no_ext n_frames = len(ult_data) # compressed # fourcc = VideoWriter_fourcc(*'MP4V') # uncompressed 8-bit fourcc = VideoWriter_fourcc(*'Y800') video = VideoWriter(output_file_no_ext + '.avi', fourcc, float(FramesPerSec), (n_width, n_height), 0) # video = VideoWriter(output_file_no_ext + '.mp4', fourcc, float(FramesPerSec), (n_width, n_height), 0) for n in range(n_frames): frame = np.rot90(np.uint8(ult_data[n]).reshape(n_width, n_height, 1)) video.write(frame) print('frame ', n, ' done', end='\r') video.release() print(filename_no_ext + ' - ULT video finished, n_frames: ', n_frames)
def jpg_to_video(char_image_path, FPS): video_fourcc = VideoWriter_fourcc( *"MP42") # 设置视频编码器,这里使用使用MP42编码器,可以生成更小的视频文件 char_img_path_list = [ char_image_path + r'/{}.jpg'.format(i) for i in range(1, number + 1) ] #生成目标字符图片文件的路径列表 char_img_test = Image.open(char_img_path_list[1]).size #获取图片的分辨率 video_writter = VideoWriter('video/new_char_video.avi', video_fourcc, FPS, char_img_test) load = 'loading' count = 0 #用来清空load进度条的计数 for image_path in char_img_path_list: img = cv2.imread(image_path) video_writter.write(img) load = load + '.' count += 1 if count % 50 == 0: load = 'loading' print() print('\r', load, end='') video_writter.release() print('\n') print('=======================') print('The video is finished!') print('=======================')
def make_video(photos_path, video_path, video_name): cap = VideoCapture(v_path) fps = cap.get(CAP_PROP_FPS) cap.release() mkdir(video_path) images_cnt = jpgcount(photos_path) print(f'{images_cnt} imagenes') img = [] # Cargar las imágenes for i in range(images_cnt): img.append(imread(photos_path + '/frame' + str(i) + '.jpg')) height, width, _ = img[1].shape # Inicializar el video video = VideoWriter(video_path + '/' + video_name + '.mp4', VideoWriter_fourcc(*'MP4V'), fps, (width, height)) print('Codificando video') # Insertar cada imagen for j in range(images_cnt): video.write(img[j]) # Cerrar proceso destroyAllWindows() video.release() print('Video Codificado')
def generate_view(self, endpointBoxes, video): # TODO: move this somewhere that makes more sense. Perhaps just the writer setup logic points = [] # Setup the output device fourcc = VideoWriter_fourcc(*'mp4v') num_frames, video_width, video_height, fps = get_video_parameters( video) video_out = VideoWriter("views/output_boxes.mp4", fourcc, fps, (video_height, video_width)) # Loop through the video frame_number = 0 while video.isOpened(): # Read a frame of the video frames_remain, frame = video.read() # Stop reading if we reach the end of the video if not frames_remain: break frame_lp = self._slice_frame(endpointBoxes, frame, frame_number) video_out.write(frame_lp) frame_number += 1 # Reset the video capture to frame 0 video.set(CAP_PROP_POS_FRAMES, 0) return
class OutputVideoWriter(object): def __init__(self, file_name, fps, height, width, is_color): self.file_name = file_name self.height = height self.width = width self.is_color = is_color self.fps = fps self.dimension = width, height print(type(file_name)) print(type(fps)) print(type(self.dimension)) print(type(is_color)) self.video = VideoWriter(file_name, VideoWriter_fourcc(*"XVID"), fps, self.dimension, is_color) def write(self, frame): """ Write frame to file """ self.video.write(frame) print("Written") def set_dimension(self, width, height): """ Set dimensions for frame """ self.height = height self.width = width def release_video(self): """ Release video cap """ self.video.release()
def create_thermal_video(self, data): # Transforme la valeur de temperature des pixels en une valeur RGB # Ecrit cette valeur dans fourcc = VideoWriter_fourcc(*'MP42') video = VideoWriter(self.store_path +'thermal.avi', fourcc, float(self.FPS), (self.WIDTH, self.HEIGHT)) for frame in data["therm"]: colored_image = [] for row in frame: colored_row = [] for pixel in row: colored_image.append(self.convert_to_color(pixel)) colored_image.append(colored_row) image = np.uint8(colored_image) video.write(image) video.realease() self.resize_thermal_video()
async def make_video_and_upload(self): outvid = self.OUTPUT_VIDEO_NAME fps = 24; size = (320, 240); is_color = 1; fourcc = VideoWriter_fourcc(*'XVID') vid = None images = [] for i in range(0, self.max_count): images.append(self.VIDEO_IMAGES_FOLDER_NAME+"/image" + str(i) + ".jpg") for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() self.insta.uploadVideo("video.avi", thumbnail=self.OUTPUT_IMAGE_NAME, caption="#memorieswithcozmo");
def draw_speed(video_path: str, speed_path: str, output_video: str) -> None: reader = VideoCapture(video_path) writer = VideoWriter( output_video, VideoWriter_fourcc(*"mp4v"), 20, (640, 480), ) data = loadtxt(speed_path, delimiter="\n", dtype="float32") frame_id = 0 while reader.isOpened(): ret, frame = reader.read() if not ret: break putText( frame, f"{data[frame_id]:0.3f}", (250, 420), FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, ) writer.write(frame) frame_id += 1 if frame_id == data.shape[0]: break reader.release() writer.release()
class VideoOutput(): def __init__(self, opt): self.out_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch)) self.out_file = os.path.join(self.out_dir, opt.name + opt.phase + ".avi") self.writer = None if (os.path.exists(self.out_file)): os.remove(self.out_file) def writeFrame(self, visuals): i = 0 for label, im_data in visuals.items(): im = util.tensor2im(im_data) #.transpose(2,1,0) if (i == 0): display = im else: display = np.concatenate((display, im), axis=1) i += 1 #print(display.shape) if (self.writer == None): dims = display.shape[1], display.shape[0] self.writer = VideoWriter(self.out_file, VideoWriter_fourcc(*"XVID"), 30.0, dims, True) self.writer.write(cv2.cvtColor(display, cv2.COLOR_RGB2BGR)) def close(self): self.writer.release()
def makeanimation(): from cv2 import VideoWriter, VideoWriter_fourcc import glob # get width, heigth, frames f = open("./frames/0.ppm", "r") line0 = f.readline() line1 = f.readline().split(" ") width, height = int(line1[0]), int(line1[1]) frames = len(glob.glob("./frames/*.ppm")) FPS = 60 fourcc = VideoWriter_fourcc(*'mp4v') video = VideoWriter('./fractal.mp4', fourcc, float(FPS), (width, height)) frame = np.zeros((height, width, 3), dtype=np.uint8) for i in range(frames): f = open(f"./frames/{i}.ppm", "r") line0 = f.readline() line1 = f.readline() for x in range(height): for y in range(width): c = float(f.readline().split(" ")[0])%256 frame[x, y] = [c, c, c] video.write(frame) print(f"Writing frame {i}") video.release() print("done")
class LowQualityWriter: def __init__(self, fps=30): self.fps = fps self.tmp_dir = None self.tmp_video_path = None self.video_writer = None def _initialize_video(self, frame): self.tmp_dir = tempfile.TemporaryDirectory() self.tmp_video_path = os.path.join(self.tmp_dir.name, 'video.avi') fourcc = VideoWriter_fourcc(*'MJPG') height, width, _ = frame.shape self.video_writer = VideoWriter(self.tmp_video_path, fourcc, float(self.fps), (width, height)) def add_frame(self, frame): if self.tmp_dir is None: self._initialize_video(frame) self.video_writer.write(np.flip(frame, axis=2)) def write(self, output_path): self.video_writer.release() abs_output_path = pathlib.Path(output_path).with_suffix( '.avi').absolute() os.makedirs(os.path.dirname(abs_output_path), exist_ok=True) shutil.move(self.tmp_video_path, abs_output_path) self.tmp_dir.cleanup() self.tmp_dir = None print(f'Video written to: {abs_output_path}')
def insert_frame_to_avi_movie(avi_file, n_frames_to_add_at_beg): movie = OpenCvVideoReader(avi_file) n_frames = movie.length dir_name = os.path.dirname(avi_file) base_name = os.path.basename(avi_file) size_avi = movie.width, movie.height fps_avi = 20 new_avi_file_name = os.path.join( dir_name, f"{base_name[:-4]}_NEW_SHIFT_{n_frames_to_add_at_beg}_frames.avi") is_color = True # put fourcc to 0 for no compression # fourcc = 0 fourcc = VideoWriter_fourcc(*"XVID") vid_avi = VideoWriter(new_avi_file_name, fourcc, fps_avi, size_avi, is_color) for frame_index in np.arange(n_frames_to_add_at_beg): frame_img = movie.get_frame(0) frame_img[:] = 0 vid_avi.write(frame_img) # https://stackoverflow.com/questions/44947505/how-to-make-a-movie-out-of-images-in-python start_time = time() for frame_index in np.arange(n_frames): frame_img = movie.get_frame(frame_index) # vid_avi.write(img) vid_avi.write(frame_img) vid_avi.release() time_to_convert = time() - start_time print(f"time_to_convert: {time_to_convert} sec")
def videoconvert(inp): capture = VideoCapture(inp) inp_ext = inp.split(".") fpsin = capture.get(CAP_PROP_FPS) count = 0 success = 1 while success: success, image = capture.read() if (success == False and image == None): pass else: imwrite("zzimg%d.jpg" % count, image) count += 1 outfile = inp_ext[0] + '_output.mp4' fourcc = VideoWriter_fourcc(*'DIVX') fpsout = fpsin img = imread("zzimg0.jpg") height, width, layers = img.shape size = (width, height) out = VideoWriter(outfile, fourcc, fpsout, size, 0) for i in range(count): img = imread("zzimg%d.jpg" % i, 0) out.write(img) print( "Video Converted to Grayscale, Please check the folder for the output file: ", outfile) out.release() capture.release() return outfile
def build_video_from_files(directory: str, filename: str, fps: int, size: tuple=None, is_color: bool=True, format: str="XVID"): """ Create a video from a folder of images, sorted by filename. By default, the video will have the size of the first image. It will resize every image to this size before adding them to the video. :param directory: path to files :param filename: name of video :param fps: frames per second :param size: video dimensions :param is_color: colour video :param format: see http://www.fourcc.org/codecs.php :return: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html """ fourcc = VideoWriter_fourcc(*format) vid = None for file in sorted(os.listdir(directory)): if not os.path.exists(file): raise FileNotFoundError(file) image = imread(file) if vid is None: if size is None: size = image.shape[1], image.shape[0] vid = VideoWriter(filename, fourcc, fps, size, is_color) try: if size[0] != image.shape[1] and size[1] != image.shape[0]: image = resize(image, size) except AttributeError: print(file) vid.write(image) vid.release() return vid
def convert_frames_to_video(self, frame_array, debug_frame_array): """ Takes list of frames and converts them to a video Parameters ---------- frame_array : [] Frames to be converted. """ height, width, layers = frame_array[0].shape size = (width, height) date = time.strftime("%c") date = time.strftime("%Y-%m-%d %H:%M") path_out = str(date) + '_' + str(self.count) path_out = path_out.replace(" ", "_") path_out = path_out.replace(":", "") print(path_out) self.count += 1 out = VideoWriter(path_out + '.avi', VideoWriter_fourcc('M', 'J', 'P', 'G'), self.fps, size) for i in range(len(frame_array)): out.write(frame_array[i]) out.release() path_out = "debug-" + path_out + '_' + str(self.confidence) out = VideoWriter(path_out + '.avi', VideoWriter_fourcc('M', 'J', 'P', 'G'), self.fps, size) for i in range(len(debug_frame_array)): out.write(debug_frame_array[i]) out.release() self.trigger = False
def generate_vid(dir_path, vid_format='XVID', outvid=None, fps=25, size=None, is_color=True): from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize fourcc = VideoWriter_fourcc(*vid_format) # out = cv2.VideoWriter(video_name, fourcc, 20.0, (640,480)) vid = None images = [str(p) for p in pathlib.Path(dir_path).iterdir()] natural_sort(images) for image in images: if not os.path.exists(image): raise Exception('Image path does not exist: %s' % image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() return vid
class Processer: def __init__(self, input_file, output_file, FPS=30, max_count=-1): self.vidcap = VideoCapture(input_file) success, self.image = self.vidcap.read() self.width = int(self.vidcap.get(4)) self.height = int(self.vidcap.get(3)) fourcc = VideoWriter_fourcc(*'XVID') self.videoWriter = VideoWriter(output_file, fourcc, float(FPS), (self.height, self.width)) self.max_count = max_count def run(self, proc_func, end_proc=None): count = 0 success = True while success and (count < self.max_count or self.max_count == -1): result = proc_func(self.image, count, self.width, self.height) self.videoWriter.write(result) success, self.image = self.vidcap.read() print('Count:', count) count += 1 if end_proc is not None: end_proc(self.videoWriter) self.videoWriter.release() self.vidcap.release() print('Total count:', count)
def save_vid(filename, image_stack, codec='MJPG', fps=30, **kwargs): """Saves image stack as a video file (better compression than gifs) Args: ----- filename (str): path to savefile image_stack (np.ndarray): image stack in [z/t,x,y,c] format codec (str): opencv fourcc compatible codec, 4 char long str """ fourcc = VideoWriter_fourcc(*codec) out = VideoWriter(filename, fourcc, fps, image_stack.shape[1:3][::-1], **kwargs) # Rescale for video compatible format if not image_stack.dtype is np.uint8: image_stack = ((image_stack - image_stack.min()) / (image_stack.max() - image_stack.min()) * 255).astype('uint8') # image_stack = np.clip(image_stack *255, 0,255).astype('uint8') for i in range(image_stack.shape[0]): if image_stack.shape[-1] == 1: out.write(cvtColor(image_stack[i], COLOR_GRAY2RGB)) elif image_stack.shape[-1] == 3: out.write(image_stack[i]) else: raise ValueError( f"Wrong number of channels for frame, should be 1 or 3, is {image_stack[i].shape[-1]}" ) out.release()
class Video_writer(): def __init__(self, videosource, fps, width, height, result): print("Initializing video writer.") self.audiofile = "tempaudio.mp3" self.videosource = videosource self.tempresult = "tempres.avi" try: if path.exists(self.tempresult): remove(self.tempresult) except WindowsError: print "Tempresult is being used" self.result = result fourcc = VideoWriter_fourcc(*'XVID') self.out = VideoWriter(self.tempresult, fourcc, fps, (int(width), int(height))) def get_audio_clip(self): if path.exists(self.audiofile): remove(self.audiofile) mv.ffmpeg_extract_audio(self.videosource, self.audiofile) return def merge_audio_video(self): print("Merging audio and video.") self.get_audio_clip() mv.ffmpeg_merge_video_audio(self.tempresult, self.audiofile, self.result) remove(self.audiofile) def write_frame(self, frame): # test # if not self.start: # self.start_window() #self.frame.DisplayNext(frame) #self.img.set_img(frame) #test #cv2.imshow('prototype',frame) self.out.write(frame) def finish_video(self, sound=True): print("Finishing video.") self.out.release() if sound: try: self.merge_audio_video() except: shutil.copy2(self.tempresult, self.result) else: shutil.copy2(self.tempresult, self.result) remove(self.tempresult) def quit(self): print("Quiting.") self.out.release() if path.exists(self.audiofile): remove(self.audiofile) if path.exists(self.tempresult): remove(self.tempresult)
def generate_standalone_pendulum_video(): FPS = 60 width = 640 height = 480 radius = 25 SCALE_FACTOR = 400 L = 0.52 * SCALE_FACTOR # Make it look large in the frame T = 2 A = 30 * np.pi / 180 TMAX = 10 TS = 0.01 offset_x = width // 2 offset_y = height // 4 fourcc = VideoWriter_fourcc(*'MP42') video = VideoWriter('./pendulum.avi', fourcc, float(FPS), (width, height)) for t in range(0, int(10 / TS), int(1 / (TS * FPS))): frame = np.full((height, width, 3), 65535, dtype=np.uint8) # Fill white angle = A * np.sin(2 * np.pi * t * TS / T) circ_x = offset_x + int(L * np.sin(angle)) circ_y = offset_y + int(L * np.cos(angle)) cv2.line(frame, (offset_x, offset_y), (circ_x, circ_y), (100, 100, 100), 10) cv2.circle(frame, (circ_x, circ_y), radius, (0, 0, 0), -1) video.write(frame) video.release()
def playCvMontage(cap, mon, title="Montage", filename="mon.avi", subtitle=None, placeholder="#"): (fps, count, _, _) = cv2VideoInfo(cap) vid = VideoWriter(filename, VideoWriter.fourcc(*"FMP4"), fps, mon.newSize) ary = expandSrts(subtitle, fps, count, placeholder) if subtitle != None else None cv2.namedWindow(title, cv2.WINDOW_NORMAL) begin_time = time() index = 0 unfinished, img = cap.read() while unfinished: if subtitle != None: text0 = mon.text mon.text = ary[index] if mon.text != text0: mon.refreshLayout() mon_img = mapUMatWithPillow(img, mon.runOn) cv2.imshow(title, mon_img) vid.write(mon_img) key = chr(cv2.waitKey(1) & 0xFF) if key == 'q': break elif key == 'p': duration = time() - begin_time print("%i time=%.3fs %.3ffps" %(index, duration, index/duration) ) unfinished, img = cap.read() index += 1 vid.release()
def video_maker(images, outimg=None, fps=24, size=None, is_color=True, format="mp4v"): global overallTimeElapsed print("Overall Encryption time: %.2f" % overallTimeElapsed) fourcc = VideoWriter_fourcc(*format) vid = None outvid = './dirty_video.mp4' for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() print('Video Encrypted.') return vid
def make_video(outvid, images=None, fps=30, size=None, is_color=True, format="FMP4"): """ Create a video from a list of images. @param outvid output video @param images list of images to use in the video @param fps frame per second @param size size of each frame @param is_color color @param format see http://www.fourcc.org/codecs.php @return see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/. By default, the video will have the size of the first image. It will resize every image to this size before adding them to the video. """ from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize fourcc = VideoWriter_fourcc(*format) vid = None for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() return vid
def make_video(images, outvid=None, fps=5, size=None, is_color=True, format="XVID"): """ Create a video from a list of images. @param outvid output video @param images list of images to use in the video @param fps frame per second @param size size of each frame @param is_color color @param format see http://www.fourcc.org/codecs.php @return see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html The function relies on http://opencv-python-tutroals.readthedocs.org/en/latest/. By default, the video will have the size of the first image. It will resize every image to this size before adding them to the video. """ from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize import os fourcc = VideoWriter_fourcc(*format) vid = None for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() return vid
def make_video(self, images, outvid=None, fps=5, size=None, is_color=True, format="XVID"): """ Create a video from a list of images. @param outvid output video @param images list of images to use in the video @param fps frame per second @param size size of each frame @param is_color color @param format see http://www.fourcc.org/codecs.php """ # fourcc = VideoWriter_fourcc(*format) # For opencv2 and opencv3: if int(cv2.__version__[0]) > 2: fourcc = cv2.VideoWriter_fourcc(*format) else: fourcc = cv2.cv.CV_FOURCC(*format) vid = None for image in images: assert os.path.exists(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release()
def make_video(outvid, images=None, fps=30, size=None, is_color=True, format="AVC1"): """ Create a video from a list of images. @param outvid output video @param images list of images to use in the video @param fps frame per second @param size size of each frame @param is_color color @param format see http://www.fourcc.org/codecs.php @return see http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html """ from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize fourcc = VideoWriter_fourcc(*format) vid = None print('len(images):', len(images)) for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() return vid
def make_video(images, output_path, fps=0.5, size=(640, 480), is_color=True): """ Create a video from a list of images. """ fourcc = VideoWriter_fourcc(*"XVID") vid = VideoWriter(output_path, fourcc, fps, size, is_color) for image in images: img = imread(image) vid.write(img) vid.release() return
class CV_Writer(object): """docstring for CV_Writer""" def __init__(self, file_loc,frame_rate,frame_size): super(CV_Writer, self).__init__() self.writer = VideoWriter(file_loc, VideoWriter_fourcc(*'DIVX'), float(frame_rate), frame_size) def write_video_frame(self, input_frame): self.writer.write(input_frame.img) def write_video_frame_yuv422(self, input_frame): raise NotImplementedError def release(self): self.writer.release()
class Record: """ Grabar video de la partida para enviar al desarrollador y poder ayudarlo a mejorar el programa. """ def __init__(self, filename, size): """ :Param filename: Nombre del archivo del video. :Type filename: str """ self.FPS = 29 # MJPG = 1196444237 # VideoWriter_fourcc('M','J','P','G') # MPEG_1 = VideoWriter_fourcc('P','I','M','1') # self.codec = VideoWriter_fourcc(*'MJPG') self.codec = VideoWriter_fourcc(*"XVID") # MPEG_42 = VideoWriter_fourcc('M','P','4','2') # MPEG_43 = VideoWriter_fourcc('D','I','V','3') # MPEG_4 = VideoWriter_fourcc('D','I','V','X') # H263 = VideoWriter_fourcc('U','2','6','3') # H263I = VideoWriter_fourcc('I','2','6','3') # FLV1 = VideoWriter_fourcc('D','I','V','X') # TODO: Correctly set FPS self.video_filename = filename self.video = None # print("SELFFFF", self.video) self.frame = 0 def add_frame(self, frame): """ :Param frame: Frame del video :Type frame: iplimage """ if self.video == None: self.video = VideoWriter(self.video_filename, self.codec, self.FPS, frame.shape[:2]) self.frame += 1 frame = flip(frame, 0) self.video.write(frame) # print("WriteFrame -->", add) def part_video(self, first_frame, last_frame): """ Dado dos frames, obtener el video que se encuentre entre ambos. :Param first_frame: Frame donde comenzará el video. :Type first_frame: int :Param last_frame: Frame donde finalizará el video. :Type last_frame: int """ pass # TODO
def save_animation(filename, files, fps=10, codec=None, clear_temp=True, frame_prefix='_tmp'): ''' Saves a movie file by drawing every frame. *filename* is the absolute path to the output filename, eg :file:`mymovie.mp4` *files* is a list of files to add to the movie *fps* is the frames per second in the movie *codec* is the codec to be used,if it is supported by the output method. *clear_temp* specifies whether the temporary image files should be deleted. ''' if len(files) > 0: fps = max(fps,10) if codec is None: #codec = CV_FOURCC('D','I','B',' ') #codec = CV_FOURCC('D','I','V','X') codec = CV_FOURCC('X','V','I','D') #codec = CV_FOURCC('X','2','6','4') # To get correct width and height for video height,width,bands = imread(files[0]).shape vw = VideoWriter(filename, codec, fps, (width, height), True) if vw is None: print "Error creating video writer" for fname in files: # 2.0 ig = imread(fname) vw.write(ig) vw.write(ig) if clear_temp: os.remove(fname) del vw return True return False
def make_video(images, outvid=None, fps=5, size=None, is_color=True, format="XVID"): """ Creates a video from a list of images. @param outvid output video @param images list of images to use in the video @param fps frames per second @param size size of each frame @param is_color color @param format see `fourcc <http://www.fourcc.org/codecs.php>`_ @return `VideoWriter <http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/ py_gui/py_video_display/py_video_display.html>`_ The function relies on `opencv <http://opencv-python-tutroals.readthedocs.org/en/latest/>`_. By default, the video will have the size of the first image. It will resize every image to this size before adding them to the video. The function does not use :epkg:`moviepy` but it is a a recommended module to do that. """ if len(images) == 0: raise ValueError("no image to convert into a video") from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize # pylint: disable=E0401 fourcc = VideoWriter_fourcc(*format) vid = None for image in images: if not os.path.exists(image): raise FileNotFoundError(image) img = imread(image) if vid is None: if size is None: size = img.shape[1], img.shape[0] vid = VideoWriter(outvid, fourcc, float(fps), size, is_color) if size[0] != img.shape[1] and size[1] != img.shape[0]: img = resize(img, size) vid.write(img) vid.release() return vid
video_filename = opt.output[:-3] + 'avi' else: video_filename = opt.output + '.avi' from cv import FOURCC from cv2 import VideoWriter movieWriter = VideoWriter(video_filename, FOURCC('U','2','6','3'), 20, (opt.length, opt.length), False) print 'Writing movie to ' + video_filename # Number of dashes in complete progress bar progress_bar_size = min(20, opt.steps) steps_per_dash = opt.steps / progress_bar_size print '['+' '*progress_bar_size+']\r[', stdout.flush() for step in xrange(1,opt.steps): lattice.step(opt.beta) if opt.movie: movieWriter.write((128*lattice.state).astype(sp.uint8)) if step % steps_per_dash == 0: stdout.write('-') stdout.flush() fd.write(' '.join(str(d) for d in [lattice.up, lattice.updown]) + '\n') if opt.steps % progress_bar_size == 0: stdout.write('-') stdout.flush() stdout.write('\n') fd.close()
def captureTStamp(files, duration, cod, fps=0, verbose=True): ''' guarda por un tiempo en minutos (duration) el video levantado desde la direccion indicada en el archvo indicado. tambíen archivos con los time stamps de cada frame. files = [ur, saveVideoFile, saveDateFile, saveMillisecondFile] duration = time in mintes cod = codec fps = frames per second for video to be saved verbose = print messages to screen si fpscam=0 trata de llerlo de la captura. para fe hay que especificarla para opencv '2.4.9.1' Examples -------- from cameraUtils import captureTStamp # para la FE duration = 1 # in minutes files = ['rtsp://192.168.1.48/live.sdp', "/home/alumno/Documentos/sebaPhDdatos/vca_test_video.avi", "/home/alumno/Documentos/sebaPhDdatos/vca_test_tsFrame.txt"] fpsCam = 12 cod = 'XVID' captureTStamp(files, duration, cod, fps=fpsCam) # %% para la PTZ duration = 0.2 # in minutes files = ["rtsp://192.168.1.49/live.sdp", "/home/alumno/Documentos/sebaPhDdatos/ptz_test_video.avi", "/home/alumno/Documentos/sebaPhDdatos/ptz_test_tsFrame.txt"] fpsCam = 20 cod = 'XVID' captureTStamp(files, duration, cod, fpsCam) ''' fcc = fourcc(cod[0],cod[1],cod[2],cod[3]) # Códec de video if verbose: print(files) print("Duration",duration,"minutes") print("fps",fps) print("codec",cod) # Inicializacion tFin = datetime.datetime.now() + datetime.timedelta(minutes=duration) ts = list() # timestamp de la captura # abrir captura cap = VideoCapture(files[0]) while not cap.isOpened(): cap = VideoCapture(files[0]) print("capture opened") # configurar writer w = int(cap.get(frame_width)) h = int(cap.get(frame_height)) if not fps: fps = cap.get(prop_fps) #para fe especificar los fps pq toma cualquier cosa con la propiedad out = VideoWriter(files[1], fcc, fps,( w, h), True) if verbose: print("capture open",cap.isOpened()) print("frame size",w,h) print("output opened",out.isOpened()) if not out.isOpened() or not cap.isOpened(): out.release() cap.release() # exit function if unable to open cap or out return s0 = getsize(files[1]) # initial filesize before writing frame # Primera captura ret, frame = cap.read() if ret: t = datetime.datetime.now() ts.append(t) out.write(frame) if verbose: print("first frame captured") # Segunda captura ret, frame = cap.read() if ret: t = datetime.datetime.now() ts.append(t) out.write(frame) if verbose: print("second frame captured") # Tercera captura ret, frame = cap.read() if ret: t = datetime.datetime.now() ts.append(t) out.write(frame) if verbose: print("third frame captured") s1 = getsize(files[1]) # size after saving 3 frames if s1==s0: out.release() cap.release() print("error when saving 3 frames, exiting") return 1 # error while saving first frame to file print(tFin) # loop while (t <= tFin): ret, frame = cap.read() if ret: t = datetime.datetime.now() ts.append(t) out.write(frame) if verbose: print(tFin,t) print("seconds elapsed",cap.get(pos_msec)/1000) print(frame.size) # end of loop # release and save out.release() cap.release() if verbose: print('loop exited, cap, out released, times saved to files') savetxt(files[2],ts, fmt= ["%s"]) return 0 # success
def run(self, show=False, save=False, tk_var_frame=None, wait=1, start_pos='none'): #interfaces if show or save: fsize = (self.width*2, self.height) save_frame = np.zeros([self.height, self.width*2, 3], dtype=np.uint8) if show: namedWindow('Tracking') if save: writer = VideoWriter() writer.open(self.fh.make_path('tracking.avi'),self.fourcc,round(self.fs),frameSize=fsize,isColor=True) #run self.framei = 0 self.pos = [] self.t = [] self.guess = [] self.contour = [] self.pct_xadj = [] self.heat = np.zeros((self.height,self.width)) consecutive_skips = 0 if start_pos == 'x': start_pts = [self.xori_adj, self.xoli_adj] elif start_pos == 'y': start_pts = [self.yori_adj, self.yoli_adj] elif start_pos == 'z': start_pts = [self.zori_adj, self.zoli_adj] elif start_pos == 'c': start_pts = [self.zori, self.xori, self.yori] elif start_pos == 'none': start_pts = [self.zori, self.xori, self.yori] consecutive_skips = self.consecutive_skip_threshold+1 self.last_center = np.mean(self.pts[np.array(start_pts)],axis=0).astype(int) self.last_contour = np.array([self.last_center]) valid,frame,ts = self.get_frame(self.mov,skip=self.resample-1) while valid: possible,diff_raw = self.find_possible_contours(frame,consecutive_skips) self.pct_xadj.append(np.mean( diff_raw[self.xadj_idxs[:,0],self.xadj_idxs[:,1]])) if len(possible) == 0: center = self.last_center contour = self.last_contour self.guess.append(True) consecutive_skips+=1 else: contour,center = self.choose_best_contour(possible) self.guess.append(False) consecutive_skips = 0 self.pos.append(center) self.contour.append(contour) self.t.append(ts) self.heat[center[1],center[0]] += 1 if show or save: lframe = self.label_frame(frame, center) save_frame[:,:self.width, :] = cvtColor(lframe.astype(np.float32), CV_GRAY2RGB) save_frame[:,self.width:, :] = cvtColor((self.diff*255).astype(np.float32), CV_GRAY2RGB) if show: self.show_frame(save_frame, wait=wait) if save: writer.write(save_frame) self.last_center = center self.last_contour = contour valid,frame,ts = self.get_frame(self.mov,skip=self.resample-1) if tk_var_frame != None: tk_var_frame[0].set('%i/%i'%(self.results['n_frames'], len(self.time)/float(self.resample) )) tk_var_frame[1].update() if save: writer.release() self.end()
def run(self, show=False, save=False, tk_var_frame=None): if show: namedWindow('Movie') namedWindow('Tracking') if save: bgs = np.shape(self.background) fsize = (bgs[0], bgs[1]*2) writer = VideoWriter() writer.open(os.path.join(self.trial_dir,'%s_tracking_movie'%self.trial_name),self.fourcc,37.,frameSize=(fsize[1],fsize[0]),isColor=True) self.results['n_frames'] = 0 consecutive_skips = 0 while True: valid,frame = self.get_frame(self.mov,skip=self.resample-1) if not valid: break diff = absdiff(frame,self.background) _, diff = threshold(diff, self.diff_thresh, 1, THRESH_BINARY) diff = diff*self.rooms_mask edges = Canny(diff.astype(np.uint8), self.cth1, self.cth2) contours, hier = findContours(edges, RETR_EXTERNAL, CHAIN_APPROX_TC89_L1) contours = [c for c in contours if not any([pa.contains_point(contour_center(c)) for pa in self.paths_ignore])] if consecutive_skips>self.consecutive_skip_threshold: consecutive_skips=0 possible = contours else: possible = [c for c in contours if dist(contour_center(c),self.last_center)<self.translation_max] if len(possible) == 0: center = self.last_center self.results['skipped'] += 1 consecutive_skips+=1 if self.path_l.contains_point(center): self.results['left_assumed']+=1 if self.path_r.contains_point(center): self.results['right_assumed']+=1 if self.path_c.contains_point(center): self.results['middle_assumed']+=1 else: chosen = possible[np.argmax([contourArea(c) for c in possible])] center = contour_center(chosen) self.results['centers'].append(center) self.results['heat'][center[1],center[0]] += 1 if self.path_l.contains_point(center): self.results['left']+=1 if self.path_r.contains_point(center): self.results['right']+=1 if self.path_c.contains_point(center): self.results['middle']+=1 self.results['centers_all'].append(center) #display if show or save: showimg = np.copy(frame).astype(np.uint8) if self.path_l.contains_point(center): color = (0,0,0) elif self.path_r.contains_point(center): color = (255,255,255) else: color = (120,120,120) circle(showimg, tuple(center), radius=10, thickness=5, color=color) if show: cv2imshow('Movie',showimg) cv2imshow('Tracking', diff) waitKey(1) #/display if save: save_frame = np.zeros([fsize[0], fsize[1], 3],dtype=np.uint8) save_frame[:,:np.shape(frame)[1]] = cvtColor(showimg.astype(np.float32), CV_GRAY2RGB) save_frame[:,np.shape(frame)[1]:] = cvtColor((diff*255).astype(np.float32), CV_GRAY2RGB) writer.write(save_frame) self.results['n_frames'] += 1 self.last_center = center if tk_var_frame != None: tk_var_frame[0].set('%i/%i'%(self.results['n_frames'], len(self.time)/float(self.resample) )) tk_var_frame[1].update() #pbar.update(self.results['n_frames']) #pbar.finish() if save: writer.release() self.end()