def save_video_helper(cam, file_format, filename, framerate): num_images = 200 video = PyCapture2.FlyCapture2Video() for i in range(num_images): print('index ', i) try: print("before retrievebuffer") image = cam.retrieveBuffer() print("after retrievebuffer") except PyCapture2.Fc2error as fc2Err: print('Error retrieving buffer : %s' % fc2Err) continue print('Grabbed image {}'.format(i)) if (i == 0): if file_format == 'AVI': video.AVIOpen(filename, framerate) elif file_format == 'MJPG': video.MJPGOpen(filename, framerate, 75) elif file_format == 'H264': video.H264Open(filename, framerate, image.getCols(), image.getRows(), 1000000) else: print('Specified format is not available.') return video.append(image) print('Appended image %d...' % i) print('Appended {} images to {} file: {}...'.format( num_images, file_format, filename)) video.close()
def generate_signal(camera, filename, framerate, channel, output): video = PyCapture2.FlyCapture2Video() video.AVIOpen(filename, framerate) t = np.zeros(len(output)) with nidaqmx.Task() as writeTask: writeTask.ao_channels.add_ao_voltage_chan("Dev1/ao0") writeTask.start() for i in range(len(output)): writeTask.write(output[i]) t[i] = time.time() image = camera.retrieveBuffer() video.append(image) writeTask.stop() print('Appended {} images to AVI file: {}...'.format( len(output), filename)) video.close() print("Done with data") return t
def openVideoWriter(self, filename, encoder=None, overwrite=False, quality=75, bitrate=1000000, img_size=None, csv_timestamps=True, embed_image_info=['timestamp']): """ Opens a video writer. Subsequent calls to .get_image() will additionally write those frames out to the file. Parameters ---------- filename : str Path to desired output file. If extension is omitted it will be inferred from <file_format> (if specified). encoder : str { 'AVI' | 'MJPG' | 'H264' } or None, optional Output encoder to use. If None, will automatically set to 'AVI' if filename ends with an '.avi' extension, 'H264' if filename ends with a 'mp4' extension, or will raise an error for other extensions. Note that 'MJPG' and 'H264' formats permit addtional arguments to be passed. The default is None. overwrite : bool, optional If False and the output file already exists, an error will be raised. The default is False. quality : int, optional Value between 0-100 determining output quality. Only applicable for MJPG format. The default is 75. bitrate : int, optional Bitrate to encode at. Only applicable for H264 format. The default is 1000000. img_size : (W,H) tuple of ints, optional Image resolution. Only applicable for H264 format. If not given, will attempt to determine from camera's video mode, but this might not work. The default is None. csv_timestamps : bool, optional If True, timestamps for each frame will be saved to a csv file corresponding to the output video file. The default is True. Note that to get 1394 cycle timestamps (more accurate), the timestamp property MUST be enabled within the embedded image info. embed_image_info : list or 'all' or None, optional List of properties to embed within top-left image pixels. Note that video MUST be monochrome for pixel values to be usable. Available properties are: [timestamp, gain, shutter, brightness, exposure, whiteBalance, frameCounter, strobePattern, ROIPosition]. Alternatively specify 'all' to use all available properties. Specify None to not embed any properties. The timestamp property MUST be enabled to get 1394 cycle timestamps in the CSV file (if applicable), regardless of whether the embedded information itself is going to be used. The default is to embed timestamps. """ # Try to auto-determine file format if unspecified if encoder is None: ext = os.path.splitext(filename)[1].lower() # case insensitive if ext == '.avi': encoder = 'AVI' elif ext == '.mp4': encoder = 'H264' elif not ext: raise ValueError('Cannot determine file_format automatically ' 'without file extension') else: raise ValueError('Cannot determine file_format automatically ' f'from {ext} extension') print(f'Recording using {encoder} encoder') encoder = encoder.upper() # ensure case insensitive if not encoder in ['AVI', 'MJPG', 'H264']: raise ValueError("Encoder must be one of 'AVI', 'MJPG', or 'H264, " f"but received {encoder}") # Auto-determine file extension if necessary if not os.path.splitext(filename)[1]: if encoder in ['AVI', 'MJPG']: filename += '.avi' elif encoder == 'H264': filename += '.mp4' # Without overwrite, error if file exists. AVI writer sometimes # appends a bunch of zeros to name, so check that too. if not overwrite: _filename, ext = os.path.splitext(filename) alt_filename = _filename + '-0000' + ext if os.path.isfile(filename) or os.path.isfile(alt_filename): raise OSError(f'Output file {filename} already exists') # Update camera to embed image info available_info = self.cam.getEmbeddedImageInfo().available prop_keys = [k for k in dir(available_info) if not k.startswith('__')] props = dict((k, False) for k in prop_keys) if embed_image_info: if not isinstance(embed_image_info, (list, tuple)): embed_image_info = [embed_image_info] if 'all' in embed_image_info: for k in prop_keys: props[k] = getattr(available_info, k) else: # use specified values for k in embed_image_info: if k not in prop_keys: raise KeyError( "Embedded property must be one of " f"list({prop_keys}), but received '{k}'") elif not getattr(available_info, k): raise ValueError( f"'{k}' embedded property not available") props[k] = True self.cam.setEmbeddedImageInfo(**props) # Open csv writer for timestamps? if csv_timestamps: csv_filename = os.path.splitext(filename)[0] + '.csv' if not overwrite and os.path.isfile(csv_filename): raise OSError(f'Timestamps file {csv_filename} already exists') self.csv_fd = open(csv_filename, 'w') fieldnames = [ 'seconds', 'microSeconds', 'cycleSeconds', 'cycleCount', 'cycleOffset' ] self.csv_writer = DictWriter(self.csv_fd, fieldnames, delimiter=',', lineterminator='\n') self.csv_writer.writeheader() # Initialise video writer, allocate to class self.video_writer = PyCapture2.FlyCapture2Video() # Open video file bytes_filename = filename.encode('utf-8') # needs to be bytes string if encoder == 'AVI': self.video_writer.AVIOpen(bytes_filename, self.fps) elif encoder == 'MJPG': self.video_writer.MJPGOpen(bytes_filename, self.fps, quality) elif encoder == 'H264': if img_size is None: if self.img_size is None: raise RuntimeError('Cannot determine image resolution') else: img_size = self.img_size W, H = img_size self.video_writer.H264Open(bytes_filename, self.fps, W, H, bitrate) # Success! self._video_writer_isOpen = True