class VideoClipWriter(object): NORMAL_VIDEO = 1 IMG_VIDEO = 2 def __init__(self, path, video_type, fps=25.0, size=None, fmt=ImgVideoCapture.DEFAULT_FMT, start=1): self.typ = video_type if video_type == VideoClipWriter.IMG_VIDEO: self.backend = ImgVideoWriter(path, fmt, start) else: if size is not None: self.backend = VideoWriter( path, cv2.cv.CV_FOURCC('D', 'I', 'V', 'X'), fps, size) else: raise Exception('video size is needed.') def write(self, im): return self.backend.write(im) def release(self): return self.backend.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()
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 __call__(self, img, record_path, FPS, width, height): img = cvtColor(img, COLOR_BGR2RGB) current_time = time() if ((self.interval_time == 0) and (self.record) and (self.is_record == False)): self.video = self.video + 1 self.out = VideoWriter( record_path + '_' + str(self.video) + '.mp4', VideoWriter_fourcc(*'MP4V'), FPS, (width, height)) self.is_record = True self.start_time = time() pass if (self.is_record and self.record): self.out.write(img) self.record_time = time() - self.start_time if (self.record_time > self.time_record): self.is_record = False self.out.release() self.out = None self.interval_time = 1 self.start_time = time() pass if ((self.interval_time is not 0) and (self.record)): self.interval_time = current_time - self.start_time if (self.interval_time > self.time_interval): self.interval_time = 0 pass
class CameraSentry(object): ''' Used for - Maintaining a temp write buffer to append to the recording so we capture moments before an event - Saving video files ''' def __init__(self, maxBufferSize=300, frameRate=30, height=480, width=640): self.buffer = queue.Queue(maxsize=maxBufferSize) self.frameRate = frameRate self.videoDimensions = (width, height) self.fourcc = VideoWriter_fourcc(*'MJPG') self.recorder = None self.isRecording = False def updateBuffer(self, frame): if self.buffer.full() and self.isRecording: self.writeFrame(self.buffer.get(), self.recorder) elif self.buffer.full() and not self.isRecording: self.buffer.get() self.buffer.put(frame) def startRecording(self): self.recorder = VideoWriter('output.avi', self.fourcc, self.frameRate, self.videoDimensions) self.writeFrame(self.buffer.get(), self.recorder) @staticmethod def writeFrame(frame, recorder): recorder.write(frame) def endRecording(self): self.recorder.release() self.recorder = 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))
class Writer(WriterBase): def __init__(self, file: str, fourcc: Union[int, str, Iterable[str]], fps: float, frame_size: Tuple[int, int], is_color: bool = True, *args, **kwargs): super(Writer, self).__init__(file, args, kwargs) self._fourcc: int = _fourcc(fourcc) self._fps: float = fps self._frame_size: Tuple[int, int] = frame_size self._is_color: bool = is_color self._stream: Optional[VideoWriter] = None def write_frame(self, frame: np.ndarray) -> None: self._stream.write(frame) self._position += 1 def open(self, file: str = "", *args, **kwargs) -> None: if not self.closed: self.close() if file: self._file = file self._stream = VideoWriter(self._file, self._fourcc, self._fps, self._frame_size, self._is_color) self._closed = False def close(self) -> None: if not self.closed: self._stream.release() self._initialize_property()
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 save_video(self, frames, n_episode): path = self.writer_path + '/' + str(n_episode.numpy()) + '_episode' if self.out_type == "GIF": path += ".gif" with imageio.get_writer(path, mode='I', duration=0.04) as writer: for i in range(frames.shape[0]): writer.append_data(frames[i].numpy()) elif self.out_type == "MP4": path += ".mp4" self.video_writer = VideoWriter( path, VideoWriter_fourcc(*'mp4v'), 120., tuple(self.frame_size), isColor=False) # alternative codec: MJPG for i in range(frames.shape[0]): self.video_writer.write(frames[i].numpy()) self.pad() self.video_writer.release() self.video_writer = None print("saved video ...") return abspath(path)
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 generate_moving_wave(self, direction, type): ''' Generate moving wave whose direction is defined by the variable, direction. Parameters: ----------- direction: <string> Defines the direction in which the wave has to move type: <string> The type of wave being generated> Square and Sinusoidal waves have been implemented for now. Return: None ------- ''' self.video = VideoWriter('./videos/' + type +'/' + direction + '_'+type + '_' + str(self.f) + 'hz_pattern_gen_'+str(self.fps) + '_fps.mkv', self.fourcc, float(self.fps), (self.width, self.height)) if direction=='horizontal': print('generating video of horizontal wave based phase patterns') dt = 1/self.width x = np.arange(0, self.width, dt) if type == 'sine': y = np.sin(2 * np.pi * x * self.f) if type == 'square': y = signal.square(2 * np.pi * x * self.f) y += max(y) # to shift range of signals to positive values frame = np.array([[y[j]*127 for j in range(self.width)] for i in range(self.height)], dtype=np.uint8) # create 2-D array of sine-wave for _ in range(0, self.width): self.video.write(cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)) shifted_frame = np.roll(frame, self.pixel_shift, axis=1) # simulated the circular shifting effect to make it a continuous frame = shifted_frame if direction=='vertical': print('generating video of horizontal wave based phase patterns') dt = 1/self.height x = np.arange(0, 1, dt) if type == 'sine': y = np.sin(2 * np.pi * x * self.f) if type == 'square': y = signal.square(2 * np.pi * x * self.f) y += max(y) # to shift range of signals to positive values frame = np.array([[y[j]*127 for j in range(self.width)] for i in range(self.height)], dtype=np.uint8).T # create 2-D array of sine-wave. Transpose it to make it vertical for _ in range(0, self.height): self.video.write(cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)) shifted_frame = np.roll(frame, self.pixel_shift, axis=0) frame = shifted_frame cv2.destroyAllWindows() self.video.release() print('generation of moving patterns done')
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 __init__(self, sensor_bp, transform, parent_actor, agent, record=False): self.vehicle = parent_actor self.camera_transform = transform self.world = self.vehicle.world self.agent = agent self.typeofCamera = sensor_bp self.frame_n = 0 bp = self.world.blueprint_library.find(sensor_bp) bp.set_attribute('image_size_x', f'{IM_WIDTH}') bp.set_attribute('image_size_y', f'{IM_HEIGHT}') bp.set_attribute('sensor_tick', f'{SENSOR_TICK}') bp.set_attribute('fov', f'{FOV}') self.sensor = self.world.world.spawn_actor( bp, self.camera_transform, attach_to=self.vehicle.vehicle) self.world.actor_list.append( self.sensor) # add to actor_list of world so we can clean up later weak_self = weakref.ref(self) if record: fourcc = VideoWriter_fourcc(*'MP42') self.video_recorder = VideoWriter('./_out/camera_view.avi', fourcc, float(30), (IM_WIDTH, IM_HEIGHT)) self.sensor.listen(lambda image: Camera.callback(weak_self, image))
class VideoRecorder: def __init__(self, log_dir): if not Params.RECORD_VIDEO: return self.frame_size = Params.FRAME_SIZE.numpy() self.pad_len = 100 self.out_type = Params.RECORD_VIDEO_TYPE if np.less(self.frame_size, 64).any(): raise Exception("Frame size must be > 64px") self.video_writer = None self.writer_path = log_dir if not isdir("recorded"): mkdir("recorded") try: mkdir(self.writer_path) except OSError: raise FileNotFoundError( f"Creation of the directory {self.writer_path} failed") def pad(self): for i in range(self.pad_len): if self.video_writer is not None: self.video_writer.write(np.zeros(self.frame_size.astype(int))) def save_video(self, frames, n_episode): path = self.writer_path + '/' + str(n_episode.numpy()) + '_episode' if self.out_type == "GIF": path += ".gif" with imageio.get_writer(path, mode='I', duration=0.04) as writer: for i in range(frames.shape[0]): writer.append_data(frames[i].numpy()) elif self.out_type == "MP4": path += ".mp4" self.video_writer = VideoWriter( path, VideoWriter_fourcc(*'mp4v'), 120., tuple(self.frame_size), isColor=False) # alternative codec: MJPG for i in range(frames.shape[0]): self.video_writer.write(frames[i].numpy()) self.pad() self.video_writer.release() self.video_writer = None print("saved video ...") return abspath(path)
class Line(Pattern): ''' Class to generate moving lines of different thicknesses, orientations and speeds Init Parameters: ---------------- thickness: <int> pixelwise thickness of the moving line pattern ''' def __init__(self, height, width, fps, thickness): Pattern.__init__(self, height, width, fps) self.thickness = thickness def generate_moving_line(self, direction): ''' Generate moving line whose direction is defined by the variable direction Parameters: ----------- direction: <string> Defines the direction in which the line has to move Return: None ------------ ''' self.video = VideoWriter('./videos/' + direction + 'line_pattern_gen_'+str(self.fps)+'_bit.avis', self.fourcc, float(self.fps), (self.width, self.height)) if direction=='vertical': print('generating video of vertical line') for x_coord in range(0, self.width): frame = np.zeros((self.height, self.width, 3), dtype=np.uint8) cv2.line(frame, (x_coord, 0), (x_coord, self.height), (0, 0, 255),self.thickness) self.video.write(frame) if direction=='horizontal': print('generating video of horizontal line') for y_coord in range(0, self.height): frame = np.zeros((self.height, self.width, 3), dtype=np.uint8) cv2.line(frame, (0, y_coord), (self.width, y_coord), (0, 0, 255), self.thickness) self.video.write(frame) if direction=='tl_diag': print('generating line from top left') for i in range(0, 2*self.width): frame = np.zeros((self.height, self.width, 3), dtype=np.uint8) cv2.line(frame, (0,i), (i,0), (0, 0, 255), self.thickness) self.video.write(frame) if direction=='bl_diag': print('generating line from bottom left') for i in range(2*self.width): frame = np.zeros((self.height, self.width, 3), dtype=np.uint8) cv2.line(frame, (0,self.width-i), (i,self.width), (0, 0, 255), self.thickness) self.video.write(frame) cv2.destroyAllWindows() self.video.release()
def run(self): """ Yes, importing all these modules from within a function is gettho, but I have not found a way around it yet. import cv2 will start displaying the feed with Qt5 (my default), which then appears to be "taken" for all the other plots being display. Therefore, the next backend is used for the other plots - TkAgg - and my package was not written to support something else than TkAgg. :return: """ #import cv2 # Gettho but I have not there seems to be conflicts with matplotlib if outside local scope. from cv2 import imshow, VideoCapture, flip, waitKey, destroyAllWindows, VideoWriter, VideoWriter_fourcc # Create the camera object self.capture_object = VideoCapture(self.s['camera_address']) ret, frame = self.capture_object.read() imshow('frame', frame) # Display the first image actual_resolution = (frame.shape[1], frame.shape[0]) print("[INFO] Webcam frames are {} shape".format(frame.shape)) counter = 0 self.flag_camera_ready.set() self.t0 = time.perf_counter() while self.flag_camera_ready.is_set( ): # Loop until parent sets the camera ready flag to False if self.flag_reading_data.is_set(): ret, frame = self.capture_object.read() counter += 1 #print(counter) frame = flip(frame, 1) # Vertical flip if ret == True: self.frame_buffer.append( frame) # Put the frame in a buffer imshow( 'frame', frame ) # For fun, not required if that takes too much resources if waitKey(1) & 0xFF == ord('q'): break else: raise ValueError('[ERROR] Problem here, look at it.') else: #print('[INFO] Camera is not ready') pass self.t1 = time.perf_counter() # Define the codec and create VideoWriter object print("[INFO] Recorded video for {} s".format(self.t1 - self.t0)) fourcc = VideoWriter_fourcc(*'MPEG') actual_fps = len(self.frame_buffer) / (self.t1 - self.t0 ) # Cannot be controlled self.out = VideoWriter(self.s['path_video'], fourcc, actual_fps, actual_resolution) for frame in self.frame_buffer: self.out.write(frame) self.capture_object.release() self.out.release() destroyAllWindows() print("[INFO] Camera process is now terminating.")
class AviWriter: def __init__(self, fName, size=None, fps=25, isColor=True, fourcc=cv.CV_FOURCC(*'MJPG')): #('X','V', 'I', 'D')): self.fileName = fName self.width = -1 self.height = -1 self.frames = 0 self.fps = fps self.aviHandler = None self.fourcc = fourcc self.isColor = isColor self.size = size def __del__(self): self.clearAviHandler() def clearAviHandler(self): if self.aviHandler != None: self.aviHandler.release() self.aviHandler = None def getFileName(self): return self.fileName def getWidth(self): return self.width def getHeight(self): return self.height def getFrames(self): return self.frames def open(self, w, h): self.clearAviHandler() print(self.fileName) print(self.fourcc) print(self.fps) print(self.size) print(self.isColor) self.aviHandler = VideoWriter(self.fileName, self.fourcc, self.fps, (w, h), self.isColor) def addFrame(self, data): h, w, z = data.shape if self.aviHandler == None: self.open(w, h) if not self.aviHandler.isOpened(): print("AviWriter file is not opened, cannot save!") return data = cvtColor(data, cv.CV_RGB2BGR) self.aviHandler.write(data)
def open(self, file: str = "", *args, **kwargs) -> None: if not self.closed: self.close() if file: self._file = file self._stream = VideoWriter(self._file, self._fourcc, self._fps, self._frame_size, self._is_color) self._closed = False
def save_batch_on_disk(images: List[np.ndarray], video_writer: cv2.VideoWriter = None) -> None: """""" if video_writer: for image in images: video_writer.write(image) else: print("[ERROR]: Video writer is not initialized!")
def __encode_frame(self, frame_path: str, writer: cv.VideoWriter) -> None: frame = cv.imread(frame_path) height, width = frame.shape[:2] if (width, height) != self.__target_size: frame = cv.resize(frame, self.__target_size, interpolation=cv.INTER_LINEAR) writer.write(frame)
def open(self, w, h): self.clearAviHandler() print(self.fileName) print(self.fourcc) print(self.fps) print(self.size) print(self.isColor) self.aviHandler = VideoWriter(self.fileName, self.fourcc, self.fps, (w, h), self.isColor)
def writer_f(writer: cv2.VideoWriter, writer_event: Event, frames: Queue): while not writer_event.is_set() or not frames.empty(): try: frame = frames.get_nowait() writer.write(frame) except: pass sleep(0.001)
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 im2video(src, fps = 30.0, image_size = (1280,720)): print('input= > {}'.format(src)) fourcc = VideoWriter_fourcc(*"MP4V") vid = VideoWriter(os.path.join(os.path.abspath(src), "input.mp4"),fourcc, fps, image_size) for file in os.listdir(src): print('{}'.format(file)) path = os.path.join(os.path.abspath(src), file) img = cv2.imread(path, 1) print(path, end = '\r') vid.write(img)
def __init__(self, curves, file, codec, fps): self.curves = curves self.max_terms_seq = None self.durations_seq = None self.fourcc = VideoWriter_fourcc(*codec) self.video = VideoWriter('./' + file, self.fourcc, float(fps), (curves.width, curves.height)) self.fps = fps self.width = curves.width self.height = curves.height
class SimVideoWriter: def __init__(self, path=videoPath, width=videoWidth, height=videoHeight, fps=videoFPS): if os.path.isfile(path): filename, extension = os.path.splitext(path) i = 0 while os.path.isfile(path): path = filename + str(i) + extension i += 1 self.width = width self.height = height codec = 'HFYU' if lossless else 'avc1' self.video = VideoWriter(path, VideoWriter_fourcc(*codec), float(fps), (width, height)) self.cellWidth = np.floor(width / worldWidth) self.cellHeight = np.floor(height / worldHeight) def end(self): self.video.release() def writeFrame(self, world): frame = np.empty((self.height, self.width, 3), dtype=np.uint8) frame[:, :] = backgroundColor for cell in world.cells: cellColor = tuple(reversed(colors[cell.team])) # BGR ageFactor = (cell.maxAge - cell.age) / cell.maxAge # 1 -> young, 0 -> old lifePointsFactor = cell.lifePoints / cell.maxLifePoints # 1 -> healthy, 0 -> damaged alpha = (ageFactor + lifePointsFactor) / 2.0 pt1 = (int(cell.col * self.cellWidth), int(cell.row * self.cellHeight)) pt2 = (int((cell.col + 1) * self.cellWidth), int((cell.row + 1) * self.cellHeight)) cellBackground = frame[ pt1[1]:pt2[1], pt1[0]:pt2[0]] # Beware, X and Y must be reversed here cellArea = np.ones(cellBackground.shape, dtype=np.uint8) for i in range(3): cellArea[:, :, i] = cellColor[i] blend = cv2.addWeighted(cellBackground, (1 - alpha), cellArea, alpha, 0) frame[pt1[1]:pt2[1], pt1[0]:pt2[0]] = blend self.video.write(frame)
def WriteFrame(stream: cv2.VideoWriter, frame: numpy.ndarray) -> None: """ 向输出流写入一帧 Args: stream: frame: Returns: """ stream.write(frame)
class CV2Writer: def __init__(self, out_name, size): from cv2 import VideoWriter, VideoWriter_fourcc self.vid = VideoWriter(out_name, cv2.VideoWriter_fourcc(*"MP4V"), FPS, size, True) def write(self, img): self.vid.write(img) def close(self): self.vid.release()
def __init__(self, res, fps): # output related self.res = np.array(res, dtype="int") self.fps = float(fps) self.current_frame = self.new_frame() self.closed = False # renderer self.filename = OUT_DIR + strftime('%Y%m%dT%H%M%S', localtime()) + ".mp4" self.title = f"Boids - Preview - {self.filename}" self.video = VideoWriter(self.filename, FourCC(*"mp4v"), int(self.fps), tuple(self.res))
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
def __init__(self, path): self.path = path FPS = 1 frame = cv2.imread(self.path) #get frame shape self.height, self.width, self.channels = frame.shape #create the video self.fourcc = VideoWriter_fourcc(*'MP42') self.video = VideoWriter('./noise.mp4', self.fourcc, float(FPS), (self.width, self.height))
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()
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
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 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)
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
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 __init__(self, file_loc, frame_rate, frame_size): super().__init__() self.writer = VideoWriter( file_loc, VideoWriter_fourcc(*"DIVX"), float(frame_rate), frame_size )
opt.length))) print 'Simulating {:d} steps of a {:d}x{:d} lattice at beta={:f}'.format( opt.steps, opt.length, opt.length, opt.beta) print 'Writing run data to ' + opt.output if opt.movie: if opt.movie != True: video_filename = opt.movie else: if opt.output[-4] == '.': 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()
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 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()