我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.VideoWriter()。
def make_video(self, images, outimg=None, fps=2, size=None, is_color=True, format="XVID", outvid='image_video.avi'): 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 # Un radio de 4 pixeles es equivalente a un radio de 0.0002 en wcs
def video (seconds, frameRate): cap = cv2.VideoCapture(0) if(not cap.isOpened()): return "error" # Define the codec and create VideoWriter object fourcc = cv2.cv.CV_FOURCC(*'XVID') name = "media/video/" + time.strftime("%d-%m-%Y_%X")+".avi" out = cv2.VideoWriter(name, fourcc, frameRate, (640,480)) program_starts = time.time() result = subprocess.Popen(["ffprobe", name], stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell=True) nFrames=0 while(nFrames<seconds*frameRate): ret, frame = cap.read() if ret==True: out.write(frame) nFrames += 1 else: break cap.release() return name
def dump_video(filename, clip, fourcc_str='X264', fps=30.0): """Write video on disk from a stack of images Parameters ---------- filename : str Fullpath of video-file to generate clip : ndarray ndarray where first dimension is used to refer to i-th frame fourcc_str : str str to retrieve fourcc from opencv fps : float frame rate of create video-stream """ fourcc = cv2.cv.CV_FOURCC(**list(fourcc_str)) fid = cv2.VideoWriter(filename, fourcc, fps, clip.shape[0:2]) if fid.isOpened(): for i in xrange(clip.shape[0]): fid.write(clip[i, ...]) return True else: return False
def applyTransform(self): self.framing(self.path) self.height,self.width=cv2.imread("Frames/1.jpg").shape[:2] # write transformed video out = cv2.VideoWriter("changedOutput.mp4",cv.CV_FOURCC('a','v','c','1'), 30.0, (self.width, self.height)) folder=self.sort_files() # write Transformed video frames for i in folder: pic="Frames/"+str(i)+".jpg" Newpic=cv2.imread(pic,0) frame=cv2.Canny(Newpic,100,200) cv2.imwrite(pic,frame) Newpic=cv2.imread(pic) img=cv2.flip(Newpic,0) out.write(img) out.release() # Writing output video file
def save_avi(reader, output_filename): try: import cv2 except ImportError: print('Please install OpenCV2 to use this format.') raise writer = cv2.VideoWriter(output_filename, cv2.VideoWriter_fourcc(*'PIM1'), 25, reader.image_size1, False) ts = [] for t, img in reader: ts.append(t) writer.write(img) write_timestamps(output_filename + '.txt', ts)
def __init__(self, output_width, output_height, output_fps, output_format, output_path): self.frame_wrappers = [] self.start_time = -1 self.end_time = -1 self.pub_img = None self.bridge = CvBridge() self.fps = output_fps self.interval = 1.0 / self.fps self.output_width = output_width self.output_height = output_height if opencv_version() == 2: fourcc = cv2.cv.FOURCC(*output_format) elif opencv_version() == 3: fourcc = cv2.VideoWriter_fourcc(*output_format) else: raise self.output_path = output_path self.video_writer = cv2.VideoWriter(output_path, fourcc, output_fps, (output_width, output_height))
def enable_videowriter(self, output_filename, fourcc_string="MJPG", fps=None): """ Write images to video file. Parameters ---------- output_filename : str Output filename. fourcc_string : str The OpenCV FOURCC code that defines the video codec (check OpenCV documentation for more information). fps : Optional[float] Frames per second. If None, configured according to current parameters. """ fourcc = cv2.VideoWriter_fourcc(*fourcc_string) if fps is None: fps = int(1000. / self._update_ms) self._video_writer = cv2.VideoWriter( output_filename, fourcc, fps, self._window_shape)
def init_video_writer(fourcc): global IS_CAPTURING global OUT global CURRENT_CAPTURE path = './avi/' if not os.path.exists(path): os.makedirs(path) log('STARTING CAPTURE') filename = str(datetime.datetime.now()).replace(" ", "_").replace(":","_")[:-7] + ".avi" OUT = cv2.VideoWriter(path + filename, fourcc, SETTINGS['output_fr'], (500, 375)) CURRENT_CAPTURE = path + filename IS_CAPTURING = True
def run(self): while True: if self.flag: ret, image = self.camera.read() if image is None: break color_swapped_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) height, width, _ = color_swapped_image.shape qt_image = QImage(color_swapped_image.data, width, height, color_swapped_image.strides[0], QImage.Format_RGB888) pixmap = QPixmap(qt_image) pixmap = pixmap.scaled(self.videoLabel.geometry().width(), self.videoLabel.geometry().height()) if self.start_flag and self.support_flag: fourcc = cv2.VideoWriter_fourcc(*'DIVX') self.path = "appdata/" + self.cap.guide.dataset_type + "/data/" + self.cap.date_str + "-" + str( self.cap.guide.gesture_type) + ".avi" self.out = cv2.VideoWriter(self.path, fourcc, 20.0, (640, 480)) self.support_flag = False if self.name == "Camera" and self.out is not None: self.image_siganl.emit(image) self.videoLabel.setPixmap(pixmap) if self.name == "Video": time.sleep(1/self.fps) else: pass
def __init__(self, args, main_out_vid_name="foreground"): self.mask_writer = None super().__init__(args, main_out_vid_name) if args.mask_output_video == "": args.mask_output_video = args.in_video[:-4] + "_bs_mask.mp4" self.mask_writer = cv2.VideoWriter(os.path.join(self.datapath, args.mask_output_video), cv2.VideoWriter_fourcc('X', '2', '6', '4'), self.cap.get(cv2.CAP_PROP_FPS), (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))), False) self.mask_writer.set(cv2.VIDEOWRITER_PROP_NSTRIPES, cpu_count()) self.foreground_writer = self.writer self.foreground = None self.mask = None
def videoWriter(cam_writer_frames_Queue, writer_blurrer_filename_Queue): while True: startTime, FRAMES = cam_writer_frames_Queue.get() t1 = time.time() # Writing frames to disk #fourcc = cv2.cv.CV_FOURCC(*'XVID') fourcc = cv2.VideoWriter_fourcc(*'mp4v') fourcc_out = cv2.VideoWriter_fourcc(*'avc1') filename_blurs = 'blurrer' + '_' + RPiName + '_' + repr(startTime) + ".avi" clipWriter = cv2.VideoWriter(filename_blurs, fourcc, 10, (320, 240)) for frameTimestamp, frame in FRAMES: clipWriter.write(frame) writer_blurrer_filename_Queue.put(filename_blurs) filename = RPiName + '_' + repr(startTime) + ".mp4" clipWriter = cv2.VideoWriter(filename, fourcc_out, 10, (320, 240)) while len(FRAMES) > 0: frameTimestamp, frame = FRAMES.pop(0) frameWithCaption = writeToFrame(frameTimestamp, frame, RPiName) clipWriter.write(frameWithCaption) print "Written to disk: ", time.time() - t1
def run(self): filename = '.' + filename_tmpl.format(self.date, 0, self.extension) print('Starting new video File [{}]'.format(filename)) video = cv2.VideoWriter(filename, self.fourcc, self.fps, self.size) while True: f = self.queue.get() if f is QueueFinished: self.queue.task_done() break video.write(f) self.queue.task_done() duration = (datetime.now() - self.date).total_seconds() new_filename = filename_tmpl.format(self.date, round(duration), self.extension) print('Releasing resources for [{}] and renaming it to [{}]'.format(filename, new_filename)) video.release() os.rename(filename, new_filename) try: redis.publish('video:new', new_filename) except: print("Error publishing {} to redis".format(new_filename), file=sys.stderr)
def put(self, name, frame): if self.type==self.DIR: cv2.imwrite(self.path+"/"+name, frame) elif self.type==self.IMG: cv2.imwrite(self.path, frame) elif self.type==self.VID: if self.writer is None: if hasattr(cv2, 'VideoWriter_fourcc'): fcc=cv2.VideoWriter_fourcc(*'MJPG') else: fcc=cv2.cv.CV_FOURCC(*'MJPG') self.writer = cv2.VideoWriter(self.path, fcc, int(self.fps), (frame.shape[1], frame.shape[0])) self.writer.write(frame) else: pass
def _write_video(self, im): if self.writer is None: h, w = im.shape[:2] self.writer = cv2.VideoWriter(self.filename, cv2.cv.CV_FOURCC(*'mp42'), 30.0, (w, h), im.ndim == 3) print('{} :: creating {} ({},{})'.format(self.__class__.__name__, self.filename, w, h)) self.writer.write(im)
def write_video(fn, im, scale=1.0, as_images=False): global g_fn_map if fn not in g_fn_map: g_fn_map[fn] = VideoWriter(fn, as_images=as_images) im_scaled = im_resize(im, scale=scale) if scale != 1.0 else im g_fn_map[fn].write(im_scaled) # def write_images(template, im):
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(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 __init__(self, file_loc,frame_rate,frame_size): super().__init__() self.writer = VideoWriter(file_loc, VideoWriter_fourcc(*'DIVX'), float(frame_rate), frame_size)
def addFrame(self, frame, width=300): frame = imutils.resize(frame, width) # check if the writer is None if self.writer is None: # store the image dimensions, initialzie the video writer, # and construct the zeros array (self.h, self.w) = frame.shape[:2] self.writer = cv2.VideoWriter(self.output, self.fourcc, self.fps, (self.w * 2, self.h * 2), True) self.zeros = np.zeros((self.h, self.w), dtype="uint8") # break the image into its RGB components, then construct the # RGB representation of each frame individually (B, G, R) = cv2.split(frame) R = cv2.merge([self.zeros, self.zeros, R]) G = cv2.merge([self.zeros, G, self.zeros]) B = cv2.merge([B, self.zeros, self.zeros]) # construct the final output frame, storing the original frame # at the top-left, the red channel in the top-right, the green # channel in the bottom-right, and the blue channel in the # bottom-left output = np.zeros((self.h * 2, self.w * 2, 3), dtype="uint8") output[0:self.h, 0:self.w] = frame output[0:self.h, self.w:self.w * 2] = R output[self.h:self.h * 2, self.w:self.w * 2] = G output[self.h:self.h * 2, 0:self.w] = B # write the output frame to file self.writer.write(output)
def addFrame(self, frame, width=600): frame = imutils.resize(frame, width) # check if the writer is None if self.writer is None: # store the image dimensions, initialzie the video writer, (self.h, self.w) = frame.shape[:2] self.writer = cv2.VideoWriter(self.output, self.fourcc, self.fps, (self.w, self.h), True) # write the output frame to file self.writer.write(frame)
def red_and_black(): red = cv2.imread('./data/redHDSolidBlock.jpg') black = cv2.imread('./data/blackHDSolidBlock.jpg') vwriter = VideoWriter('red_black_0.5Hz.avi') frames = 0 for t in range(30): for f in range(20): vwriter.addFrame(black) frames+=1 for f in range(20): vwriter.addFrame(red) frames+=1 vwriter.finalise() print("Created movie with %d frames" % frames)
def webcam_capture_video(output = 'webcam.avi', duration = 5): w = VideoWriter(output = output) cap = cv2.VideoCapture(0) t = t0 = time.time() t1 = t + duration md = [] while (t < t1): _,f = cap.read() w.addFrame(f) md.append(t) t = time.time() w.finalise() print("Captured %d frames to %s in %f\n" % (len(md), output, (t - t0)))
def write_labels(video, label_dict, secs=1): cap = cv2.VideoCapture(video) w=int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH )) h=int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT )) out = cv2.VideoWriter('output.mp4', -1, 20.0, (w,h)) f_no = 0 fps = get_frame_rate(cap) inc = int(fps * secs) f_nos = label_dict.keys() lbl = '' while(cap.isOpened()): ret, frame = cap.read() if ret==True: if f_no in f_nos: try: lbls = label_dict[f_no] lbl = ",".join(lbls.keys()) except: pass cv2.putText(frame,lbl,(105, 105),cv2.FONT_HERSHEY_COMPLEX_SMALL,2,(0,0,255)) #out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break #inc f_no += 1 cap.release() out.release() cv2.destroyAllWindows() #if __name__ == '__main__' : # get_frames_every_x_sec('video.mp4', '.')
def saveVideo3D(self, filename, sequence, showPC=True, showGT=False, niceColors=True, plotFrameNumbers=False, height=400, width=400): """ Create a video with 3D annotations :param filename: name of file to save :param sequence: sequence data :return: None """ txt = 'Saving {}'.format(filename) pbar = pb.ProgressBar(maxval=self.joints.shape[0], widgets=[txt, pb.Percentage(), pb.Bar()]) pbar.start() # Define the codec and create VideoWriter object fourcc = cv2.cv.CV_FOURCC(*'DIVX') video = cv2.VideoWriter('{}/depth_{}.avi'.format(self.subfolder, filename), fourcc, self.fps, (height, width)) if not video: raise EnvironmentError("Error in creating video writer") for i in range(self.joints.shape[0]): jt = self.joints[i] img = self.plotResult3D_OS(sequence.data[i].dpt, sequence.data[i].T, sequence.data[i].gt3Dorig, jt, showPC=showPC, showGT=showGT, niceColors=niceColors, width=width, height=height) img = numpy.flipud(img) img = img[:, :, [2, 1, 0]] # change color channels for OpenCV img = cv2.resize(img, (height, width)) if plotFrameNumbers: if sequence.data[i].subSeqName == 'ref': cv2.putText(img, "Reference Frame {}".format(i), (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255)) # plot frame number cv2.putText(img, "{}".format(i), (height-50, width-10), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255)) # write frame video.write(img) pbar.update(i) video.release() del video cv2.destroyAllWindows() pbar.finish()
def saveVideoFrames(self, filename, images): """ Create a video with synthesized images :param filename: name of file to save :param images: video data :return: None """ txt = 'Saving {}'.format(filename) pbar = pb.ProgressBar(maxval=images.shape[0], widgets=[txt, pb.Percentage(), pb.Bar()]) pbar.start() height = width = 128 # Define the codec and create VideoWriter object fourcc = cv2.cv.CV_FOURCC(*'DIVX') video = cv2.VideoWriter('{}/synth_{}.avi'.format(self.subfolder, filename), fourcc, self.fps, (height, width)) if not video: raise EnvironmentError("Error in creating video writer") for i in range(images.shape[0]): img = images[i] img = cv2.normalize(img, alpha=0, beta=255, norm_type=cv2.cv.CV_MINMAX, dtype=cv2.cv.CV_8UC1) img = cv2.cvtColor(img, cv2.cv.CV_GRAY2BGR) img = cv2.resize(img, (height, width)) # write frame video.write(img) pbar.update(i) video.release() del video cv2.destroyAllWindows() pbar.finish()
def convert_video(self, video_path, output_directory, skip=0, resize=400): video = cv2.VideoCapture(video_path) video_output = None i = 0 img_init = None while video.get(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO) < 1.0: i += 1 for _ in range(skip+1): status, bgr_img = video.read() img = PIL.Image.fromarray(cv2.cvtColor( bgr_img, cv2.COLOR_BGR2RGB )) img = neural_art.utility.resize_img(img, resize) if video_output is None: video_output = cv2.VideoWriter( "{}/out.avi".format(output_directory), fourcc=0, #raw fps=video.get(cv2.cv.CV_CAP_PROP_FPS) / (skip + 1), frameSize=img.size, isColor=True ) if(not video_output.isOpened()): raise(Exception("Cannot Open VideoWriter")) if img_init is None: img_init = img converted_img = self.frame_converter.convert(img, init_img=img_init, iteration=self.iteration) converted_img.save("{}/converted_{:05d}.png".format(output_directory, i)) img_init = converted_img video_output.write(cv2.cvtColor( numpy.asarray(converted_img), cv2.COLOR_RGB2BGR )) video_output.release()
def __init__(self, IP, PORT, CameraID, parent=None): """ Initialization. """ self._image = None self._imgWidth = 320 self._imgHeight = 240 self._cameraID = CameraID # Proxy to ALVideoDevice. self._videoProxy = None # Our video module name. self._imgClient = "" # This will contain this alImage we get from Nao. self._alImage = None self._registerImageClient(IP, PORT) # Trigger 'timerEvent' every ms. self.delay=0.1 self.opencvframe=None # Show opencv image self.showvideo=False self.output_path='./data/'+datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')+'/' # Define the codec and create VideoWriter object self.enabledwriter=False self._fps=2.0 self.outvideo=self.output_path+'log.avi' self._fourcc = cv2.cv.FOURCC(*'XVID') self._out =None self.numframe=0
def initWriter(self): if not os.path.exists(self.output_path): os.makedirs(self.output_path) self._out = cv2.VideoWriter(self.outvideo, self._fourcc, self._fps, (self._imgWidth,self._imgHeight)) self.enabledwriter=True
def __init__(self, IP, PORT, CameraID, parent=None): """ Initialization. """ self._image = None self._imgWidth = 320 self._imgHeight = 240 self._cameraID = CameraID # Proxy to ALVideoDevice. self._videoProxy = None # Our video module name. self._imgClient = "" # This will contain this alImage we get from Nao. self._alImage = None self._registerImageClient(IP, PORT) # Trigger 'timerEvent' every ms. self.delay=0.05 self.output_path='./data/'+datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')+'/' # Define the codec and create VideoWriter object self.enabledwriter=False self._fps=2.0 self.outvideo=self.output_path+'log.avi' self._fourcc = cv2.cv.FOURCC(*'XVID') self._out =None self.numframe=0
def Test(agent): if (test_write_video): size = (640, 480) fps = 30.0 fourcc = cv2.VideoWriter_fourcc(*'XVID') # cv2.cv.CV_FOURCC(*'XVID') out_video = cv2.VideoWriter(path_work_dir + "test.avi", fourcc, fps, size) reward_total = 0 num_episodes = 30 while (num_episodes != 0): if (not env.IsRunning()): env.Reset() agent.Reset() print("Total reward: {}".format(reward_total)) reward_total = 0 num_episodes -= 1 state_raw = env.Observation() state = Preprocess(state_raw) action = agent.Act(state) for _ in xrange(frame_repeat): if (test_display): cv2.imshow("frame-test", state_raw) cv2.waitKey(20) if (test_write_video): out_video.write(state_raw) reward = env.Act(action, 1) reward_total += reward if (not env.IsRunning()): break state_raw = env.Observation()
def Test(agent): if (test_write_video): size = (640, 480) fps = 30.0 #/ frame_repeat fourcc = cv2.VideoWriter_fourcc(*'XVID') # cv2.cv.CV_FOURCC(*'XVID') out_video = cv2.VideoWriter(path_work_dir + "test.avi", fourcc, fps, size) reward_total = 0 num_episodes = 30 while (num_episodes != 0): if (not env.IsRunning()): env.Reset() print("Total reward: {}".format(reward_total)) reward_total = 0 num_episodes -= 1 state_raw = env.Observation() state = Preprocess(state_raw) action = agent.GetAction(state) for _ in xrange(frame_repeat): # Display. if (test_display): cv2.imshow("frame-test", state_raw) cv2.waitKey(20) if (test_write_video): out_video.write(state_raw) reward = env.Act(action, 1) reward_total += reward if (not env.IsRunning()): break state_raw = env.Observation()
def __init__(self, index=0): self.frame = None self.capture = cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # self.capture.set(cv2.CAP_PROP_EXPOSURE, 0) # self.capture.set(cv2.CAP_PROP_GAIN, 0) # Define codec and create VideoWriter object # fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') # self.out = cv2.VideoWriter('output.avi', fourcc, 120.0, (640, 480))
def __init__(self, fn, height, width, channels=3, fps=30): super(Writer, self).__init__() self.width = width self.height = height self.channels = channels self.fn = fn print("writing to %s with shape (%i, %i, %i)" % (fn, height, width, channels)) cc4 = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') self.out = cv2.VideoWriter(fn, cc4, fps, (width, height), isColor=(channels == 3))
def get_video_writer(args): # Define the codec and create VideoWriter object #fourcc = cv2.VideoWriter_fourcc(*'XVID') fourcc = cv2.VideoWriter_fourcc('P','I','M','1') return cv2.VideoWriter(args.video_path, fourcc, args.fps, (args.width, args.height))
def image2video(): video_writer = cv2.VideoWriter(filename=args.videopath, fourcc=cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps=args.videofps, frameSize=(videosize[0], videosize[1])) list = os.listdir(args.imagepath) list.sort() for jpg in list: video_writer.write(cv2.imread(os.path.join(args.imagepath, jpg))) video_writer.release()
def main(): if Display: cap = cv2.VideoCapture(0) out = cv2.VideoWriter('output.avi', -1, 2.0, (600, 440)) count = 0 while(count < 20): ret, frame1 = cap.read() ret, frame2 = cap.read() frame1 = skimage.img_as_float(frame1) frame2 = skimage.img_as_float(frame2) output_img = optical_flow_ssd(frame1, frame2) out.write(output_img) cv2.imshow('frame', output_img) count = count + 1 if cv2.waitKey(1) & 0xFF == ord('q'): cap.release() out.release() cv2.destroyAllWindows() break else: test()
def __init__(self, config_path): self.termites = [] self.params = utils.read_config_file(config_path) self.simulation_speed = self.params['simulation_speed'] self.out = cv2.VideoWriter('{}simulation-out.avi'.format(self.params['output_path']), cv2.VideoWriter_fourcc(*'XVID'), 30.0, (1280,480))
def __init__(self, video_path, out_path, video_shape, filters, write_capture_info, subtractor='MOG'): """Initializer. Args: video_path (str): path to video file. out_path (str): output video destination path. video_shape (tuple): default size for frame redimensioning. filters (list): list of filter's names to apply in video source. write_info (bool): should write frame info when displaying. subtractor (str): name of background subtractor. Returns: None. """ if video_path == '-1': video_path = int(video_path) self.source = cv2.VideoCapture(video_path) if not self.source.isOpened(): print('Could not find video file.') sys.exit() if subtractor == 'MOG': self.subtractor = cv2.createBackgroundSubtractorMOG2() elif subtractor == 'GMG': self.subtractor = cv2.bgsegm.createBackgroundSubtractorGMG() self.current_frame = None self.playing = False self.video_shape = video_shape self.codec = cv2.VideoWriter_fourcc(*'XVID') self.out = cv2.VideoWriter('{}tracking-out.avi'.format(out_path), self.codec, 30.0, self.video_shape) self.filters = filters self.write_capture_info = write_capture_info self.start()
def writeVideo(self): height,width=cv2.imread("Frames/1.jpg").shape[:2] out = cv2.VideoWriter("changedOutput.ogv",cv.CV_FOURCC('t','h','e','0'), 25.0, (width,height)) folder=self.sort_files() for i in folder: pic="Frames/"+str(i)+".jpg" img=cv2.imread(pic) out.write(img) out.release()
def writeOutputFile(self): self.height,self.width=cv2.imread("/Users/pratikramdasi/Desktop/frames/0 (1).jpg").shape[:2] out = cv2.VideoWriter("/Users/pratikramdasi/Desktop/vtest.mp4",cv.CV_FOURCC('a','v','c','1'), 30.0, (self.width, self.height)) folder=self.sort_files() for i in folder: pic="/Users/pratikramdasi/Desktop/frames/0 ("+str(i)+").jpg" img=cv2.imread(pic) out.write(img) out.release()
def writeOutputFile(self,output): self.height,self.width=cv2.imread("Frames/1.jpg").shape[:2] out = cv2.VideoWriter(output,cv.CV_FOURCC('a','v','c','1'), 30.0, (self.width, self.height)) folder=self.sort_files() for i in folder: pic="Frames/"+str(i)+".jpg" img=cv2.imread(pic) out.write(img) out.release() # Method to sort the files (here, frames!)
def open_writer(self, camera): if self.cameras_enabled[camera] and not self.writers[camera]: self.writers[camera] = VideoWriter(path + '/' + camera + self.extension, self.four_cc, self.rate_hz, (self.image[camera].width, self.image[camera].height), isColor=camera != 'depth')
def main(): cap = cv2.VideoCapture(0) frame_size = (int(cap.get(3)), int(cap.get(4))) fourcc = cv2.cv.CV_FOURCC(*"XVID") prev_frame = None last_motion = None motion_filename = None motion_file = None while cap.isOpened(): now = datetime.datetime.now() success, frame = cap.read() assert success, "failed reading frame" frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame_gray = cv2.GaussianBlur(frame_gray, (21, 21), 0) if have_motion(prev_frame, frame_gray): if motion_file is None: motion_filename = now.strftime("%Y_%m_%d_%H_%M_%S_MOTION.avi") motion_file = cv2.VideoWriter(motion_filename, fourcc, 20.0, frame_size) last_motion = now print "Motion!", last_motion if motion_file is not None: motion_file.write(frame) if now - last_motion > MOTION_RECORD_TIME: motion_file.release() motion_file = None Process(target = push_file, args = (motion_filename, )).start() prev_frame = frame_gray cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
def _writevideoframe(self): if not self.is_writingvideo: return if self._videoWriter is None: fps = self._capture.get(cv2.CAP_PROP_FPS) if fps == 0.0: # FPS??????? if self._frameElapsed < 20: # wait until more frame elapse so that the estimate is more stable. return else: fps = self._fpsEstimate # print fps size = (int(self._capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self._capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) self._videoWriter = cv2.VideoWriter(self._videoFilename, self._videoEncoding, fps, size) self._videoWriter.write(self._frame)
def start(self): now = dt.datetime.now() if len(self.path) !=0 and self.path[len(self.path)-1] != '/': self.path = self.path + '/' output_name = self.path + str(dt.datetime.date(now))+ '-0.avi' video_num = 1 while os.path.isfile(output_name): output_name = self.path +str(dt.datetime.date(now)) + '-'+str(video_num)+'.avi' video_num = video_num + 1 fourcc = cv2.cv.CV_FOURCC(*'XVID') self.out = cv2.VideoWriter(output_name,fourcc,self.framerate,(self.width,self.height)) return self