本文整理汇总了Python中imageio.imwrite方法的典型用法代码示例。如果您正苦于以下问题:Python imageio.imwrite方法的具体用法?Python imageio.imwrite怎么用?Python imageio.imwrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类imageio
的用法示例。
在下文中一共展示了imageio.imwrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_image
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
""" save image """
data = data.asnumpy().transpose((0, 2, 3, 1))
datanp = np.clip(
(data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
x_dim = min(8, batch_size)
y_dim = int(math.ceil(float(batch_size) / x_dim))
height, width = int(image_size + padding), int(image_size + padding)
grid = np.zeros((height * y_dim + 1 + padding // 2, width *
x_dim + 1 + padding // 2, 3), dtype=np.uint8)
k = 0
for y in range(y_dim):
for x in range(x_dim):
if k >= batch_size:
break
start_y = y * height + 1 + padding // 2
end_y = start_y + height - padding
start_x = x * width + 1 + padding // 2
end_x = start_x + width - padding
np.copyto(grid[start_y:end_y, start_x:end_x, :], datanp[k])
k += 1
imageio.imwrite(
'{}/fake_samples_epoch_{}.png'.format(output_dir, epoch), grid)
示例2: begin_background
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def begin_background(self):
self.queue = Queue()
def bg_target(queue):
while True:
if not queue.empty():
filename, tensor = queue.get()
if filename is None: break
imageio.imwrite(filename, tensor.numpy())
self.process = [
Process(target=bg_target, args=(self.queue,)) \
for _ in range(self.n_processes)
]
for p in self.process: p.start()
示例3: _generate_samples
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def _generate_samples(self, samples_path, cover, epoch):
cover = cover.to(self.device)
generated, payload, decoded = self._encode_decode(cover)
samples = generated.size(0)
for sample in range(samples):
cover_path = os.path.join(samples_path, '{}.cover.png'.format(sample))
sample_name = '{}.generated-{:2d}.png'.format(sample, epoch)
sample_path = os.path.join(samples_path, sample_name)
image = (cover[sample].permute(1, 2, 0).detach().cpu().numpy() + 1.0) / 2.0
imageio.imwrite(cover_path, (255.0 * image).astype('uint8'))
sampled = generated[sample].clamp(-1.0, 1.0).permute(1, 2, 0)
sampled = sampled.detach().cpu().numpy() + 1.0
image = sampled / 2.0
imageio.imwrite(sample_path, (255.0 * image).astype('uint8'))
示例4: encode
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def encode(self, cover, output, text):
"""Encode an image.
Args:
cover (str): Path to the image to be used as cover.
output (str): Path where the generated image will be saved.
text (str): Message to hide inside the image.
"""
cover = imread(cover, pilmode='RGB') / 127.5 - 1.0
cover = torch.FloatTensor(cover).permute(2, 1, 0).unsqueeze(0)
cover_size = cover.size()
# _, _, height, width = cover.size()
payload = self._make_payload(cover_size[3], cover_size[2], self.data_depth, text)
cover = cover.to(self.device)
payload = payload.to(self.device)
generated = self.encoder(cover, payload)[0].clamp(-1.0, 1.0)
generated = (generated.permute(2, 1, 0).detach().cpu().numpy() + 1.0) * 127.5
imwrite(output, generated.astype('uint8'))
if self.verbose:
print('Encoding completed.')
示例5: predict_to_directory
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def predict_to_directory(self, spath, tpath,fold=0, stage=0, limit=-1, batchSize=32,binaryArray=False,ttflips=False):
generic.ensure(tpath)
with tqdm.tqdm(total=len(generic.dir_list(spath)), unit="files", desc="segmentation of images from " + str(spath) + " to " + str(tpath)) as pbar:
for v in self.predict_on_directory(spath, fold=fold, stage=stage, limit=limit, batch_size=batchSize, ttflips=ttflips):
b:imgaug.Batch=v;
for i in range(len(b.data)):
id=b.data[i];
orig=b.images[i];
map=b.segmentation_maps_aug[i]
scaledMap=imgaug.augmenters.Scale({"height": orig.shape[0], "width": orig.shape[1]}).augment_segmentation_maps([map])
if isinstance(tpath, datasets.ConstrainedDirectory):
tp=tpath.path
else:
tp=tpath
if binaryArray:
np.save(os.path.join(tp, id[0:id.index('.')]),scaledMap[0].arr);
else: imageio.imwrite(os.path.join(tp, id[0:id.index('.')] + ".png"), (scaledMap[0].arr*255).astype(np.uint8))
pbar.update(batchSize)
示例6: save_data_list
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def save_data_list(input_dir, filepathes):
"""
Read, resize and save images listed in filepathes.
"""
cnt = 0
bad_img = list()
for filepath in filepathes:
image_path = os.path.join(input_dir, filepath)
img, path = common.misc.get_image(image_path, LOAD_SIZE, is_crop=False)
if img is None:
bad_img.append(path)
np.savetxt('../bad_img.txt', bad_img, fmt='%s', comments=None)
continue
img = img.astype('uint8')
output_file = os.path.join(OUTPUT_DIR, filepath)
if not os.path.exists(os.path.dirname(output_file)):
os.mkdir(os.path.dirname(output_file))
imageio.imwrite(output_file, img)
cnt += 1
if cnt % 1000 == 0:
print('Resizing %d / %d' % (cnt, len(filepathes)))
示例7: test_fastai_image_input
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def test_fastai_image_input(capsys, tmpdir):
class ImageInputModelForFastai(bentoml.BentoService):
@bentoml.api(input=FastaiImageInput())
def predict(self, image):
return list(image.shape)
ms = ImageInputModelForFastai()
import imageio
import numpy as np
img_file = tmpdir.join("img.png")
imageio.imwrite(str(img_file), np.zeros((10, 10)))
api = ms.get_service_apis()[0]
test_args = ["--input={}".format(img_file)]
api.handle_cli(test_args)
out, _ = capsys.readouterr()
assert out.strip() == '[3, 10, 10]'
示例8: _save_image
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def _save_image(image, filename, return_img=None):
"""Save a NumPy image array.
This is an internal helper.
"""
if not image.size:
raise ValueError('Empty image. Have you run plot() first?')
# write screenshot to file
supported_formats = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"]
if isinstance(filename, str):
if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
filename = os.path.join(pyvista.FIGURE_PATH, filename)
if not any([filename.lower().endswith(ext) for ext in supported_formats]):
filename += ".png"
filename = os.path.abspath(os.path.expanduser(filename))
w = imageio.imwrite(filename, image)
if not return_img:
return w
return image
示例9: obama_demo
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def obama_demo():
wd = 'obama_res@dense_py'
if not osp.exists(wd):
os.mkdir(wd)
app = RenderPipeline(**cfg)
img_fps = sorted(glob('obama/*.jpg'))
triangles = sio.loadmat('tri_refine.mat')['tri'] # mx3
triangles = _to_ctype(triangles).astype(np.int32) # for type compatible
for img_fp in img_fps[:]:
vertices = sio.loadmat(img_fp.replace('.jpg', '_0.mat'))['vertex'].T # mx3
img = imageio.imread(img_fp).astype(np.float32) / 255.
# end = time.clock()
img_render = app(vertices, triangles, img)
# print('Elapse: {:.1f}ms'.format((time.clock() - end) * 1000))
img_wfp = osp.join(wd, osp.basename(img_fp))
imageio.imwrite(img_wfp, img_render)
print('Writing to {}'.format(img_wfp))
示例10: test_debug
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def test_debug(self):
image = imageio.imread("./temp/dump.png")
grid_n = 6
img_size = image.shape[1] // grid_n
img_ch = image.shape[-1]
images = np.vsplit(image, grid_n)
images = [np.hsplit(i, grid_n) for i in images]
images = np.reshape(np.array(images), [grid_n*grid_n, img_size, img_size, img_ch])
with tf.Graph().as_default():
with tf.Session() as sess:
v_images_placeholder = tf.placeholder(dtype=tf.float32)
v_images = tf.contrib.gan.eval.preprocess_image(v_images_placeholder)
v_logits = tf.contrib.gan.eval.run_inception(v_images)
v_score = tf.contrib.gan.eval.classifier_score_from_logits(v_logits)
score, logits = sess.run([v_score, v_logits], feed_dict={v_images_placeholder:images})
imageio.imwrite("./temp/inception_logits.png", logits)
示例11: plot_images
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def plot_images(args, x_sample, dir, file_name, size_x=10, size_y=10):
batch, channels, height, width = x_sample.shape
print(x_sample.shape)
mosaic = np.zeros((height * size_y, width * size_x, channels))
for j in range(size_y):
for i in range(size_x):
idx = j * size_x + i
image = x_sample[idx]
mosaic[j*height:(j+1)*height, i*height:(i+1)*height] = \
image.transpose(1, 2, 0)
# Remove channel for BW images
mosaic = mosaic.squeeze()
imageio.imwrite(dir + file_name + '.png', mosaic)
示例12: imsave
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def imsave(path, img):
# type: (str, (Union[np.ndarray,list])) -> None
"""
Automatically clip the image represented in a numpy array to 0~255 and save the image.
:param path: Path to save the image.
:param img: Image represented in numpy array with a legal format for scipy.misc.imsave
:return: None
"""
if isinstance(img, list):
img = np.array(img)
if img.shape[-1] > 3 and len(img.shape) >= 3:
# Convert the image into one channel by summing all channels together
img = np.sum(img, axis=-1, keepdims=True)
img = np.clip(img, 0, 255).astype(np.uint8)
if len(img.shape) == 3 and img.shape[-1] == 1:
img = np.squeeze(img, -1)
imageio.imwrite(path, img)
示例13: main
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, help="environment name")
parser.add_argument('--seed', type=int, default=time.time())
parser.add_argument('--out', type=str, help="path to save figure")
args = parser.parse_args()
img = get_img(args.env, args.seed)
imageio.imwrite(args.out, img)
示例14: save_im
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def save_im(path, im, jpg_quality=95):
"""Saves an image to a file.
:param path: Path to the output image file.
:param im: ndarray with the image to save.
:param jpg_quality: Quality of the saved image (applies only to JPEG).
"""
ext = os.path.splitext(path)[1][1:]
if ext.lower() in ['jpg', 'jpeg']:
imageio.imwrite(path, im, quality=jpg_quality)
else:
imageio.imwrite(path, im)
示例15: save_depth
# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imwrite [as 别名]
def save_depth(path, im):
"""Saves a depth image (16-bit) to a PNG file.
:param path: Path to the output depth image file.
:param im: ndarray with the depth image to save.
"""
if path.split('.')[-1].lower() != 'png':
raise ValueError('Only PNG format is currently supported.')
im_uint16 = np.round(im).astype(np.uint16)
# PyPNG library can save 16-bit PNG and is faster than imageio.imwrite().
w_depth = png.Writer(im.shape[1], im.shape[0], greyscale=True, bitdepth=16)
with open(path, 'wb') as f:
w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1])))