本文整理汇总了Python中utils.save_image方法的典型用法代码示例。如果您正苦于以下问题:Python utils.save_image方法的具体用法?Python utils.save_image怎么用?Python utils.save_image使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类utils
的用法示例。
在下文中一共展示了utils.save_image方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_camera
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def start_camera(camera, folder, interval, until=None):
"""
Start taking pictures every interval.
If until is specified, it will take pictures
until that time is reached (24h format).
Needs to be of the following format: HH:MM
"""
utils.clear_directory(folder)
number = 0
while True:
_, image = camera.read()
now = datetime.datetime.now()
number += 1
print 'Taking picture number %d at %s' % (number, now.isoformat())
utils.save_image(image, folder, now)
if utils.time_over(until, now):
break
time.sleep(interval)
del(camera)
示例2: main
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def main():
parser = build_parser()
options = parser.parse_args()
check_opts(options)
network = options.network_path
if not os.path.isdir(network):
parser.error("Network %s does not exist." % network)
content_image = utils.load_image(options.content)
reshaped_content_height = (content_image.shape[0] - content_image.shape[0] % 4)
reshaped_content_width = (content_image.shape[1] - content_image.shape[1] % 4)
reshaped_content_image = content_image[:reshaped_content_height, :reshaped_content_width, :]
reshaped_content_image = np.ndarray.reshape(reshaped_content_image, (1,) + reshaped_content_image.shape)
prediction = ffwd(reshaped_content_image, network)
utils.save_image(prediction, options.output_path)
示例3: write_disk_grid
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def write_disk_grid(global_step, summary_freq, log_dir, input_images,
output_images, pred_images, pred_masks):
"""Function called by TF to save the prediction periodically."""
def write_grid(grid, global_step):
"""Native python function to call for writing images to files."""
if global_step % summary_freq == 0:
img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
utils.save_image(grid, img_path)
return 0
grid = _build_image_grid(input_images, output_images, pred_images, pred_masks)
slim.summaries.add_image_summary(
tf.expand_dims(grid, axis=0), name='grid_vis')
save_op = tf.py_func(write_grid, [grid, global_step], [tf.int64],
'write_grid')[0]
return save_op
示例4: stylize
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def stylize(args):
device = torch.device("cuda" if args.cuda else "cpu")
content_image = utils.load_image(args.content_image, scale=args.content_scale)
content_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: x.mul(255))
])
content_image = content_transform(content_image)
content_image = content_image.unsqueeze(0).to(device)
with torch.no_grad():
style_model = TransformerNet(style_num=args.style_num)
state_dict = torch.load(args.model)
style_model.load_state_dict(state_dict)
style_model.to(device)
output = style_model(content_image, style_id = [args.style_id]).cpu()
utils.save_image('output/'+args.output_image+'_style'+str(args.style_id)+'.jpg', output[0])
示例5: motion_detection
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def motion_detection(camera, folder, until):
"""
Uses 3 frames to look for motion, can't remember where
I found it but it gives better result than my first try
with comparing 2 frames.
"""
utils.clear_directory(folder)
# Need to get 2 images to start with
previous_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
current_image = cv2.cvtColor(camera.read()[1], cv2.cv.CV_RGB2GRAY)
purple = (140, 25, 71)
while True:
now = datetime.datetime.now()
_, image = camera.read()
gray_image = cv2.cvtColor(image, cv2.cv.CV_RGB2GRAY)
difference1 = cv2.absdiff(previous_image, gray_image)
difference2 = cv2.absdiff(current_image, gray_image)
result = cv2.bitwise_and(difference1, difference2)
# Basic threshold, turn the bitwise_and into a black or white (haha)
# result, white (255) being a motion
_, result = cv2.threshold(result, 40, 255, cv2.THRESH_BINARY)
# Let's show a square around the detected motion in the original pic
low_point, high_point = utils.find_motion_boundaries(result.tolist())
if low_point is not None and high_point is not None:
cv2.rectangle(image, low_point, high_point, purple, 3)
print 'Motion detected ! Taking picture'
utils.save_image(image, folder, now)
previous_image = current_image
current_image = gray_image
if utils.time_over(until, now):
break
del(camera)
示例6: generate
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def generate():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g', type=int, default=-1)
parser.add_argument('--gen', type=str, default=None)
parser.add_argument('--depth', '-d', type=int, default=0)
parser.add_argument('--out', '-o', type=str, default='img/')
parser.add_argument('--num', '-n', type=int, default=10)
args = parser.parse_args()
gen = network.Generator(depth=args.depth)
print('loading generator model from ' + args.gen)
serializers.load_npz(args.gen, gen)
if args.gpu >= 0:
cuda.get_device_from_id(0).use()
gen.to_gpu()
xp = gen.xp
z1 = gen.z(1)
z2 = gen.z(1)
for i in range(args.num):
print(i)
p = i / (args.num-1)
z = z1 * p + z2 * (1 - p)
x = gen(z, alpha=1.0)
x = chainer.cuda.to_cpu(x.data)
img = x[0].copy()
filename = os.path.join(args.out, 'gen_%04d.png'%i)
utils.save_image(img, filename)
示例7: write_disk_grid
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def write_disk_grid(self,
global_step,
log_dir,
input_images,
gt_projs,
pred_projs,
input_voxels=None,
output_voxels=None):
"""Function called by TF to save the prediction periodically."""
summary_freq = self._params.save_every
def write_grid(input_images, gt_projs, pred_projs, global_step,
input_voxels, output_voxels):
"""Native python function to call for writing images to files."""
grid = _build_image_grid(
input_images,
gt_projs,
pred_projs,
input_voxels=input_voxels,
output_voxels=output_voxels)
if global_step % summary_freq == 0:
img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
utils.save_image(grid, img_path)
return grid
save_op = tf.py_func(write_grid, [
input_images, gt_projs, pred_projs, global_step, input_voxels,
output_voxels
], [tf.uint8], 'write_grid')[0]
slim.summaries.add_image_summary(
tf.expand_dims(save_op, axis=0), name='grid_vis')
return save_op
示例8: write_disk_grid
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def write_disk_grid(self,
global_step,
log_dir,
input_images,
gt_projs,
pred_projs,
pred_voxels=None):
"""Function called by TF to save the prediction periodically."""
summary_freq = self._params.save_every
def write_grid(input_images, gt_projs, pred_projs, pred_voxels,
global_step):
"""Native python function to call for writing images to files."""
grid = _build_image_grid(input_images, gt_projs, pred_projs, pred_voxels)
if global_step % summary_freq == 0:
img_path = os.path.join(log_dir, '%s.jpg' % str(global_step))
utils.save_image(grid, img_path)
with open(
os.path.join(log_dir, 'pred_voxels_%s' % str(global_step)),
'w') as fout:
np.save(fout, pred_voxels)
with open(
os.path.join(log_dir, 'input_images_%s' % str(global_step)),
'w') as fout:
np.save(fout, input_images)
return grid
py_func_args = [
input_images, gt_projs, pred_projs, pred_voxels, global_step
]
save_grid_op = tf.py_func(write_grid, py_func_args, [tf.uint8],
'wrtie_grid')[0]
slim.summaries.add_image_summary(
tf.expand_dims(save_grid_op, axis=0), name='grid_vis')
return save_grid_op
示例9: main
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def main():
# parse arguments
args = parse_args()
if args is None:
exit()
# load content image
content_image = utils.load_image(args.content, max_size=args.max_size)
# open session
soft_config = tf.ConfigProto(allow_soft_placement=True)
soft_config.gpu_options.allow_growth = True # to deal with large image
sess = tf.Session(config=soft_config)
# build the graph
transformer = style_transfer_tester.StyleTransferTester(session=sess,
model_path=args.style_model,
content_image=content_image,
)
# execute the graph
start_time = time.time()
output_image = transformer.test()
end_time = time.time()
# save result
utils.save_image(output_image, args.output)
# report execution time
shape = content_image.shape #(batch, width, height, channel)
print('Execution time for a %d x %d image : %f msec' % (shape[0], shape[1], 1000.*float(end_time - start_time)/60))
示例10: stylize
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def stylize(args):
device = torch.device("cuda" if args.cuda else "cpu")
content_image = utils.load_image(args.content_image, scale=args.content_scale)
content_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: x.mul(255))
])
content_image = content_transform(content_image)
content_image = content_image.unsqueeze(0).to(device)
if args.model.endswith(".onnx"):
output = stylize_onnx_caffe2(content_image, args)
else:
with torch.no_grad():
style_model = TransformerNet()
state_dict = torch.load(args.model)
# remove saved deprecated running_* keys in InstanceNorm from the checkpoint
for k in list(state_dict.keys()):
if re.search(r'in\d+\.running_(mean|var)$', k):
del state_dict[k]
style_model.load_state_dict(state_dict)
style_model.to(device)
if args.export_onnx:
assert args.export_onnx.endswith(".onnx"), "Export model file should end with .onnx"
output = torch.onnx._export(style_model, content_image, args.export_onnx).cpu()
else:
output = style_model(content_image).cpu()
utils.save_image(args.output_image, output[0])
示例11: save_images
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def save_images(img_dir, img_idx, file_suffix, inp_dict):
his_imgs = utils.flatten_img_seq(inp_dict['his_imgs'])
fut_imgs = utils.flatten_img_seq(inp_dict['fut_imgs'])
#
if file_suffix == 'gt':
utils.save_image(his_imgs, os.path.join(img_dir, '%02d_%s_his_poses.png' % (img_idx, file_suffix)))
utils.save_image(fut_imgs, os.path.join(img_dir, '%02d_%s_fut_poses.png' % (img_idx, file_suffix)))
示例12: save_images
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def save_images(img_dir, img_idx, file_suffix, inp_dict):
A_imgs = utils.flatten_img_seq(inp_dict['A_imgs'])
B_imgs = utils.flatten_img_seq(inp_dict['B_imgs'])
C_imgs = utils.flatten_img_seq(inp_dict['C_imgs'])
predD_imgs = utils.flatten_img_seq(inp_dict['predD_imgs'])
sub_name = '%02d_%s' % (img_idx, file_suffix)
utils.save_image(A_imgs, os.path.join(img_dir, '%s_A.png' % sub_name))
utils.save_image(B_imgs, os.path.join(img_dir, '%s_B.png' % sub_name))
utils.save_image(C_imgs, os.path.join(img_dir, '%s_C.png' % sub_name))
utils.save_image(predD_imgs, os.path.join(img_dir, '%s_predD.png' % sub_name))
示例13: stylize
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def stylize(args):
device = torch.device("cuda" if args.cuda else "cpu")
content_transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda(lambda x: x.mul(255))])
content_image = utils.load_image(args.content_image, scale=args.content_scale)
content_image = content_transform(content_image)
content_image = content_image.unsqueeze(0).to(device)
with torch.no_grad():
style_model = torch.load(args.model)
style_model.to(device)
output = style_model(content_image).cpu()
utils.save_image(args.output_image, output[0])
示例14: loop_body_patch
# 需要导入模块: import utils [as 别名]
# 或者: from utils import save_image [as 别名]
def loop_body_patch(it, ckpt_path, depth_in, depth_ref, color, mask, config):
"""
:param depth_ref: unused yet. offline quantitative evaluation of depth_dt.
"""
print(time.ctime())
print("Load checkpoint: {}".format(ckpt_path))
h, w = depth_in.shape[:2]
low_thres = config.low_thres
up_thres = config.up_thres
thres_range = (up_thres - low_thres) / 2.0
params = build_model(h, w, config)
# ckpt_step = ckpt_path.split("/")[-1]
sess = tf.Session()
load_from_checkpoint(sess, ckpt_path)
depth_dn_im, depth_dt_im = sess.run([params["depth_dn"], params["depth_dt"]],
feed_dict={params["depth_in"]: depth_in.reshape(1, h, w, 1),
params["color"]: color.reshape(1, h, w, 1),
params["is_training"]: False})
depth_dn_im = (((depth_dn_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)
depth_dt_im = (((depth_dt_im + 1.0) * thres_range + low_thres) * mask).astype(np.uint16)
utils.save_image(depth_dn_im, config.sample_dir, "frame_{}_dn.png".format(it))
utils.save_image(depth_dt_im, config.sample_dir, "frame_{}_dt.png".format(it))
tf.reset_default_graph()
print("saving img {}.".format(it))