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)
python类imsave()的实例源码
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 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 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 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'