Python imageio.mimread() Examples
The following are 12
code examples of imageio.mimread().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
imageio
, or try the search function
.
Example #1
Source File: readAVI_imageio.py From pyimagevideo with GNU General Public License v3.0 | 6 votes |
def testreadavi(fn: Path): fn = Path(fn).expanduser() vid = imageio.mimread(fn) # %% play video ax = figure().gca() h = ax.imshow(vid[0]) t = ax.set_title('') for i, I in enumerate(vid): h.set_data(I) t.set_text(str(i)) draw() pause(0.1)
Example #2
Source File: gif.py From dreampower with GNU General Public License v3.0 | 6 votes |
def _setup(self, *args): self.__phases = select_phases(self._args) self.__input_path = self._args['input'] self.__output_path = self._args['output'] self.__tmp_dir = None self.__temp_input_paths = [] self.__temp_output_paths = [] self.__tmp_dir = tempfile.mkdtemp() Conf.log.debug("Temporay dir is {}".format(self.__tmp_dir)) imgs = imageio.mimread(self.__input_path) Conf.log.info("GIF have {} Frames To Process".format(len(imgs))) self.__temp_input_paths = [os.path.join(self.__tmp_dir, "intput_{}.png".format(i)) for i in range(len(imgs))] self._args['input'] = self.__temp_input_paths self.__temp_output_paths = [os.path.join(self.__tmp_dir, "output_{}.png".format(i)) for i in range(len(imgs))] self._args['output'] = self.__temp_output_paths for i in zip(imgs, self.__temp_input_paths): write_image(cv2.cvtColor(i[0], cv2.COLOR_RGB2BGR), i[1])
Example #3
Source File: utils.py From dreampower with GNU General Public License v3.0 | 6 votes |
def check_shape(path, shape=Conf.desired_shape): """ Validate the shape of an image. :param image: <RGB> Image to check :param shape: <(int,int,int)> Valid shape :return: None """ if os.path.splitext(path)[1] != ".gif": img_shape = read_image(path).shape else: img_shape = imageio.mimread(path)[0][:, :, :3].shape if img_shape != shape: Conf.log.error("{} Image is not 512 x 512, got shape: {}".format(path, img_shape)) Conf.log.error("You should use one of the rescale options or manually resize the image") sys.exit(1)
Example #4
Source File: test_base.py From pulse2percept with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_Percept_save(): ndarray = np.arange(256, dtype=np.float32).repeat(31).reshape((-1, 16, 16)) percept = Percept(ndarray.transpose((2, 0, 1))) # Save multiple frames as a gif or movie: for fname in ['test.mp4', 'test.avi', 'test.mov', 'test.wmv', 'test.gif']: print(fname) percept.save(fname) npt.assert_equal(os.path.isfile(fname), True) # Normalized to [0, 255] with some loss of precision: mov = mimread(fname) npt.assert_equal(np.min(mov) <= 2, True) npt.assert_equal(np.max(mov) >= 250, True) os.remove(fname) # Cannot save multiple frames image: fname = 'test.jpg' with pytest.raises(ValueError): percept.save(fname) # But, can save single frame as image: percept = Percept(ndarray[..., :1]) for fname in ['test.jpg', 'test.png', 'test.tif', 'test.gif']: percept.save(fname) npt.assert_equal(os.path.isfile(fname), True) img = img_as_float(imread(fname)) npt.assert_almost_equal(np.min(img), 0, decimal=3) npt.assert_almost_equal(np.max(img), 1.0, decimal=3) os.remove(fname)
Example #5
Source File: main.py From mil with MIT License | 5 votes |
def generate_test_demos(data_generator): if not FLAGS.use_noisy_demos: n_folders = len(data_generator.demos.keys()) demos = data_generator.demos else: n_folders = len(data_generator.noisy_demos.keys()) demos = data_generator.noisy_demos policy_demo_idx = [np.random.choice(n_demo, replace=False, size=FLAGS.test_update_batch_size) \ for n_demo in [demos[i]['demoX'].shape[0] for i in xrange(n_folders)]] selected_demoO, selected_demoX, selected_demoU = [], [], [] for i in xrange(n_folders): selected_cond = np.array(demos[i]['demoConditions'])[np.arange(len(demos[i]['demoConditions'])) == policy_demo_idx[i]] Xs, Us, Os = [], [], [] for idx in selected_cond: if FLAGS.use_noisy_demos: demo_gif_dir = data_generator.noisy_demo_gif_dir else: demo_gif_dir = data_generator.demo_gif_dir O = np.array(imageio.mimread(demo_gif_dir + data_generator.gif_prefix + '_%d/cond%d.samp0.gif' % (i, idx)))[:, :, :, :3] O = np.transpose(O, [0, 3, 2, 1]) # transpose to mujoco setting for images O = O.reshape(FLAGS.T, -1) / 255.0 # normalize Os.append(O) Xs.append(demos[i]['demoX'][np.arange(demos[i]['demoX'].shape[0]) == policy_demo_idx[i]].squeeze()) Us.append(demos[i]['demoU'][np.arange(demos[i]['demoU'].shape[0]) == policy_demo_idx[i]].squeeze()) selected_demoO.append(np.array(Os)) selected_demoX.append(np.array(Xs)) selected_demoU.append(np.array(Us)) print "Finished collecting demos for testing" selected_demo = dict(selected_demoX=selected_demoX, selected_demoU=selected_demoU, selected_demoO=selected_demoO) data_generator.selected_demo = selected_demo
Example #6
Source File: eval_push.py From mil with MIT License | 5 votes |
def load_demo(task_id, demo_dir, demo_inds): demo_info = pickle.load(open(demo_dir+task_id+'.pkl', 'rb')) demoX = demo_info['demoX'][demo_inds,:,:] demoU = demo_info['demoU'][demo_inds,:,:] d1, d2, _ = demoX.shape demoX = np.reshape(demoX, [1, d1*d2, -1]) demoU = np.reshape(demoU, [1, d1*d2, -1]) # read in demo video if CROP: demo_gifs = [imageio.mimread(demo_dir+'crop_object_'+task_id+'/cond%d.samp0.gif' % demo_ind) for demo_ind in demo_inds] else: demo_gifs = [imageio.mimread(demo_dir+'object_'+task_id+'/cond%d.samp0.gif' % demo_ind) for demo_ind in demo_inds] return demoX, demoU, demo_gifs, demo_info
Example #7
Source File: test_all.py From pyimagevideo with GNU General Public License v3.0 | 5 votes |
def test_tiff_multipage_rw(): pytest.importorskip('skimage') pytest.importorskip('matplotlib') with tempfile.TemporaryDirectory() as d: d = Path(d).expanduser() piv.genimgseries(d) ofn = d / 'mp.tif' piv.png2tiff(ofn, '[0-9].png') y = imageio.mimread(ofn) assert len(y) == 10
Example #8
Source File: benchmark.py From aicsimageio with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _run_benchmark_suite(resources_dir: Path): # Default reader / imageio imread tests default_reader_single_image_results = _run_benchmark( resources_dir=resources_dir, extensions=["*.png", "*.jpg", "*.bmp"], non_aicsimageio_reader=imageio.imread, ) # Default reader / imageio mimread tests default_reader_many_image_results = _run_benchmark( resources_dir=resources_dir, extensions=["*.gif"], non_aicsimageio_reader=imageio.mimread, ) # Tiff reader / tifffile imread tests tiff_reader_results = _run_benchmark( resources_dir=resources_dir, extensions=["*.tiff"], non_aicsimageio_reader=tifffile.imread, ) # CZI reader / czifile imread tests czi_reader_results = _run_benchmark( resources_dir=resources_dir, extensions=["*.czi"], non_aicsimageio_reader=czifile.imread, ) return [ *default_reader_single_image_results, *default_reader_many_image_results, *tiff_reader_results, *czi_reader_results, ]
Example #9
Source File: pusher_mil_pytorch_data_loader.py From rl_swiss with MIT License | 5 votes |
def __getitem__(self, task): ''' We use idx as meaning the task idx ''' task = self.prefix + '_' + str(task) traj_idxs = np.random.choice( self.demos[task]['demoU'].shape[0], size=self.total_num_trajs_per_task, replace=False ) # get the states U = [self.demos[task]['demoU'][v] for v in traj_idxs] U = np.array(U) X = [self.demos[task]['demoX'][v] for v in traj_idxs] X = np.array(X) assert U.shape[2] == self.act_dim assert X.shape[2] == self.state_dim # get the videos vids = [] for idx in traj_idxs: # vid = imageio.mimread(self.vid_paths_dict[task][idx]) # no need for transposing since I've already saved them # with correct ordering of dimensions vid = np.load(self.vid_paths_dict[task][idx]) # we will do this on the GPU # .astype(np.float32) # vid /= 255.0 vids.append(vid) # vids = np.array(vids) return { 'videos': vids, 'states': X, 'actions': U }
Example #10
Source File: vis.py From phyre with Apache License 2.0 | 5 votes |
def compose_gifs_compact(input_fpathes, output_fpath): """Create progressin for first and last frames over time.""" first_and_last_per_batch_id = [] for fname in input_fpathes: data = imageio.mimread(fname) data = np.concatenate([data[0], data[-1]], axis=0) first_and_last_per_batch_id.append(data) if first_and_last_per_batch_id: imageio.mimwrite(output_fpath, first_and_last_per_batch_id)
Example #11
Source File: vis.py From phyre with Apache License 2.0 | 5 votes |
def compose_gifs(input_fpathes, output_fpath): """Concatenate and sync all gifs.""" all_data = [] for fname in input_fpathes: all_data.append(imageio.mimread(fname)) max_timestamps = max(len(data) for data in all_data) def _pad(data): return data + [data[-1]] * (max_timestamps - len(data)) all_data = np.concatenate([_pad(data) for data in all_data], 1) imageio.mimwrite(output_fpath, all_data)
Example #12
Source File: image.py From catalyst with Apache License 2.0 | 5 votes |
def mimread( uri, clip_range: Tuple[int, int] = None, expand_dims: bool = True, rootpath: Union[str, pathlib.Path] = None, **kwargs, ) -> np.ndarray: """ Reads multiple images from the specified file. Args: uri (str, pathlib.Path, bytes, file): the resource to load the image from, e.g. a filename, ``pathlib.Path``, http address or file object, see ``imageio.mimread`` docs for more info clip_range (Tuple[int, int]): lower and upper interval edges, image values outside the interval are clipped to the interval edges expand_dims (bool): if True, append channel axis to grayscale images rootpath (Union[str, pathlib.Path]): path to the resource with image (allows to use relative path) rootpath (Union[str, pathlib.Path]): path to the resource with image (allows to use relative path) **kwargs: extra params for image read Returns: np.ndarray: image """ if rootpath is not None: uri = uri if uri.startswith(rootpath) else os.path.join(rootpath, uri) image = np.dstack(imageio.mimread(uri, **kwargs)) if clip_range is not None: image = np.clip(image, *clip_range) if expand_dims and len(image.shape) < 3: # grayscale image = np.expand_dims(image, -1) return image