Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
centered in an array of the specified shape before saving.
"""
rescale = min(float(w_1) / w_2 for w_1, w_2 in zip(shape, image.shape))
small_shape = (rescale * np.asarray(image.shape[:2])).astype(int)
small_image = transform.resize(image, small_shape)
if len(image.shape) == 3:
shape = shape + (image.shape[2],)
background_value = dtype_range[small_image.dtype.type][1]
thumb = background_value * np.ones(shape, dtype=small_image.dtype)
i = (shape[0] - small_shape[0]) // 2
j = (shape[1] - small_shape[1]) // 2
thumb[i:i+small_shape[0], j:j+small_shape[1]] = small_image
io.imsave(thumb_path, thumb)
model.fit(x=X,
y=Y,
batch_size=1,
epochs=1000)
# Test model
print(model.evaluate(X, Y, batch_size=1))
output = model.predict(X)
# Output colorizations
for i in range(len(output)):
cur = np.zeros((128, 128, 3))
cur[:,:,0] = Xtest[i][:,:,0]
cur[:,:,1:] = output[i]
imsave("colorizations/img_"+str(i)+".png", lab2rgb(cur))
imsave("colorizations/img_gray_"+str(i)+".png", rgb2gray(lab2rgb(cur)))
# To continue training from one of the checkpoints
if not args.checkpoint_name:
raise IOError('In test mode, a checkpoint is expected.')
saver.restore(sess, args.checkpoint_name)
# Test network
print 'generating network output'
for curr_test_image_name in test_image_names:
splits = curr_test_image_name.split('/')
splits = splits[len(splits)-1].split('.')
print curr_test_image_name
batch_A,batch_B = load_images_paired(list([curr_test_image_name]),
is_train = False, true_size = args.input_size, enlarge_size = args.enlarge_size)
fake_B = sess.run(model.generator_output(image_A),
feed_dict={image_A: batch_A.astype('float32'), image_B: batch_B.astype('float32'), keep_prob: 1-args.dropout_rate})
io.imsave(out_dir+splits[0]+'_test_output_fakeB.png',(fake_B[0]+1.0)/2.0)
io.imsave(out_dir+splits[0]+'_realB.png',(batch_B[0]+1.0)/2.0)
io.imsave(out_dir+splits[0]+'_realA.png',(batch_A[0]+1.0)/2.0)
img = original_colors(content_im_orig, img)
if args.style_color:
img = style_colors(content_im_orig, img)
img = np.asarray(img, dtype=np.uint8)
# Init result list
if not os.path.isdir(args.out_folder):
os.makedirs(args.out_folder)
print('Result will save to {} ...\n'.format(args.out_folder))
name = '{}_with_style(s)'.format(os.path.splitext(os.path.basename(args.content_image))[0])
for path in args.style_images:
name = '{}_{}'.format(name, os.path.splitext(os.path.basename(path))[0])
if args.prefix:
name = '{}_{}'.format(args.prefix, name)
imsave(os.path.join(args.out_folder, '{}.png'.format(name)), img)
img_features = None
if(featureRepresentation == 'image'):
img_features = img.flatten()
elif(featureRepresentation == 'pca'):
img_features = decomposition.PCA(n_components=8).fit_transform(img.flatten())
elif(featureRepresentation == 'glcm'):
img_features = Helper.get_textural_features(img, 1, True)
clf = get_model()
result = clf.predict(img_features.reshape(1,-1))
if(shouldSaveResult == True):
# Save image with result in filename
if os.path.exists("Results"):
shutil.rmtree("Results")
os.makedirs("Results")
io.imsave("Results/{}_{}.png".format(Helper.generate_random_id(8), result), img)
return result
elif(isinstance(img, list)):
if(featureRepresentation == 'glcm'):
sample_size = 16
else:
sample_size = 20*20
test_data = np.zeros((len(img), sample_size))
i = 0
for image in img:
if(featureRepresentation == 'image'):
test_data[i] = image.flatten()
elif(featureRepresentation == 'pca'):
test_data[i] = decomposition.PCA(n_components=8).fit_transform(image.flatten())
def SaveImage(_path, _buffer):
# with warnings.catch_warnings():
# warnings.simplefilter("ignore")
# ski.io.imsave(_path, _buffer)
ski.io.imsave(_path, _buffer)
def SaveFinalImage(self,currently_considered_image_path,current_image_loaded):
io.imsave(currently_considered_image_path,current_image_loaded)
Rotates image based on a specified amount of degrees
INPUT
file_path: file path to the folder containing images.
degrees_of_rotation: Integer, specifying degrees to rotate the
image. Set number from 1 to 360.
lst_imgs: list of image strings.
OUTPUT
Images rotated by the degrees of rotation specififed.
'''
for l in lst_imgs:
img = io.imread(file_path + str(l) + '.jpeg')
img = rotate(img, degrees_of_rotation)
io.imsave(file_path + str(l) + '_' + str(degrees_of_rotation) + '.jpeg', img)
out_k_m = out_k.view(-1,1,opt.kernel_size[0],opt.kernel_size[1])
# print(out_k_m)
out_y = nn.functional.conv2d(out_x, out_k_m, padding=0, bias=None)
total_loss = mse(out_y, y) + tv_loss(out_x) #+ tv_loss2(out_k_m)
total_loss.backward()
optimizer.step()
if (step+1) % opt.save_frequency == 0:
#print('Iteration %05d' %(step+1))
save_path = os.path.join(opt.save_path, '%s_x.png'%imgname)
out_x_np = torch_to_np(out_x)
out_x_np = out_x_np.squeeze()
out_x_np = out_x_np[padh//2:padh//2+img_size[1], padw//2:padw//2+img_size[2]]
imsave(save_path, out_x_np)
save_path = os.path.join(opt.save_path, '%s_k.png'%imgname)
out_k_np = torch_to_np(out_k_m)
out_k_np = out_k_np.squeeze()
out_k_np /= np.max(out_k_np)
imsave(save_path, out_k_np)
torch.save(net, os.path.join(opt.save_path, "%s_xnet.pth" % imgname))
torch.save(net_kernel, os.path.join(opt.save_path, "%s_knet.pth" % imgname))
ms_ = sess.run(ms, feed_dict=feed_dict)
for i, m in enumerate(ms_):
output_path = os.path.join(args.output, fname+"_ms_{}.png".format(i))
skimage.io.imsave(output_path, m)
if len(fr) > 0:
fr_ = sess.run(fr, feed_dict=feed_dict)
for i, m in enumerate(fr_):
output_path = os.path.join(args.output, fname+"_fr_{}.png".format(i))
skimage.io.imsave(output_path, m)
if len(guide) > 0:
guide_ = sess.run(guide, feed_dict=feed_dict)
for i, g in enumerate(guide_):
output_path = os.path.join(args.output, fname+"_guide_{}.png".format(i))
skimage.io.imsave(output_path, g)