Python scipy.misc 模块,imsave() 实例源码
我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用scipy.misc.imsave()。
def validate_model(self, val_iter, epoch, step):
labels, codes, images = next(val_iter)
fake_imgs, real_imgs, d_loss, g_loss, l1_loss = self.generate_fake_samples(images, labels)
print("Sample: d_loss: %.5f,g_loss: %.5f,l1_loss: %.5f" % (d_loss, l1_loss))
merged_fake_images = merge(scale_back(fake_imgs), [self.batch_size, 1])
merged_real_images = merge(scale_back(real_imgs), 1])
merged_pair = np.concatenate([merged_real_images, merged_fake_images], axis=1)
model_id, _ = self.get_model_id_and_dir()
model_sample_dir = os.path.join(self.sample_dir, model_id)
if not os.path.exists(model_sample_dir):
os.makedirs(model_sample_dir)
sample_img_path = os.path.join(model_sample_dir, "sample_%02d_%04d.png" % (epoch, step))
misc.imsave(sample_img_path, merged_pair)
def generate(p, ics, gcs, *args):
from scipy import misc
import subprocess
import datetime
inits = p.generate(np.array(ics),*args)
goals = p.generate(np.array(gcs),*args)
for noise_fn,output_dir in zip(noise_fns,output_dirs):
inits = noise_fn(inits)
goals = noise_fn(goals)
for i,init in enumerate(inits):
for j,goal in enumerate(goals):
d = "{}/{}/{:03d}-{:03d}-{:03d}".format(output_dir,p.__name__,steps,i,j)
try:
subprocess.call(["mv",d,d+"_old_"+datetime.datetime.today().isoformat()])
except:
pass
os.makedirs(d)
print(d)
misc.imsave(os.path.join(d,"init.png"),init)
misc.imsave(os.path.join(d,"goal.png"),goal)
################################################################
def resize_images(prms):
seqNum = range(11)
rawStr = ['rawLeftImFile', 'rawRightImFile']
imstr = ['leftImFile', 'rightImFile']
num = ku.get_num_images()
for raw, new in zip(rawStr, imstr):
for seq in seqNum:
N = num[seq]
print seq, N, raw, new
rawNames = [prms['paths'][raw] % (seq,i) for i in range(N)]
newNames = [prms['paths'][new] % (seq,i) for i in range(N)]
dirName = os.path.dirname(newNames[0])
if not os.path.exists(dirName):
os.makedirs(dirName)
for rawIm, newIm in zip(rawNames, newNames):
im = scm.imread(rawIm)
im = scm.imresize(im, [256, 256])
scm.imsave(newIm, im)
##
# Save images as jpgs.
def save_as_jpg(prms):
seqNum = range(11)
rawStr = ['rawLeftImFile', newNames):
im = scm.imread(rawIm)
scm.imsave(newIm, im)
##
# Get the names of images
def preprocess(image_dir, new_image_dir, preprocess_fn):
image_paths = []
labels = []
if os.path.isdir(new_image_dir):
rmtree(new_image_dir)
os.makedirs(new_image_dir)
classes = os.listdir(image_dir)
for clas in classes:
class_dir = os.path.join(image_dir, str(clas))
new_class_dir = os.path.join(new_image_dir, str(clas))
os.makedirs(new_class_dir)
for image_name in os.listdir(class_dir):
image = misc.imread(os.path.join(class_dir, image_name))
image = preprocess_fn(image)
misc.imsave(os.path.join(new_class_dir, image_name), image)
def main(args):
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = args.gpu_fraction)
with tf.Session(config=tf.ConfigProto(gpu_options = gpu_options)) as sess:
saver = tf.train.import_Meta_graph('./Meta_graph/my-model.Meta')
saver.restore(sess,tf.train.latest_checkpoint('./model'))
image_batch = tf.get_collection('image_batch')[0]
GT_trimap = tf.get_collection('GT_trimap')[0]
pred_mattes = tf.get_collection('pred_mattes')[0]
rgb = misc.imread(args.rgb)
alpha = misc.imread(args.alpha,'L')
trimap = generate_trimap(np.expand_dims(np.copy(alpha),2),np.expand_dims(alpha,2))[:,:,0]
origin_shape = alpha.shape
rgb = np.expand_dims(misc.imresize(rgb.astype(np.uint8),[320,320,3]).astype(np.float32)-g_mean,0)
trimap = np.expand_dims(np.expand_dims(misc.imresize(trimap.astype(np.uint8),320],interp = 'nearest').astype(np.float32),0)
Feed_dict = {image_batch:rgb,GT_trimap:trimap}
pred_alpha = sess.run(pred_mattes,Feed_dict = Feed_dict)
final_alpha = misc.imresize(np.squeeze(pred_alpha),origin_shape)
# misc.imshow(final_alpha)
misc.imsave('./alpha.png',final_alpha)
def test_15(self):
bpth = tempfile.mkdtemp()
os.mkdir(os.path.join(bpth, 'a'))
ipth = os.path.join(bpth, 'a', 'b.png')
img = np.ones((32,32))
misc.imsave(ipth, img)
ei = util.ExampleImages(pth=bpth)
im = ei.images()
assert(len(im) > 0)
gp = ei.groups()
assert(len(gp) > 0)
img = ei.image('b.png', group='a')
assert(img.shape == (32,32))
im = ei.image('b.png', group='a', scaled=True, dtype=np.float32,
zoom=0.5)
os.remove(ipth)
os.rmdir(os.path.join(bpth, 'a'))
os.rmdir(bpth)
def save(self, data):
"""Takes in an array of CYX pixel values and writes them to a png
:param data: a CYX or YX array with C being the rgb channels for each pixel value
"""
# check for rgb,rgba,or r
if len(data.shape) == 3:
assert data.shape[0] in [4, 3, 2, 1]
# if three dimensions,transpose to YXC (imsave() needs it in these axes)
data = np.transpose(data, (1, 0))
# if there's only one channel,repeat across the next two channels
if data.shape[2] == 1:
data = np.repeat(data, repeats=3, axis=2)
elif data.shape[2] == 2:
data = np.pad(data, ((0, 0), (0, 1)), 'constant')
elif len(data.shape) != 2:
raise ValueError("Data was not of dimensions CYX or YX")
imsave(self.file_path, data, format="png")
def test_recognize(args):
imdetect = args.detect
im1 = args.im1
im2 = args.im2
payload = {'img':file2base64(imdetect)}
import numpy as np
imarr = np.array(misc.imread(imdetect))
r = requests.get("http://face.icybee.cn/face/face_detect", data=payload)
print(json.loads(r.text)['Boxes'][0])
Box = json.loads(r.text)['Boxes'][0]
Box = [int(i) for i in Box]
misc.imsave('sample.jpg',imarr[Box[1]:Box[3],Box[0]:Box[2],:],)
payload = {
'img1':file2base64(im1),
'img2':file2base64(im2)
}
r = requests.get("http://face.icybee.cn/face/face_recognize", data=payload)
print(r.text)
#print(json.loads(r.text)['dist'])
def mirror_pic(output_data_path, _dir, pic, img):
fname, fextension = os.path.splitext(pic)
mirror_x_img = img[:, ::-1, :]
mirror_x_img_gray = rgb2gray(mirror_x_img)
mirror_y_img = img[::-1, :, :]
mirror_y_img_gray = rgb2gray(mirror_y_img)
mirror_xy_img = img[::-1, :]
mirror_xy_img_gray = rgb2gray(mirror_xy_img)
misc.imsave(os.path.join(output_data_path, (fname + '_mirror_x' + fextension)), mirror_x_img_gray)
os.chmod(os.path.join(output_data_path, stat.S_IWRITE)
misc.imsave(os.path.join(output_data_path, (fname + '_mirror_y' + fextension)), mirror_y_img_gray)
os.chmod(os.path.join(output_data_path, (fname + '_mirror_xy' + fextension)), mirror_xy_img_gray)
os.chmod(os.path.join(output_data_path, stat.S_IWRITE)
return mirror_x_img, mirror_y_img, mirror_xy_img
def process_mot(path):
'''
1920 x 1080 -> 384 x 216
640 x 480 -> 320 x 240
'''
images = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath, filename)
img = misc.imread(full_path,mode='RGB')
if img.shape == LARGE_IMAGE_SIZE:
img = misc.imresize(img, size=LARGE_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
elif img.shape == MEDIUM_IMAGE_SIZE:
img = misc.imresize(img, size=MEDIUM_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
else:
print("Unexpected shape " + str(img.shape))
continue
output_filename = os.path.join(dirpath, filename[:-4] + "_ds.jpg")
misc.imsave(output_filename, img)
images.append(output_filename)
return images
def process_vot(path, min_height, min_width):
images = []
for dirpath, filenames in os.walk(path):
img_shape = None
pad_height = 0
pad_width = 0
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath,mode='RGB')
img_shape = img.shape
ratio = min(float(min_width)/img.shape[1], float(min_height)/img.shape[0])
img = misc.imresize(img, size=ratio)
img, pad_height, pad_width = pad_image(img, (min_height, min_width))
output_filename = os.path.join(dirpath, img)
images.append(output_filename)
if img_shape:
gt_path = os.path.join(dirpath, "groundtruth.txt")
preprocess_label(gt_path, ratio, img_shape, min_width, pad_width)
return images
def main():
#ids=[14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
ids=range(1,41)
rate=2.0/3
for id in ids:
gtfn=os.path.join(path,'P%d/V2Rct.nii.gz'%id)
# outfn=os.path.join(path,'P%d/V2Rct_all.nii.gz'%id)
gtOrg=sitk.ReadImage(gtfn)
gtMat=sitk.GetArrayFromImage(gtOrg)
print 'mat shape,', gtMat.shape
for s in range(1,gtMat.shape[0]):
sliceMat=gtMat[s-1,:]
sliceMatScale = nd.interpolation.zoom(sliceMat, zoom=rate)
scmi.imsave('p%d_'%id+'s%d.png'%s, sliceMat)
#gtMat=np.transpose(gtMat,(2,1,0))
# gtVol=sitk.GetimageFromArray(gtMat)
# sitk.WriteImage(gtVol,outfn)
#
# prefn='preSub%d_as32_v12.nii'%id
# preOrg=sitk.ReadImage(prefn)
# preMat=sitk.GetArrayFromImage(preOrg)
# preMat=np.transpose(preMat,0))
# preVol=sitk.GetimageFromArra(preMat)
# sitk.WriteImage(preVol,prefn)
def resize_to_optimal(infile, scale_ratio, rect, outfile):
image_array = imread(infile, mode='RGB')
im_shape = image_array.shape
h, w, _ = im_shape
width = float(rect.right()-rect.left())
scale_amount = (optimal_extent * scale_ratio) / width
new_w = int(scale_amount * w)
new_h = int(scale_amount * h)
new_w = new_w - (new_w % 4)
new_h = new_h - (new_h % 4)
print("optimal resize of width {} and ratio {} went from {},{} to {},{}".format(width, h, new_w, new_h))
new_shape = (new_h, new_w)
image_array_resized = imresize(image_array, new_shape)
imsave(outfile, image_array_resized)
return new_shape
def visualize(code, filename, filename_r, filename_all):
gen.eval()
generated_by_riter = [[] for _ in range(1+opt.r_iterations)]
for i in xrange((code.size(0) - 1) // opt.batch_size + 1):
batch_size = min(opt.batch_size, code.size(0) - i * opt.batch_size)
batch_code = Variable(code[i * opt.batch_size : i * opt.batch_size + batch_size])
for r_iter in xrange(1+opt.r_iterations):
imgs, _ = gen(batch_code, n_execute_lis_layers=r_iter)
if opt.output_scale:
imgs = imgs * 2 - 1
imgs_np = (imgs.data.cpu().numpy()*255).astype(np.uint8).transpose((0, 1))
generated_by_riter[r_iter].extend(imgs_np)
generated_all = []
for i in xrange(len(generated_by_riter[0])):
block = [imgs[i] for imgs in generated_by_riter]
generated_all.append(np.hstack(block))
misc.imsave(filename, util.draw_grid(generated_by_riter[0], cols=opt.vis_col))
for r_iter in xrange(1, 1+opt.r_iterations):
misc.imsave(filename_r.format(r_iter-1), util.draw_grid(generated_by_riter[r_iter], cols=opt.vis_col))
misc.imsave(filename_all, util.draw_grid(generated_all, cols=opt.vis_col))
gen.train()
def generate(sample_image):
start_time = time.time()
g = ModelGraph()
with tf.Session() as sess:
# We need to initialize variables in this case because the Variable `generator/x` will not restored.
tf.sg_init(sess)
vars = [v for v in tf.global_variables() if "generator" not in v.name]
saver = tf.train.Saver(vars)
saver.restore(sess, tf.train.latest_checkpoint('asset/train/ckpt'))
i = 0
while True:
mse, _ = sess.run([g.mse, g.train_gen], {g.y: transform_image(sample_image)}) # (16,28)
if time.time() - start_time > 60: # Save every 60 seconds
gen_image = sess.run(g.x)
gen_image = np.squeeze(gen_image)
misc.imsave('gen_images/%s/gen_%.2f.jpg' % (label, mse), gen_image)
start_time = time.time()
i += 1
if i == 60: break # Finish after 1 hour
def process_image(im_fp, dset_part):
bn = path.basename(im_fp)
dn = path.dirname(im_fp)
img_idx = int(bn[:bn.find("_")])
body_fp = path.join(dn, bn + '_body.pkl')
im = sm.imread(im_fp)
if not path.exists(body_fp):
raise Exception("Body fit not found for `%s`!" % (im_fp))
rendering = upr.render_body_impl(body_fp,
resolution=(im.shape[0], im.shape[1]),
quiet=True,
use_light=False)[0]
annotation = upm.regions_to_classes(rendering, upm.six_region_groups,
warn_id=str(img_idx))
out_fp = path.join('..', 'data', 'pose', 'extracted', dset_part,
"{:0{width}d}_bodysegments.png".format(
img_idx, width=bn.find("_")))
sm.imsave(out_fp, annotation)
out_fp = path.join('..',
"{:0{width}d}_bodysegments_vis.png".format(
img_idx, vs.apply_colormap(annotation, vmin=0, vmax=6,
cmap=config.CMAP)[:, 0:3])
def process_frame(frame_idx, img, model, write_to_dir, conf_threshold, input_size=224):
"""Finds bounding Boxes in a video frame,draws these bounding Boxes
and saves the result to HDD.
"""
# find BBs in frame
bbs, time_model = find_bbs(img, input_size=input_size)
# draw BBs
img_out = np.copy(img)
for (bb, score) in bbs:
if score > conf_threshold and bb.width > 2 and bb.height > 2:
img_out = bb.draw_on_image(img_out, color=[0, 255, 0], thickness=3)
# save to output directory
save_to_fp = os.path.join(write_to_dir, "%05d.jpg" % (frame_idx,))
misc.imsave(save_to_fp, img_out)
return time_model
def main():
img = imread(args.input_path)
img = ndimage.rotate(img, args.angle, mode=args.mode)
misc.imsave(args.output_path, img)
def main():
print(args)
for dir_path, dir_names, file_names in os.walk(args.input_data_dir):
# dir_path is a string,the path to the directory
# dir_names is a list of the names of the subdirectories in dir_path (excluding '.' and '..')
# file_names is a list of the names of the non-directory files in dir_path
dir_absolute_path = args.output_data_dir + dir_path.replace(args.input_data_dir, '')
if not os.path.exists(dir_absolute_path):
os.mkdir(dir_absolute_path)
for file_name in file_names:
# Split the pathname path into a pair (root,ext) such that root + ext == path,and ext is empty or begins
# with a period and contains at most one period.
(root, ext) = os.path.splitext(file_name)
new_file_name = '%s/%s.%dx%d%s' % (
dir_absolute_path, root, args.width, args.height, ext)
print(new_file_name)
if not os.path.exists(new_file_name):
img = imread(dir_path + '/' + file_name)
# type(img) = ndarray,https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
(width, height) = img.shape[0:2]
if width > height:
size = (args.width, height * args.width / width)
else:
size = (width * args.height / height, args.height)
new_img = misc.imresize(img, size)
misc.imsave(new_file_name, new_img)
def setup(self, pre_encode=False):
sbd_path = get_data_path('sbd')
voc_path = get_data_path('pascal')
target_path = self.root + '/SegmentationClass/pre_encoded/'
if not os.path.exists(target_path):
os.makedirs(target_path)
sbd_train_list = tuple(open(sbd_path + 'dataset/train.txt', 'r'))
sbd_train_list = [id_.rstrip() for id_ in sbd_train_list]
self.files['train_aug'] = self.files['train'] + sbd_train_list
if pre_encode:
print("Pre-encoding segmentation masks...")
for i in tqdm(sbd_train_list):
lbl_path = sbd_path + 'dataset/cls/' + i + '.mat'
lbl = io.loadmat(lbl_path)['GTcls'][0]['Segmentation'][0].astype(np.int32)
lbl = m.toimage(lbl, high=lbl.max(), low=lbl.min())
m.imsave(target_path + i + '.png', lbl)
for i in tqdm(self.files['trainval']):
lbl_path = self.root + '/SegmentationClass/' + i + '.png'
lbl = self.encode_segmap(m.imread(lbl_path))
lbl = m.toimage(lbl, lbl)
def pcaCreate(image_files,dir,name_num, dir_list):
image_list = []
new_file_name = dir
save_dir = dir_list + new_file_name
save_dir_tt = save_dir + "\\"
for image_file in image_files:
image_list.append(misc.imread(image_file))
for image in image_list:
img = np.asarray(image, dtype='float32')
img = img / 255.
img_size = img.size / 3
img1 = img.reshape(img_size, 3)
img1 = np.transpose(img1)
img_cov = np.cov([img1[0], img1[1], img1[2]])
lamda, p = np.linalg.eig(img_cov)
p = np.transpose(p)
alpha1 = random.normalvariate(0, 0.3)
alpha2 = random.normalvariate(0, 0.3)
alpha3 = random.normalvariate(0, 0.3)
v = np.transpose((alpha1 * lamda[0], alpha2 * lamda[1], alpha3 * lamda[2]))
add_num = np.dot(p, v)
img2 = np.array([img[:, 0] + add_num[0], img[:, 1] + add_num[1], 2] + add_num[2]])
img2 = np.swapaxes(img2, 0, 2)
img2 = np.swapaxes(img2, 1)
misc.imsave(save_dir_tt + np.str(name_num) + '.jpg', img2)
name_num += 1
return image_list
def pcaCreate_Ori(image_files,dir):
parser = argparse.ArgumentParser()
parser.add_argument("file_suffix", help="specific the file suffix")
parser.add_argument("root_dir", help="E:\\")
parser.add_argument("-f", "--file", help="record result to file")
parser.add_argument("data_set",help= "specific the file suffix")
args = parser.parse_args()
img_num = len(os.listdir(args.root_dir + '/' + args.dataset))
for i in range(img_num):
img_name = os.listdir(args.root_dir + '/' + args.dataset)[i]
img = Image.open(os.path.join(args.root_dir, args.dataset, img_name))
img = np.asarray(img, 1)
misc.imsave('test2222.jpg', img2)
def saveAllImages(rgb_array, directory, foldername):
"""
Saves unfiltered and filtered images to a file directory
:param rgb_array: image rgb array
:param directory: image directory name
:param foldername: name of the folder that will contain saved files
:return:
"""
rgb_array_red = rgb_array * 1
r_array = setimageColor(rgb_array_red, 'r')
rgb_array_green = rgb_array * 1
g_array = setimageColor(rgb_array_green, 'g')
rgb_array_blue = rgb_array * 1
b_array = setimageColor(rgb_array_blue, 'b')
trueimage = 'image.png'
redimage = 'red.png'
greenimage = 'green.png'
blueimage = 'blue.png'
plotimage = 'plot.png'
if not os.path.exists(os.path.join(directory, foldername)):
os.mkdir(os.path.join(directory, foldername))
misc.imsave(os.path.join(directory, foldername, trueimage), rgb_array)
misc.imsave(os.path.join(directory, redimage), r_array)
misc.imsave(os.path.join(directory, greenimage), g_array)
misc.imsave(os.path.join(directory, blueimage), b_array)
savePlot(rgb_array, os.path.join(directory, plotimage))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png", mode='RGB')
print(len(im_array), len(im_array[0]))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255,255,255)":
# tmp[i][j]=(0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp",tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi,noj,j))
def main():
'''
????????
'''
im_array = ndimage.imread("ustc.bmp", len(im_array))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255,j))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png",j))
def main():
'''
????????
'''
im_array = ndimage.imread("ms.bmp",j))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png",j))
def load_image_array(image_file, image_size,
image_id, data_dir='Data/datasets/mscoco/train2014',
mode='train'):
img = None
if os.path.exists(image_file):
#print('found' + image_file)
img = skimage.io.imread(image_file)
else:
print('notfound' + image_file)
img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id))
img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode,
image_id))
skimage.io.imsave(img_path, img)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,0] = img
img_new[:,1] = img
img_new[:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
def save_concat_images(imgs, img_path):
concated = np.concatenate(imgs, axis=1)
misc.imsave(img_path, concated)
def swap_attribute(src_img, att_img, model_dir, gpu):
'''
Input
src_img: the source image that you want to change its attribute
att_img: the attribute image that has certain attribute
model_dir: the directory that contains the checkpoint,ckpt.* files
model: the GeneGAN network that defined in train.py
gpu: for example,'0,1'. Use '' for cpu mode
Output
out1: src_img with attributes
out2: att_img without attributes
'''
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
ckpt = tf.train.get_checkpoint_state(model_dir)
# print(ckpt)
# print(ckpt.model_checkpoint_path)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
out2, out1 = sess.run([model.Ae, model.Bx], Feed_dict={model.Ax: att_img, model.Be: src_img})
misc.imsave('out1.jpg', out1[0])
misc.imsave('out2.jpg', out2[0])
def interpolation(src_img, inter_num, gpu):
'''
Input
src_img: the source image that you want to change its attribute
att_img: the attribute image that has certain attribute
inter_num: number of interpolation points
model_dir: the directory that contains the checkpoint,1'. Use '' for cpu mode
Output
out: [src_img,inter1,inter2,...,inter_{inter_num}]
'''
os.environ["CUDA_VISIBLE_DEVICES"] = gpu
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
ckpt = tf.train.get_checkpoint_state(model_dir)
# print(ckpt)
# print(ckpt.model_checkpoint_path)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
out = src_img[0]
for i in range(1, inter_num + 1):
lambda_i = i / float(inter_num)
model.out_i = model.joiner('G_joiner', model.B, model.x * lambda_i)
out_i = sess.run(model.out_i, model.Be: src_img})
out = np.concatenate((out, out_i[0]), axis=1)
# print(out.shape)
misc.imsave('interpolation.jpg', out)
def interpolation2(src_img, ckpt.model_checkpoint_path)
B, src_feat = sess.run([model.B, model.e], Feed_dict={model.Be: src_img})
att_feat = sess.run(model.x, Feed_dict={model.Ax: att_img})
out = src_img[0]
for i in range(1, inter_num + 1):
lambda_i = i / float(inter_num)
out_i = sess.run(model.joiner('G_joiner', B, src_feat + (att_feat - src_feat) * lambda_i) )
out = np.concatenate((out, axis=1)
# print(out.shape)
misc.imsave('interpolation2.jpg', out)
def AddNoize(i):
R = random.randint(0, 1)
if (R==1):
i=np.fliplr(i)#random mirroring
R = random.randint(0, 1)
if (R==1):
R = random.randint(-10, 10)
i= ndimage.interpolation.rotate(i,R)#random rotation
R = random.randint(0, 1)
if (R==1):
crop_left=random.randint(0,15)
crop_right = random.randint(1, 15)
crop_top = random.randint(0, 15)
crop_bot = random.randint(1, 15)
i=i[crop_left:-crop_right,crop_top:-crop_bot,:] #Randomcrop
#Next code is VERY SLOW becoase it use Python to change brightness
#need to optimase it,but i have no time yet:)
R = random.randint(0, 2)
if (R==2): #Random brightness in R channel
d = random.random()+1
i[:, 0] = adjust_gamma(i[:,0],d)
R = random.randint(0, 2)
if (R==2): #Random brightness in G channel
d = random.random()+1
i[:, 1] = adjust_gamma(i[:, 1], d)
R = random.randint(0, 2)
if (R==2): #Random brightness in B channel
d = random.random()+1
i[:, 2] = adjust_gamma(i[:, 2], d)
#misc.imsave("test.jpg",i)
return i
#Prepare data for learning
def save_image(image, save_dir, name=""):
"""
Save image by unprocessing assuming mean 127.5
:param image:
:param save_dir:
:param name:
:return:
"""
image += 1
image *= 127.5
image = np.clip(image, 255).astype(np.uint8)
image = np.reshape(image, -1))
misc.imsave(os.path.join(save_dir, name + "pred_image.png"), image)
def resize_raw_images(prms):
rawNames,_,_ = get_imnames(prms, isRaw=True)
tgNames,_ = get_imnames(prms)
for rn,tn in zip(rawNames, tgNames):
im = scm.imread(rn)
im = scm.imresize(im, [320, 480])
dName = os.path.dirname(tn)
if not os.path.exists(dName):
os.makedirs(dName)
scm.imsave(tn, im)
##
# Write pairs file
def vis_pairs(prms, isSave=False, svIdx=None, svPath=None):
imName1, imName2, euls, trans = read_pairs(prms)
N = len(imName1)
seed = 3
randState = np.random.RandomState(seed)
perm = randState.permutation(N)
fig = plt.figure()
plt.ion()
imName1 = [imName1[i] for i in perm]
imName2 = [imName2[i] for i in perm]
euls = [euls[i] for i in perm]
trans = [trans[i] for i in perm]
titleStr = 'Trans: ' + '%.3f ' * 3 + 'Rot: ' + '%.3f ' * 3
count = 0
numSave = 0
for (im1,im2,eu,tr) in zip(imName1, trans):
titleName = titleStr % (tuple(tr) + eu)
im1 = scm.imread(im1)
im2 = scm.imread(im2)
print count
if isSave:
if count in svIdx:
imN1 = svPath % (count,1)
imN2 = svPath % (count,2)
scm.imsave(imN1,im1)
scm.imsave(imN2,im2)
numSave += 1
if numSave==len(svIdx):
return
else:
vu.plot_pairs(im1, im2, fig, titleStr=titleName)
cmd = raw_input()
if cmd == 'exit':
return
count += 1
##
def reshape_images(cls, source_folder, target_folder, height=128, width=128,
extensions=('.jpg', '.jpeg', '.png')):
""" copy images and reshape them"""
# check source_folder and target_folder:
cls.check_folder_existance(source_folder, throw_error_if_no_folder=True)
cls.check_folder_existance(target_folder, display_msg=False)
if source_folder[-1] == "/":
source_folder = source_folder[:-1]
if target_folder[-1] == "/":
target_folder = target_folder[:-1]
# read images and reshape:
print("Resizing '", "' images...")
for filename in os.listdir(source_folder):
if os.path.isdir(source_folder + '/' + filename):
cls.reshape_images(source_folder + '/' + filename,
target_folder + '/' + filename,
height, width, extensions=extensions)
else:
if extensions == '' and os.path.splitext(filename)[1] == '':
copy2(source_folder + "/" + filename,
target_folder + "/" + filename)
image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
image_resized = misc.imresize(image, (height, width))
misc.imsave(target_folder + "/" + filename, image_resized)
else:
for extension in extensions:
if filename.endswith(extension):
copy2(source_folder + "/" + filename,
target_folder + "/" + filename)
image = ndimage.imread(target_folder + "/" + filename, mode="RGB")
image_resized = misc.imresize(image, width))
misc.imsave(target_folder + "/" + filename, image_resized)
def crop_images(cls, '.png')):
""" copy images and center crop them"""
# check source_folder and target_folder:
cls.check_folder_existance(source_folder, display_msg=False)
if source_folder[-1] == "/":
source_folder = source_folder[:-1]
if target_folder[-1] == "/":
target_folder = target_folder[:-1]
# read images and crop:
print("Cropping '", "' images...")
for filename in os.listdir(source_folder):
if os.path.isdir(source_folder + '/' + filename):
cls.crop_images(source_folder + '/' + filename, mode="RGB")
[width_original, height_original, _] = image.shape
offset_w = (width_original - width) / 2
offset_h = (width_original - width) / 2
image_cropped = image[offset_w : width + offset_w, offset_h : height + offset_h, :]
misc.imsave(target_folder + "/" + filename, image_cropped)
else:
for extension in extensions:
if filename.endswith(extension):
copy2(source_folder + "/" + filename, mode="RGB")
[width_original, _] = image.shape
offset_w = (width_original - width) / 2
offset_h = (width_original - width) / 2
image_cropped = image[offset_w : width + offset_w, :]
misc.imsave(target_folder + "/" + filename, image_cropped)
def convert_to_grayscale(cls,
extensions=('.jpg', '.png')):
""" convert images from RGB to Grayscale"""
# check source_folder and target_folder:
cls.check_folder_existance(source_folder, display_msg=False)
if source_folder[-1] == "/":
source_folder = source_folder[:-1]
if target_folder[-1] == "/":
target_folder = target_folder[:-1]
# read images and reshape:
print("Convert '", "' images to grayscale...")
for filename in os.listdir(source_folder):
if os.path.isdir(source_folder + '/' + filename):
cls.convert_to_grayscale(source_folder + '/' + filename,
target_folder + '/' + filename,
extensions=extensions)
else:
if extensions == '' and os.path.splitext(filename)[1] == '':
copy2(source_folder + "/" + filename, flatten=True)
misc.imsave(target_folder + "/" + filename, image)
else:
for extension in extensions:
if filename.endswith(extension):
copy2(source_folder + "/" + filename, flatten=True)
misc.imsave(target_folder + "/" + filename, image)
def convert_format(cls, '.png'), new_extension='.jpg'):
""" change images from one format to another (eg. change png files to jpeg) """
# check source_folder and target_folder:
cls.check_folder_existance(source_folder, display_msg=False)
if source_folder[-1] == "/":
source_folder = source_folder[:-1]
if target_folder[-1] == "/":
target_folder = target_folder[:-1]
# read images and reshape:
print("Change format of '", "' files...")
for filename in os.listdir(source_folder):
if os.path.isdir(source_folder + '/' + filename):
cls.convert_format(source_folder + '/' + filename,
extensions=extensions, new_extension=new_extension)
else:
if extensions == '' and os.path.splitext(filename)[1] == '':
copy2(source_folder + "/" + filename,
target_folder + "/" + filename + new_extension)
image = ndimage.imread(target_folder + "/" + filename + new_extension)
misc.imsave(target_folder + "/" + filename + new_extension, image)
else:
for extension in extensions:
if filename.endswith(extension):
new_filename = os.path.splitext(filename)[0] + new_extension
copy2(source_folder + "/" + filename,
target_folder + "/" + new_filename)
image = ndimage.imread(target_folder + "/" + new_filename)
misc.imsave(target_folder + "/" + new_filename, image)
def save_alpha_img(org, mat, name):
w, _ = mat.shape
#print(mat[200:210,200:210])
rmat = np.reshape(mat, (w, h))
amat = np.zeros((w, 4), dtype=np.int)
amat[:, 3] = rmat * 1000
amat[:, 0:3] = org
print(amat[200:205, 200:205])
#im = Image.fromarray(np.uint8(amat))
#im.save(name + '.png')
misc.imsave(name + '.png', amat)
def save_image(image, image)
# as describe at Sec.4.2
def save_alpha_img(org, h = mat.shape[0], mat.shape[1]
#print(mat[200:210, 3] = np.round(rmat * 1000)
amat[:, 0:3] = org
#print(amat[200:205,200:205])
#im = Image.fromarray(np.uint8(amat))
#im.save(name + '.png')
misc.imsave(name + '.png', amat)
def _write_deepdream(images, layer, path_outdir, path_logdir):
is_success = True
images = _im_normlize([images])
layer, units, k = layer
# write into disk
path_out = os.path.join(path_outdir, "deepdream_" + layer.lower().replace("/", "_"))
is_success = make_dir(path_out)
for i in range(len(images)):
for j in range(images[i].shape[0]):
img_save = images[i][j]
if img_save.shape[2] == 1:
img_save = np.squeeze(img_save, axis=2)
imsave(os.path.join(path_out, "image_%d.png" % (units[(i * images[i].shape[0]) + j + k])), img_save, format = "png")
# write into logfile
path_log = os.path.join(path_logdir, layer.lower().replace("/", "_"))
is_success = make_dir(path_log)
with tf.Graph().as_default() as g:
image = tf.placeholder(tf.float32, shape = [None, None, None])
image_summary_t = tf.summary.image(name = "One_By_One_DeepDream", tensor = image, max_outputs = config["MAX_FEATUREMAP"])
with tf.Session() as sess:
summary = sess.run(image_summary_t, Feed_dict = {image : np.concatenate(images, axis = 0)})
try:
file_writer = tf.summary.FileWriter(path_log, g) # create file writer
# compute and write the summary
file_writer.add_summary(summary)
except:
is_success = False
print("Error occured in writting results into log file.")
finally:
file_writer.close() # close file writer
return is_success