我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用cv2.VideoWriter_fourcc()。
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 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 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 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 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, output='video.avi', fps=20, codec=["M", "J", "P", "G"]): self.output = output self.fps = fps self.codec = codec self.fourcc = cv2.VideoWriter_fourcc(*self.codec) self.writer = None (self.h, self.w) = (None, None) self.zeros = None
def __init__(self, output='video.avi', fps=20, codec=["M", "J", "P", "G"]): self.output = output self.fps = fps self.codec = codec self.fourcc = cv2.VideoWriter_fourcc(*self.codec) self.writer = None (self.h, self.w) = (None, None)
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 __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 start_writinvideo(self, filename, encoding=cv2.VideoWriter_fourcc('I', '4', '2', '0')): # cv2.VideoWriter_fourcc('I', '4', '2', '0') """Start Writing existed frame to a video file""" self._videoFilename = filename self._videoEncoding = encoding
def toMovie(): """ iterating the files and save them to movie-file """ files = checkInput() codecs = cv2.VideoWriter_fourcc(*'FMP4') height, width, channel = cv2.imread(files[0]).shape video = cv2.VideoWriter(outputfile + ".mkv", codecs, fps, (width, height), True) if not video.isOpened(): sys.exit("Error when writing video file") images = 0 found = 0 for file in files: dst = calculatePicture(file) images = images + 1 if quiet: sys.stdout.flush() sys.stdout.write("\rimages: " + str(images) + "/" + str(len(files)) + " and " + str(found) + " added to movie") if dst is not None and video.isOpened(): found = found + 1 video.write(dst) video.release() if quiet: print print("saved to " + outputfile + ".mkv")
def __init__(self, camera, cmd_q, res, codec, fps): Process.__init__(self) self.res = res self.fps = fps self.codec = codec self.camera = camera self.fourcc = cv2.VideoWriter_fourcc(*self.codec) self.cmd_q = cmd_q self.recording = False self.out = None self.data_buf = None
def __init__(self, size, fps, date, codec, extension): self.date = date self.extension = extension self.fourcc = cv2.VideoWriter_fourcc(*codec) if codec else 0 self.fps = fps self.size = size self.queue = Queue(maxsize = 32) thread = Thread(target=self.run) thread.start()
def __init__(self): self.eye_region_of_interest = [Pt(0, 0), Pt(320, 240)] self.blob_history = [] self.enabled = True self.eye_padding = 10 self.has_roi = False self.pipeline = GripWrapper() self.blinks = 0 self.pipeline_completions = 0 self.w = 320 self.h = 240 self.video_writer = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), 15, (self.w, self.h)) self.blank_frame = numpy.zeros([self.h, self.w, 3]).astype(numpy.uint8) self.done = False
def __init__(self, path, fps=30.0): fourcc = VideoWriter_fourcc(*"XVID") self.path = path self.data = writer(self.path, fourcc, fps, (1920,1080))
def main(args): fourcc = cv2.VideoWriter_fourcc('M','J','P','G') writer = cv2.VideoWriter('/tmp/outpu.avi', fourcc, 10, (1920, 1200)) os.chdir(args.image_folder) file_list = glob.glob("*.jpg") sorted_files = sorted(file_list, key=lambda x: int(x.split('.')[0])) for file in sorted_files: print(file) img = cv2.imread(file) writer.write(img) writer.release()
def normalize(path, **kwargs): reso = kwargs.pop('reso', (WIDTH, HEIGHT)) seconds = kwargs.pop('sec', SECONDS) fps = kwargs.pop('fps', FPS) remove = kwargs.pop('remove', True) log = kwargs.pop('log', True) if platform == "linux" or platform == "linux2": codec = LINUX_CODEC elif platform == "darwin": codec = MAC_CODEC else: raise Exception("Unsupported Platform") codec = kwargs.pop('codec', codec) if not os.path.isfile(path): raise Exception('%s not found!' % (path, )) audio_path = path[0:-4] + '.tmp.wav' command = "ffmpeg -i %s %s -y" % (path, audio_path) download_log = open("download.log", 'w') if log else None subprocess.call(command, shell=True, stdout=download_log, stderr=subprocess.STDOUT) cap = cv2.VideoCapture(path) cv2_version = cv2.__version__[0] if cv2_version == '3': fourcc = cv2.VideoWriter_fourcc(*codec) elif cv2_version == '2': fourcc = cv2.cv.CV_FOURCC(*codec) else: raise Exception('Unsupported OpenCV version!') out_path = path[0:-4] + '.tmp.avi' out = cv2.VideoWriter(out_path, fourcc, fps, reso, True) frame_count = fps * seconds while(cap.isOpened()): if frame_count <= 0: break frame_count -= 1 ret, frame = cap.read() if not ret: continue resized = cv2.resize(frame, reso) out.write(resized) cap.release() out.release() if remove: os.unlink(path) return (audio_path, out_path)
def main(parser): capture = cv2.VideoCapture(parser.source) src_width, src_height = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) if(parser.record == True): fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(parser.output_path,fourcc, 20.0, (src_width,src_height)) cascPath = "./haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) while True: ret, frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE ) pred_features = detect_features(gray, faces, src_width, src_height, parser.width, parser.height) result_img = draw_features_point_on_image(frame, pred_features, src_width, src_height) for (x, y, w, h) in faces: cv2.rectangle(result_img, (x, y), (x+w, y+h), (0, 255, 0), 1) if (ret==True) and (parser.record == True): out.write(result_img) cv2.imshow('Video', result_img) if cv2.waitKey(1) & 0xFF == ord('q'): break capture.release() if parser.record == True: out.release() cv2.destroyAllWindows()
def _exportVideoThread(self): ww = self.display.widget n = None if self.pAnnotate.value(): n = self.display.layerNames() videoWrite(self.pPath.value(), ww.image, levels=ww.item.levels, shape=(self.pHeight.value(), self.pWidth.value()), frames=self.pFrames.value(), annotate_names=n, lut=ww.item.lut, updateFn=self._thread.sigUpdate) # # fourcc = cv2.VideoWriter_fourcc(*'XVID') # ww = self.display.widget # im = ww.image # if self.pResize.value(): # w, h = (self.pWidth.value(), self.pHeight.value()) # im = [cv2.resize(i, (w, h)) for i in im] # else: # h, w = im.shape[1:3] # fr = self.pFrames.value() # pa = self.pPath.value() # assert pa[-3:] in ('avi', # 'png'), 'video export only supports *.avi or *.png' # isVideo = pa[-3:] == 'avi' # if isVideo: # cap = cv2.VideoCapture(0) # # im.ndim==4) # out = cv2.VideoWriter(pa, fourcc, fr, (w, h), isColor=1) # # times = np.linspace(0, len(im), len(im) * fr) # interpolator = LinearInterpolateImageStack(im) # # lut = ww.item.lut # if lut is not None: # lut = lut(im[0]) # # for n, time in enumerate(times): # # update progress: # self._thread.sigUpdate.emit(100 * n / len(times)) # image = interpolator(time) # # argb = makeRGBA(image, lut=lut, # levels=ww.item.levels)[0] # cimg = cv2.cvtColor(argb, cv2.COLOR_RGBA2BGR) # # if isVideo: # out.write(cimg) # else: # cv2.imwrite('%s_%i_%.3f.png' % (pa[:-4], n, time), cimg) # # if isVideo: # cap.release() # out.release()
def video(self, tensor=None, videofile=None, win=None, env=None, opts=None): """ This function plays a video. It takes as input the filename of the video or a `LxHxWxC` tensor containing all the frames of the video. The function does not support any plot-specific `options`. """ opts = {} if opts is None else opts opts['fps'] = opts.get('fps', 25) _assert_opts(opts) assert tensor is not None or videofile is not None, \ 'should specify video tensor or file' if tensor is not None: import cv2 import tempfile assert tensor.ndim == 4, 'video should be in 4D tensor' videofile = '/tmp/%s.ogv' % next(tempfile._get_candidate_names()) if cv2.__version__.startswith('2'): # OpenCV 2 fourcc = cv2.cv.CV_FOURCC( chr(ord('T')), chr(ord('H')), chr(ord('E')), chr(ord('O')) ) elif cv2.__version__.startswith('3'): # OpenCV 3 fourcc = cv2.VideoWriter_fourcc( chr(ord('T')), chr(ord('H')), chr(ord('E')), chr(ord('O')) ) writer = cv2.VideoWriter( videofile, fourcc, opts.get('fps'), (tensor.shape[1], tensor.shape[2]) ) assert writer.isOpened(), 'video writer could not be opened' for i in range(tensor.shape[0]): writer.write(tensor[i, :, :, :]) writer.release() writer = None extension = videofile.split(".")[-1].lower() mimetypes = dict(mp4='mp4', ogv='ogg', avi='avi', webm='webm') mimetype = mimetypes.get(extension) assert mimetype is not None, 'unknown video type: %s' % extension bytestr = loadfile(videofile) videodata = """ <video controls> <source type="video/%s" src="data:video/%s;base64,%s"> Your browser does not support the video tag. </video> """ % (mimetype, mimetype, base64.b64encode(bytestr).decode('utf-8')) return self.text(text=videodata, win=win, env=env, opts=opts)
def main(): args = parser.parse_args() mask = cv2.imread(args.mask_file, cv2.IMREAD_COLOR) cap = cv2.VideoCapture(args.in_video) last_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) - 1 if args.end_with == -1: args.end_with = last_frame else: if args.end_with > last_frame: print( "Warning: specified end frame ({:d})is beyond the last video frame ({:d}). Stopping after last frame.".format( args.end_with, last_frame)) args.end_with = last_frame if args.out_video == "": args.out_video = args.in_video[:-4] + "_masked.mp4" writer = cv2.VideoWriter(args.out_video, cv2.VideoWriter_fourcc('X', '2', '6', '4'), cap.get(cv2.CAP_PROP_FPS), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))), True) writer.set(cv2.VIDEOWRITER_PROP_NSTRIPES, cpu_count()) if args.start_from > 0: cap.set(cv2.CAP_PROP_POS_FRAMES, args.start_from) total_frame_span = args.end_with - args.start_from frame_counter = 0 if args.frame_count == -1: cur_frame_number = args.start_from while cur_frame_number < args.end_with: process_frame(cap, writer, mask) frame_counter += 1 amount_done = frame_counter / total_frame_span update_progress(amount_done) cur_frame_number += 1 else: frame_interval = total_frame_span // args.frame_count for i_frame in range(args.start_from, args.end_with, frame_interval): cap.set(cv2.CAP_PROP_POS_FRAMES, i_frame) process_frame(cap, writer, mask) frame_counter += 1 amount_done = frame_counter / args.frame_count update_progress(amount_done) cap.release() writer.release() return 0
def __init__(self, args, out_postfix="_out", with_video_output=True): self.global_video_offset = 0 self.flip_video = False self.datapath = "./" self.__dict__.update(vars(args)) self.writer = None if os.path.exists("settings.yaml"): stream = open("settings.yaml", mode='r') self.settings = load(stream, Loader=Loader) stream.close() self.datapath = self.settings['datapath'].replace("<current_user>", getuser()) print("Processing path: ", self.datapath) if 'raw_options' in self.settings: raw_options = self.settings['raw_options'] if self.in_video in raw_options: self.global_video_offset = raw_options[args.in_video]['global_offset'] self.flip_video = raw_options[args.in_video]['flip'] self.cap = None self.reload_video() print("Processing video file {:s}.".format(self.in_video)) last_frame = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) - 1) if self.end_with == -1: self.end_with = last_frame else: if self.end_with > last_frame: print(("Warning: specified end frame ({:d}) is beyond the last video frame" + " ({:d}). Stopping after last frame.") .format(self.end_with, last_frame)) self.end_with = last_frame print("Frame range: {:d}--{:d}".format(self.start_from, self.end_with)) if with_video_output: if self.out_video == "": self.out_video = args.in_video[:-4] + "_" + out_postfix + ".mp4" self.writer = cv2.VideoWriter(os.path.join(self.datapath, self.out_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))), True) self.writer.set(cv2.VIDEOWRITER_PROP_NSTRIPES, cpu_count()) else: self.writer = None self.frame = None self.cur_frame_number = None
def camera(self, file, SaveVideo): if file == 'camera': file = 0 else: assert os.path.isfile(file), \ 'file {} does not exist'.format(file) camera = cv2.VideoCapture(file) self.say('Press [ESC] to quit demo') assert camera.isOpened(), \ 'Cannot capture source' elapsed = int() start = timer() cv2.namedWindow('', 0) _, frame = camera.read() height, width, _ = frame.shape cv2.resizeWindow('', width, height) if SaveVideo: fourcc = cv2.VideoWriter_fourcc(*'XVID') if file == 0: fps = 1 / self._get_fps(frame) if fps < 1: fps = 1 else: fps = round(camera.get(cv2.CAP_PROP_FPS)) videoWriter = cv2.VideoWriter('video.avi', fourcc, fps, (width, height)) while camera.isOpened(): _, frame = camera.read() if frame is None: print ('\nEnd of Video') break preprocessed = self.framework.preprocess(frame) feed_dict = {self.inp: [preprocessed]} net_out = self.sess.run(self.out,feed_dict)[0] processed = self.framework.postprocess(net_out, frame, False) if SaveVideo: videoWriter.write(processed) cv2.imshow('', processed) elapsed += 1 if elapsed % 5 == 0: sys.stdout.write('\r') sys.stdout.write('{0:3.3f} FPS'.format( elapsed / (timer() - start))) sys.stdout.flush() choice = cv2.waitKey(1) if choice == 27: break sys.stdout.write('\n') if SaveVideo: videoWriter.release() camera.release() cv2.destroyAllWindows()