def crop_images(path_images, path_output, dimensions, centre=True):
"""
Batch crop images from top left hand corner to dimensions specified. Skips
images where dimensions are incompatible.
"""
print 'cropping images...'
for i, filename in enumerate(os.listdir(path_images)):
try:
image = io.imread('{}{}'.format(path_images, filename))
cropped = crop_image(image, dimensions, centre=centre)
io.imsave(
fname='{}{}'.format(path_output, filename),
arr=cropped
)
print '{}: {}'.format(i, filename)
except IndexError:
print '{}: {} failed - dimensions incompatible'.format(i, filename)
print 'all images cropped and saved.'
python类imsave()的实例源码
def _remove_padding(path_to_image, output_path, padding):
"""
Removes padding of a single image and saves output to a new file
:param path_to_image: full path to an input image
:param output_path: full path to a file in which output result is saved
:param padding: integer
:return: nothing
"""
if not os.path.isfile(path_to_image):
print 'Warning: %s not found' % path_to_image
return
# read image
image = io.imread(path_to_image)
dim = image.shape
x = dim[0] - padding
y = dim[1] - padding
# crop the image
image_cropped = image[padding:x, padding:y]
# save cropped image
io.imsave(output_path, image_cropped)
def showImage( batch_id, dictionary, imSize, attr, outfile):
images = dictionary.get('data')
labels = dictionary.get('labels')
for i in xrange(10000):
singleImage = images[i]
recon = np.zeros( (imSize, imSize, 3), dtype = np.uint8 )
singleImage = singleImage.reshape( (imSize*3, imSize))
red = singleImage[0:imSize,:]
blue = singleImage[imSize:2*imSize,:]
green = singleImage[2*imSize:3*imSize,:]
recon[:,:,0] = red
recon[:,:,1] = blue
recon[:,:,2] = green
outpath = os.path.abspath(".") + "/" + attr + "/" + str(batch_id) + "_" + str(i) + ".jpg"
#recon = resize(recon, (256, 256))
io.imsave(outpath, recon)
outfile.write(outpath + " " + str(labels[i]) + "\n")
def __call__(self, sample):
"""Return sample and write image within sample"""
pathfunc, namefunc = self.pathfunc, self.namefunc
name = namefunc(sample) if isfunction(namefunc) else next(namefunc)
if isinstance(pathfunc, str):
filepath = pathfunc.replace('*', str(name))
elif isfunction(pathfunc):
filepath = pathfunc(sample, name)
else:
raise ValueError('Expect path or function: ' + str(pathfunc))
create_folders(os.path.split(filepath)[0])
img = sample if self.column is None else sample[self.column]
sio.imsave(filepath, img)
return sample
def plot_figure_video_structure(structures, structure_combined, structure_optimized, rigidity_refined):
# Figure 92
PTH='./figure_structure/'
if not os.path.isdir(PTH):
os.makedirs(PTH)
structure_min = np.percentile(structure_optimized[rigidity_refined==1].ravel(), 2)
structure_max = np.percentile(structure_optimized[rigidity_refined==1].ravel(), 98)
Is_fwd = structure2image(structures[1], rigidity_refined,
structure_min=structure_min,
structure_max=structure_max)
Is_comb = structure2image(structure_combined, rigidity_refined,
structure_min=structure_min,
structure_max=structure_max)
Is_opt = structure2image(structure_optimized, rigidity_refined,
structure_min=structure_min,
structure_max=structure_max)
io.imsave(PTH+'structure_fwd.png', Is_fwd)
io.imsave(PTH+'structure_comb.png', Is_comb)
io.imsave(PTH+'structure_opt.png', Is_opt)
def plot_figure_video_pasted_example(rigidity, flow_discrete, flow_ours):
# Figure 94
PTH='./figure_pasted/'
if not os.path.isdir(PTH):
os.makedirs(PTH)
I_rigidity = np.dstack((rigidity,rigidity,rigidity)).astype('float')
I_df = flow_viz.computeFlowImage(flow_discrete[0],flow_discrete[1])
I_struc = flow_viz.computeFlowImage(flow_ours[0],flow_ours[1])
I_struc_filtered = I_rigidity*I_struc
I_final = I_struc_filtered + (1-I_rigidity)*I_df
I_rigidity_ = I_rigidity.copy()
I_rigidity_[:,:,1] = 0
I_rigidity_[:,:,2] = 1-I_rigidity_[:,:,2]
io.imsave(PTH+'rigidiyt.png', I_rigidity_)
io.imsave(PTH+'discreteflow.png', I_df)
io.imsave(PTH+'structureflow.png', I_struc)
io.imsave(PTH+'structureflow_filtered.png', I_struc_filtered.astype('uint8'))
io.imsave(PTH+'mrflow.png', I_final.astype('uint8'))
def plot_figure_95(images, rigidity, structure, flow_init, flow):
# Results figure for video.
PTH='./figure_results/'
if not os.path.isdir(PTH):
os.makedirs(PTH)
# Save frame triplet
io.imsave(PTH+'image_0.png', images[0])
io.imsave(PTH+'image_1.png', images[1])
io.imsave(PTH+'image_2.png', images[2])
I_rigidity = np.dstack((rigidity,rigidity,rigidity)).astype('float')
I_rigidity[:,:,1] = 0
I_rigidity[:,:,2] = 1-I_rigidity[:,:,2]
io.imsave(PTH+'rigidity.png', I_rigidity)
I_structure = structure2image(structure, rigidity)
io.imsave(PTH+'structure.png', I_structure)
I_mrflow = flow_viz.computeFlowImage(flow[0],flow[1])
I_discreteflow = flow_viz.computeFlowImage(flow_init[0],flow_init[1])
io.imsave(PTH+'mrflow.png', I_mrflow)
io.imsave(PTH+'discreteflow.png', I_discreteflow)
def SaveImage(img, args, epoch):
"""
Postprocess Image and use total tv-norm to denoise postprocessed image
1. postprocess Image
2. use total tv-norm to denoise postprocessed image
Parameters
--------
img: ndarray (1x3xMxN), optimized image
Returns
"""
out = PostprocessImage(img)
out = denoise_tv_chambolle(out, weight=args.remove_noise, multichannel=True)
if args.mod_type == "purposeful":
save_name = os.path.join(args.output,"{}_{}_{}_{}_{}.jpg".\
format(args.layer_name, args.mod_type, os.path.basename(args.content_image)[:-4],\
os.path.basename(args.style_image)[:-4], epoch))
else:
save_name = os.path.join(args.output,"{}_{}_{}_{}.jpg".\
format(args.layer_name, args.mod_type, os.path.basename(args.content_image)[:-4], epoch))
logging.info('save output to %s', save_name)
io.imsave(save_name, out)
def cropframes(clip_dir, image_files, clip_path):
clip = clip_path.split('/')[-1]
clip_name = clip.split('.')[0]
crop_dir = clip_dir + 'cropped/'
# crop_dir = '/home/sxg755/dataset/train/all_frames/cropped/'
if not os.path.exists(crop_dir):
os.makedirs(crop_dir)
cropped_files = []
for idx, image in enumerate(image_files):
img = io.imread(image)
h = img.shape[0]
w = img.shape[1]
img_cropped = img[0:4*h/5, 0:w]
io.imsave(crop_dir + clip_name + '_keyframe' + "{0:0>4}".format(idx+1) + '.jpg', img_cropped)
cropped_files.append(crop_dir + clip_name + '_keyframe' + "{0:0>4}".format(idx+1) + '.jpg')
return cropped_files
def mrz():
"""
Command-line script for extracting MRZ from a given image
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
parser.add_argument('filename')
parser.add_argument('--json', action='store_true', help='Produce JSON (rather than tabular) output')
parser.add_argument('-r', '--save-roi', default=None,
help='Output the region of the image that is detected to contain the MRZ to the given png file')
parser.add_argument('--version', action='version', version='PassportEye MRZ v%s' % passporteye.__version__)
args = parser.parse_args()
filename, mrz, walltime = process_file((args.filename, args.save_roi is not None))
d = mrz.to_dict() if mrz is not None else {'mrz_type': None, 'valid': False, 'valid_score': 0}
d['walltime'] = walltime
d['filename'] = filename
if args.save_roi is not None and mrz is not None and 'roi' in mrz.aux:
io.imsave(args.save_roi, mrz.aux['roi'])
if not args.json:
for k in d:
print("%s\t%s" % (k, str(d[k])))
else:
print(json.dumps(d, indent=2))
def save_labels(fns):
'''
INPUT list 'fns': filepaths to all labels
'''
progress.currval = 0
slices=np.zeros((240,240))
label=glob(fns+'/*OT.nii.gz')
print 'len of label:',len(label)
print 'type of label:',type(label)
s = ni.load_image(label[0])
print s.shape
print "=========="
label_idx=0
for slice_idx in xrange(1):
slices=np.asarray(s[:,:,slice_idx])
print slices.shape
io.imsave(ORI_PATH+'Labels/{}_{}L.png'.format(label_idx, slice_idx), slices)
def save_image_with_clusters(x, clusters, filename, shape=(10, 10), scale_each=False,
transpose=False):
'''single image, each row is a cluster'''
makedirs(filename)
n = x.shape[0]
images = np.zeros_like(x)
curr_len = 0
for i in range(10):
images_i = x[clusters==i, :]
n_i = images_i.shape[0]
images[curr_len : curr_len+n_i, :] = images_i
curr_len += n_i
x = images
if transpose:
x = x.transpose(0, 2, 3, 1)
if scale_each is True:
for i in range(n):
x[i] = rescale_intensity(x[i], out_range=(0, 1))
n_channels = x.shape[3]
x = img_as_ubyte(x)
r, c = shape
if r * c < n:
print('Shape too small to contain all images')
h, w = x.shape[1:3]
ret = np.zeros((h * r, w * c, n_channels), dtype='uint8')
for i in range(r):
for j in range(c):
if i * c + j < n:
ret[i * h:(i + 1) * h, j * w:(j + 1) * w, :] = x[i * c + j]
ret = ret.squeeze()
io.imsave(filename, ret)
def simple_image_process(file_name):
random_number = random.randint(1,100)
image = io.imread(file_name,as_grey=True)
io.imsave(file_name + str(random_number) +'.png',image)
return random_number
def save_image_collections(x, filename, shape=(10, 10), scale_each=False,
transpose=False):
"""
:param shape: tuple
The shape of final big images.
:param x: numpy array
Input image collections. (number_of_images, rows, columns, channels) or
(number_of_images, channels, rows, columns)
:param scale_each: bool
If true, rescale intensity for each image.
:param transpose: bool
If true, transpose x to (number_of_images, rows, columns, channels),
i.e., put channels behind.
:return: `uint8` numpy array
The output image.
"""
makedirs(filename)
n = x.shape[0]
if transpose:
x = x.transpose(0, 2, 3, 1)
if scale_each is True:
for i in range(n):
x[i] = rescale_intensity(x[i], out_range=(0, 1))
n_channels = x.shape[3]
x = img_as_ubyte(x)
r, c = shape
if r * c < n:
print('Shape too small to contain all images')
h, w = x.shape[1:3]
ret = np.zeros((h * r, w * c, n_channels), dtype='uint8')
for i in range(r):
for j in range(c):
if i * c + j < n:
ret[i * h:(i + 1) * h, j * w:(j + 1) * w, :] = x[i * c + j]
ret = ret.squeeze()
io.imsave(filename, ret)
def convert_RGB_mask_to_index(im, colors, ignore_missing_labels=False):
"""
:param im: mask in RGB format (classes are RGB colors)
:param colors: the color map should be in the following format
colors = OrderedDict([
("Sky", np.array([[128, 128, 128]], dtype=np.uint8)),
("Building", np.array([[128, 0, 0], # Building
[64, 192, 0], # Wall
[0, 128, 64] # Bridge
], dtype=np.uint8)
...
])
:param ignore_missing_labels: if True the function continue also if some
pixels fail the mappint
:return: the mask in index class format
"""
out = (np.ones(im.shape[:2]) * 255).astype(np.uint8)
for grey_val, (label, rgb) in enumerate(colors.items()):
for el in rgb:
match_pxls = np.where((im == np.asarray(el)).sum(-1) == 3)
out[match_pxls] = grey_val
if ignore_missing_labels: # retrieve the void label
if [0, 0, 0] in rgb:
void_label = grey_val
# debug
# outpath = '/Users/marcus/exp/datasets/camvid/grey_test/o.png'
# imsave(outpath, out)
######
if ignore_missing_labels:
match_missing = np.where(out == 255)
if match_missing[0].size > 0:
print "Ignoring missing labels"
out[match_missing] = void_label
assert (out != 255).all(), "rounding errors or missing classes in colors"
return out.astype(np.uint8)
def save_image(outpath, img):
import errno
try:
os.makedirs(os.path.dirname(outpath))
except OSError as e:
if e.errno != errno.EEXIST:
raise e
pass
imsave(outpath, img)
def SaveImage(img, filename, remove_noise=0.05):
logging.info('save output to %s', filename)
out = PostprocessImage(img)
if remove_noise != 0.0:
out = denoise_tv_chambolle(out, weight=remove_noise, multichannel=True)
io.imsave(filename, out)
def save_output(gen, dest):
out = gen.get_outputs()[0]
io.imsave(dest, postprocess_img(out.asnumpy()[0]))
def _save_picture(data, path):
try:
io.imsave(path, data)
return True
except (KeyError, TypeError):
return False
augmentation.py 文件源码
项目:Nature-Conservancy-Fish-Image-Prediction
作者: Brok-Bucholtz
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def augment(method, save_dir):
train_filepaths = list(glob('./data/train/*/*.jpg'))
labels = [path[13:-14] for path in train_filepaths]
# Create label directories if they don't exist
for label in labels:
if not exists(save_dir + label):
makedirs(save_dir + label)
for file_path, label in tqdm(list(zip(train_filepaths, labels))):
augmented_image = method(io.imread(file_path))
io.imsave(save_dir + label + '/' + basename(file_path), augmented_image)
def saveImages(image_list, name_list, path):
"""Saves the list of images in the folder specified by path"""
i = 0
for image in image_list:
name = name_list[i]
io.imsave("./images/" + path + "/" + name + ".jpg", image)
i += 1
def saveImages(image_list, name_list, path):
"""Saves the list of images in the folder specified by path"""
i = 0
for image in image_list:
name = name_list[i]
io.imsave(path + "/" + name + ".jpg", image)
i += 1
def skimage_to_pil(img):
"""
Convert Skimage image to a PIL image
:param img: Skimage image object
:return: PIL image object
"""
# Get the absolute path of the working directory
abspath = os.path.dirname(__file__)
# Create a temp file to store the image
temp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False, dir=abspath)
# Save the image into the temp file
io.imsave(temp.name, img)
# Read the image as a PIL object
pil_img = Image.open(temp.name)
pil_img.load()
# Close the file
temp.close()
# Delete the file
os.remove(temp.name)
return pil_img
def save_image(filepath, image):
"""
Save numpy array as image (or numpy array) to given filepath.
Supported formats: gif, png, jpg, bmp, tif, npy
:param string filepath: File path for image file. Extension determines
image file format, e.g. .gif
:param numpy array image: Numpy array to save as image.
Must be of shape (h,w) or (h,w,3) or (h,w,4)
"""
if filepath.endswith('.npy'): # image as numpy array
np.save(filepath, image, allow_pickle=False)
else:
ski.imsave(filepath, image)
def test():
rgba = io.imread("debug.png")
hsva = RGBAtoHSVA(rgba)
noise = np.random.normal(0,0.01,rgba.shape)
hsva += noise
io.imsave("debug_rgbaconvert.png", HSVAtoRGBA(hsva))
def predictsinglefile(model, filepath):
filepath = os.path.abspath(filepath)
assert os.path.isfile(filepath), "File " + str(filepath) + " does not exist"
outputpath = os.path.dirname(filepath) + "/" + os.path.splitext(os.path.basename(filepath))[0] + "_hinted.png"
original = io.imread(filepath)
hinted = predict(model, original)
io.imsave(outputpath, hinted)
def main(_):
x, img = load_image(FLAGS.input)
sess = tf.Session()
print("\nLoading Vgg")
imgs = tf.placeholder(tf.float32, [None, 224, 224, 3])
vgg = vgg16(imgs, 'vgg16_weights.npz', sess)
print("\nFeedforwarding")
prob = sess.run(vgg.probs, feed_dict={vgg.imgs: x})[0]
preds = (np.argsort(prob)[::-1])[0:5]
print('\nTop 5 classes are')
for p in preds:
print(class_names[p], prob[p])
# Target class
predicted_class = preds[0]
# Target layer for visualization
layer_name = FLAGS.layer_name
# Number of output classes of model being used
nb_classes = 1000
cam3 = grad_cam(x, vgg, sess, predicted_class, layer_name, nb_classes)
img = img.astype(float)
img /= img.max()
# Superimposing the visualization with the image.
new_img = img+3*cam3
new_img /= new_img.max()
# Display and save
io.imshow(new_img)
plt.show()
io.imsave(FLAGS.output, new_img)
def save_image(array, fname, directory='processed'):
if not exists(directory):
makedirs(directory)
io.imsave('processed/{}'.format(fname), array)
def plot_figure_1(images, rigidity_refined, structure_refined, flow_estimated, flow_gt):
""" Plot teaser image:
- Triplet of frames
- Segmentation
- Structure
- Flow
"""
if not os.path.isdir('./teaser'):
os.makedirs('teaser')
I1 = img_as_ubyte(images[1])
cm_bwr = plt.get_cmap('bwr')
Irigidity = cm_bwr(rigidity_refined.astype('float32'))
Istructure = structure2image(structure_refined, rigidity_refined)
#Istructure_gray = structure2image(structure_refined, rigidity_refined)
#Istructure_plasma = structure2image(structure_refined, rigidity_refined,cmap='plasma')
#Istructure_inferno = structure2image(structure_refined, rigidity_refined,cmap='inferno')
#Istructure_hot = structure2image(structure_refined, rigidity_refined,cmap='hot')
#Istructure_magma =structure2image(structure_refined, rigidity_refined,cmap='magma')
#Istructure_viridis =structure2image(structure_refined, rigidity_refined,cmap='viridis')
#Istructure_jet =structure2image(structure_refined, rigidity_refined,cmap='jet')
#Istructure_rainbow =structure2image(structure_refined, rigidity_refined,cmap='rainbow')
Iflow_estimated = flow_viz.computeFlowImage(flow_estimated[0], flow_estimated[1])
Iflow_gt = flow_viz.computeFlowImage(flow_gt[0],flow_gt[1])
io.imsave('./teaser/01_images.png', I1)
io.imsave('./teaser/02_rigidity.png', Irigidity)
io.imsave('./teaser/03_structure.png', Istructure)
#io.imsave('./teaser/03_structure_gray.png', Istructure_gray)
#io.imsave('./teaser/03_structure_plasma.png', Istructure_plasma)
#io.imsave('./teaser/03_structure_inferno.png', Istructure_inferno)
#io.imsave('./teaser/03_structure_hot.png', Istructure_hot)
#io.imsave('./teaser/03_structure_magma.png', Istructure_magma)
#io.imsave('./teaser/03_structure_viridis.png', Istructure_viridis)
#io.imsave('./teaser/03_structure_jet.png', Istructure_jet)
#io.imsave('./teaser/03_structure_rainbow.png', Istructure_rainbow)
io.imsave('./teaser/04_flowest.png', Iflow_estimated)
io.imsave('./teaser/05_flowgt.png', Iflow_gt)
def plot_figure_3(image, rigidity_cnn, rigidity_motion, rigidity_structure, rigidity_refined):
if not os.path.isdir('./rigidityestimation'):
os.makedirs('./rigidityestimation')
cm_bwr = plt.get_cmap('bwr')
Irigidity_cnn = cm_bwr(rigidity_cnn.astype('float32'))
Irigidity_motion = cm_bwr(rigidity_motion.astype('float32'))
Irigidity_structure = cm_bwr(rigidity_structure.astype('float32'))
Irigidity_refined = cm_bwr(rigidity_refined.astype('float32'))
io.imsave('./rigidityestimation/01_image.png', img_as_ubyte(image))
io.imsave('./rigidityestimation/02_rigidity_cnn.png', Irigidity_cnn)
io.imsave('./rigidityestimation/03_rigidity_motion.png', Irigidity_motion)
io.imsave('./rigidityestimation/04_rigidity_structure.png', Irigidity_structure)
io.imsave('./rigidityestimation/05_rigidity_refined.png', Irigidity_refined)