本文整理匯總了Python中imageio.mimread方法的典型用法代碼示例。如果您正苦於以下問題:Python imageio.mimread方法的具體用法?Python imageio.mimread怎麽用?Python imageio.mimread使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類imageio
的用法示例。
在下文中一共展示了imageio.mimread方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testreadavi
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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)
示例2: _setup
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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])
示例3: check_shape
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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)
示例4: test_Percept_save
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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)
示例5: generate_test_demos
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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
示例6: load_demo
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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
示例7: test_tiff_multipage_rw
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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
示例8: _run_benchmark_suite
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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,
]
示例9: __getitem__
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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
}
示例10: compose_gifs_compact
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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)
示例11: compose_gifs
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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)
示例12: mimread
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimread [as 別名]
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