我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用skimage.io.imsave()。
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.'
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
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)
def plot_figure_6(images, rigidity_refined, structure_refined, flow_estimated, flow_init, flow_gt, flow_gt_valid): if not os.path.isdir('./results_supmat/temp'): os.makedirs('results_supmat/temp') I = img_as_ubyte((images[0]+images[1]+images[2])/3.0) io.imsave('./results_supmat/temp/01_image.png',I) Iuv_gt = flow_viz.computeFlowImage(flow_gt[0], flow_gt[1]) io.imsave('./results_supmat/temp/02_gt_flow.png', Iuv_gt) cm_bwr = plt.get_cmap('bwr') Irigidity = cm_bwr(rigidity_refined.astype('float32')) io.imsave('./results_supmat/temp/03_rigidity.png',Irigidity) Istructure = structure2image(structure_refined, rigidity_refined) io.imsave('./results_supmat/temp/04_structure.png',Istructure) Iuv_est = flow_viz.computeFlowImage(flow_estimated[0],flow_estimated[1]) io.imsave('./results_supmat/temp/05_flow.png',Iuv_est) epe_est = np.sqrt((flow_estimated[0]-flow_gt[0])**2 + (flow_estimated[1]-flow_gt[1])**2) epe_init = np.sqrt((flow_init[0]-flow_gt[0])**2 + (flow_init[1]-flow_gt[1])**2) #import ipdb; ipdb.set_trace() epe_est[flow_gt_valid==0] = 0 epe_init[flow_gt_valid==0] = 0 epe_diff = epe_init - epe_est epe_green = np.clip(epe_diff, 0, 3)/3.0 epe_red = np.clip(-epe_diff, 0, 3)/3.0 Icomparison = np.zeros((rigidity_refined.shape[0],rigidity_refined.shape[1],3)) Icomparison[:,:,0] = epe_red Icomparison[:,:,1] = epe_green Icomparison = img_as_ubyte(Icomparison) io.imsave('./results_supmat/temp/06_comparison.png',Icomparison)
def plot_figure_factorization_b(images, structures, structure_optimized, rigidity_refined): # Figure 91 PTH='./figure_factorization/' if not os.path.isdir(PTH): os.makedirs(PTH) io.imsave(PTH+'image_00.png',images[0]) io.imsave(PTH+'image_01.png',images[1]) io.imsave(PTH+'image_02.png',images[2]) # Structure maps structure_min = np.percentile(structure_optimized[rigidity_refined==1].ravel(), 2) structure_max = np.percentile(structure_optimized[rigidity_refined==1].ravel(), 98) Is_bwd = structure2image(structures[0], rigidity_refined, structure_min=structure_min, structure_max=structure_max) Is_fwd = structure2image(structures[1], rigidity_refined, structure_min=structure_min, structure_max=structure_max) Is_comb = structure2image(structure_optimized, rigidity_refined, structure_min=structure_min, structure_max=structure_max) io.imsave(PTH+'structure_bwd.png', Is_bwd) io.imsave(PTH+'structure_fwd.png', Is_fwd) io.imsave(PTH+'structure_comb.png', Is_comb)
def plot_figure_video_rigidity_example(image, rigidity): # Figure 93 PTH='./figure_rigidity_example/' if not os.path.isdir(PTH): os.makedirs(PTH) I_bw = color.rgb2gray(image) I_bw = np.dstack((I_bw,I_bw,I_bw))*0.5 I_bw[:,:,0][rigidity==1] += 0.5 I_bw[:,:,2][rigidity==0] += 0.5 io.imsave(PTH+'image.png', image) io.imsave(PTH+'rigidity.png', I_bw)
def save_hog_image_comparison(filename): input_image = io.imread(filename) gray_image = color.rgb2gray(input_image) out_filename = "hog/" + filename # 87% for orientations=8, pixels_per_cell=(4, 4), cells_per_block=(1, 1) fd, hog_image = hog(gray_image, orientations=8, pixels_per_cell=(4, 4), cells_per_block=(1, 1), visualise=True) # io.imsave("hog/" + filename, hog_image) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True) ax1.axis('off') ax1.imshow(gray_image, cmap=plt.cm.gray) ax1.set_title('Input image') ax1.set_adjustable('box-forced') # Rescale histogram for better display hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) ax2.axis('off') ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray) ax2.set_title('Histogram of Oriented Gradients') ax1.set_adjustable('box-forced') plt.savefig(out_filename) plt.close() return hog_image
def batch_jpg_to_png(path_input, path_output): """ Convert jpg images to png. """ print 'coverting images...' for i, filename in enumerate(os.listdir(path_input)): input_jpg = '{}{}'.format(path_input, filename) fname = filename.replace('.jpg', '.png') output_png = '{}{}'.format(path_output, fname) I = io.imread(input_jpg) io.imsave(output_png, I) print '{}: {}'.format(i, filename) print 'image conversion complete.'
def _read_embed_save(self, filename, message): try: path_cover = '{}{}'.format(self._path_images, filename) path_stego = '{}{}'.format(self._path_output, filename) I = io.imread(path_cover) S = lsb.embed(I, message, self._seq_method) io.imsave(arr=S, fname=path_stego) except KeyError as e: print '%s | message size greater than image capacity.' % filename
def deskew(args,image, image_param): # Deskew the given image based on the horizontal line # Calculate the angle of the points between 20% and 80% of the line uintimage = get_uintimg(image) binary = get_binary(args, uintimage) labels, numl = measurements.label(binary) objects = measurements.find_objects(labels) deskew_path = None for i, b in enumerate(objects): linecoords = Linecoords(image, i, b) # The line has to be bigger than minwidth, smaller than maxwidth, stay in the top (30%) of the img, # only one obj allowed and the line isn't allowed to start contact the topborder of the image if int(args.minwidthhor * image_param.width) < get_width(b) < int(args.maxwidthhor * image_param.width) \ and int(image_param.height * args.minheighthor) < get_height(b) < int(image_param.height * args.maxheighthor) \ and int(image_param.height * args.minheighthormask) < (linecoords.height_start+linecoords.height_stop)/2 < int(image_param.height * args.maxheighthormask) \ and linecoords.height_start != 0: pixelwidth = set_pixelground(binary[b].shape[1]) arr = np.arange(1, pixelwidth(args.deskewlinesize) + 1) mean_y = [] #Calculate the mean value for every y-array for idx in range(pixelwidth(args.deskewlinesize)): value_y = measurements.find_objects(labels[b][:, idx + pixelwidth((1.0-args.deskewlinesize)/2)] == i + 1)[0] mean_y.append((value_y[0].stop + value_y[0].start) / 2) polyfit_value = np.polyfit(arr, mean_y, 1) deskewangle = np.arctan(polyfit_value[0]) * (360 / (2 * np.pi)) args.ramp = True deskew_image = transform.rotate(image, deskewangle) create_dir(image_param.pathout+os.path.normcase("/deskew/")) deskew_path = "%s_deskew.%s" % (image_param.pathout+os.path.normcase("/deskew/")+image_param.name, args.extension) deskewinfo = open(image_param.pathout+os.path.normcase("/deskew/")+image_param.name + "_deskewangle.txt", "w") deskewinfo.write("Deskewangle:\t%d" % deskewangle) deskewinfo.close() image_param.deskewpath = deskew_path with warnings.catch_warnings(): #Transform rotate convert the img to float and save convert it back warnings.simplefilter("ignore") misc.imsave(deskew_path, deskew_image) break return deskew_path
def SaveImage(img, filename): logging.info('save output to %s', filename) out = PostprocessImage(img) if args.remove_noise != 0.0: out = denoise_tv_chambolle(out, weight=args.remove_noise, multichannel=True) io.imsave(filename, out) # input
def SaveImage(img, filename, remove_noise=0.02): 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_image(image, save_dir, name): """ Save image by unprocessing and converting to rgb. :param image: iamge to save :param save_dir: location to save image at :param name: prefix to save filename :return: """ image = color.lab2rgb(image) io.imsave(os.path.join(save_dir, name + ".png"), image)
def encord(frame, q): img = cv2.resize(frame, (frame.shape[1] // 2, frame.shape[0] // 2)) img = img[:, ::-1].copy() s = StringIO() io.imsave(s, img, plugin='pil') s.seek(0) files = {'file': s,} q.put([img, files])
def encord(frame, q): img = frame[::2, ::-2].copy() # img = img[:, ::-1] # uncomment if you want flip the image s = StringIO() io.imsave(s, img[:, :, [2, 1, 0]], plugin='pil') s.seek(0) files = {'file': s,} q.put([img, files])
def save_label(self, slices, patient_num): """ Load the targets of one patient in format.mha and saves the slices in format png :param slices: list of label slice of a patient (groundTruth) :param patient_num: id-number of the patient """ print (slices.shape) for slice_idx, slice_el in enumerate(slices): try: io.imsave('Labels/{}_{}L.png'.format(patient_num, slice_idx), slice_el) except: mkdir_p('Labels/') io.imsave('Labels/{}_{}L.png'.format(patient_num, slice_idx), slice_el)
def get_static_google_map(request, filename=None, crop=False): response = urlfetch.fetch(request) # check for an error (no image at requested location) if response.getheader('x-staticmap-api-warning') is not None: return None try: img = Image.open(cStringIO.StringIO(response.content)) except IOError: print "IOError:" # print error (or it may return a image showing the error" return None else: img = np.asarray(img.convert("RGB")) # there seems not to be any simple way to check for the gray error image # that Google throws when going above the API limit -- so here's a hack. if (img==224).sum() / float(img.size) > 0.95: return None # remove the Google watermark at the bottom of the image if crop: img_shape = img.shape img = img[:int(img_shape[0]*0.85),:int(img_shape[1]*0.85)] if filename is not None: basedir = os.path.dirname(filename) if not os.path.exists(basedir) and basedir not in ["","./"]: os.makedirs(basedir) io.imsave(filename, img) return img
def _save_synthetic_examples(self, examples, parents, parent_ids, class_name): """ Saves synthetic images for reporting purposes :param examples: array of size (num_examples, image_width*image_height) :param parents: array of size (num_examples, image_width*image_height) :param parent_ids: array of size (num_examples, 2) :param class_name: string :return: nothing """ save_dir = os.path.join(self.path_to_output, 'figures/synthetic_examples/{}'.format(class_name)) helpers.prepare_dir(save_dir, empty=True) parents = np.reshape(parents, (-1, self._image_width, self._image_height)) #parents_resized = parents parents_resized = np.zeros((len(parents), 200, 200)) for i in xrange(len(parents)): parents_resized[i] = resize(parents[i], (200, 200)) i = 0 for _, img in enumerate(examples): i = int(i) sys.stdout.write('\rSaving synthetic example {} of {}'.format(i+1, len(examples))) sys.stdout.flush() img = img.reshape((self._image_height, self._image_width)) img = resize(img, (200, 200)) io.imsave(os.path.join(save_dir, '{}_{}_synthetic.png'.format(class_name, i)), img) io.imsave(os.path.join(save_dir, '{}_{}_parent_1.png'.format(class_name, i)), parents_resized[parent_ids[i, 0]]) io.imsave(os.path.join(save_dir, '{}_{}_parent_2.png'.format(class_name, i)), parents_resized[parent_ids[i, 1]]) i += 1 sys.stdout.write('\n')
def generate(self, tile): # Generate the terrain elevation and landcover image exy = None cxy = None for tx in range(tile[0] - 1, tile[0] + 2): ey = None cy = None for ty in range(tile[1] - 1, tile[1] + 2): e = elevation((tx, ty, self.__zoom)) c = landcover((tx, ty, self.__zoom)) ey = e if ey is None else np.concatenate((ey, e), axis=0) cy = c if cy is None else np.concatenate((cy, c), axis=0) exy = ey if exy is None else np.concatenate((exy, ey), axis=1) cxy = cy if cxy is None else np.concatenate((cxy, cy), axis=1) cxy = self.set_rocks_in_grad(exy, cxy) z0 = np.min(exy) zscale = max(MIN_ZSCALE, np.max(exy) - z0) exy = (exy - z0) / zscale exy[exy < 0] = 0 exy[exy > 1] = 1 # Resize the images, which should be power of 2 new_shape = (1 << (exy.shape[0] - 1).bit_length(), 1 << (exy.shape[1] - 1).bit_length()) exy = resize(exy, new_shape) new_shape = (1 << (cxy.shape[0] - 1).bit_length(), 1 << (cxy.shape[1] - 1).bit_length()) cxy = Image.fromarray(cxy, mode='RGB') cxy = cxy.resize(new_shape, Image.ANTIALIAS) # Save the textures io.use_plugin('freeimage') exy = img_as_uint(exy) update_mutex.acquire() self.__z0 = z0 self.__zscale = zscale io.imsave('mapzen/rsc/elevation.png', exy) io.imsave('mapzen/rsc/landcover.png', cxy) self.__tile_back = np.copy(tile) # Mark as pending to become updated. The objects should not be updated # in a parallel thread, but self.__updated = False update_mutex.release()
def save_patient(self, reg_norm_n4, patient_num): ''' INPUT: (1) int 'patient_num': unique identifier for each patient (2) string 'reg_norm_n4': 'reg' for original images, 'norm' normalized images, 'n4' for n4 normalized images OUTPUT: saves png in Norm_PNG directory for normed, Training_PNG for reg ''' print 'Saving scans for patient {}...'.format(patient_num) progress.currval = 0 if reg_norm_n4 == 'norm': #saved normed slices for slice_ix in progress(xrange(155)): # reshape to strip strip = self.normed_slices[slice_ix].reshape(1200, 240) if np.max(strip) != 0: # set values < 1 strip /= np.max(strip) if np.min(strip) <= -1: # set values > -1 strip /= abs(np.min(strip)) # save as patient_slice.png #print 'the max of strip:',np.max(strip) #print "the min of strip:",np.min(strip) io.imsave(ORI_PATH+'Norm_PNG/{}_{}.jpg'.format(patient_num, slice_ix), strip) elif reg_norm_n4 == 'reg': for slice_ix in progress(xrange(155)): strip = self.slices_by_slice[slice_ix].reshape(1200, 240) if np.max(strip) != 0: strip /= np.max(strip) io.imsave(ORI_PATH+'Training_PNG/{}_{}.png'.format(patient_num, slice_ix), strip) else: for slice_ix in progress(xrange(155)): # reshape to strip strip = self.normed_slices[slice_ix].reshape(1200, 240) if np.max(strip) != 0: # set values < 1 strip /= np.max(strip) if np.min(strip) <= -1: # set values > -1 strip /= abs(np.min(strip)) # save as patient_slice.png io.imsave(ORI_PATH+'n4_PNG/{}_{}.png'.format(patient_num, slice_ix), strip) print 'save'