def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
#Here you select the model
python类Image()的实例源码
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
#ANIMAL model (default)
#Here you select the model
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
#Here you select the model
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
#Here you select the model
def test_pil_version(self):
import sys
import PIL.Image
major,minor,sub = PIL.Image.VERSION.split('.')[:3]
rmajor,rminor,rsub = 1,1,5 # 2008/03/20
major,minor,sub = int(major),int(minor),int(sub)
print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
sys.stderr.flush()
self.assert_(major > rmajor
or major == rmajor and minor >= rminor
or major == rmajor and minor == rminor and sub >= sub)
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
# Image types to place in an <object> element
def _screencap(args):
dev = ioskit.Device(args.udid)
image = dev.screenshot()
if args.rotate:
method = getattr(Image, 'ROTATE_{}'.format(args.rotate))
image = image.transpose(method)
image.save(args.output)
print 'Screenshot saved to "%s"' % args.output
def screenshot(self, filename=None):
'''
Take ios screenshot
Args:
- filename(string): optional
Returns:
PIL.Image object
'''
image = self.d.screenshot()
if self.rotation:
method = getattr(Image, 'ROTATE_{}'.format(self.rotation*90))
image = image.transpose(method)
if filename:
image.save(filename)
return image
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
# Image types to place in an <object> element
def showBGRimage(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
a[:,:,[0,2]] = a[:,:,[2,0]] # for B,G,R order
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
def showmap(a, fmt='png'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
#def checkparam(param):
# octave = param['octave']
# starting_range = param['starting_range']
# ending_range = param['ending_range']
# assert starting_range <= ending_range, 'starting ratio should <= ending ratio'
# assert octave >= 1, 'octave should >= 1'
# return starting_range, ending_range, octave
def load_and_resize_image(path, height, width, mode='RGB'):
"""
Returns an np.ndarray (height x width x channels)
mode -- (RGB for color or L for grayscale)
"""
image = PIL.Image.open(path) # YY => RGB 8 bits, jpeg format, instance of Image class, not ndarray
image = image.convert(mode)
image = np.array(image) # YY => ndarray, uint8 values bet 0 and 255, shape 240x320x3 (h x w x ch)
if height > 0 and width > 0:
image = scipy.misc.imresize(image, (height, width),
'bilinear') # YY => ndarray, uint8 values bet 0 and 255, shape (h2 x w2 x ch)
return image
def _screencap(args):
dev = ioskit.Device(args.udid)
image = dev.screenshot()
if args.rotate:
method = getattr(Image, 'ROTATE_{}'.format(args.rotate))
image = image.transpose(method)
image.save(args.output)
print 'Screenshot saved to "%s"' % args.output
def screenshot(self, filename=None):
'''
Take ios screenshot
Args:
- filename(string): optional
Returns:
PIL.Image object
'''
image = self.d.screenshot()
if self.rotation:
method = getattr(Image, 'ROTATE_{}'.format(self.rotation*90))
image = image.transpose(method)
if filename:
image.save(filename)
return image
def __init__(self):
super(self).__init__()
# Import from Image only when in use
from PIL import Image
self.Image = Image
def save_array_to_tiff(array, output, verbose=True):
'''Y.G. Nov 1, 2017
Save array to a tif file
'''
img = PIL.Image.fromarray(array)
img.save( output )
if verbose:
print( 'The data is save to: %s.'%( output ))
def load_pilatus(filename):
'''Y.G. Nov 1, 2017
Load a pilatus 2D image
'''
return np.array( PIL.Image.open(filename).convert('I') )
def get_avg_img( data_series, img_samp_index=None, sampling = 100, plot_ = False , save=False, *argv,**kwargs):
'''Get average imagef from a data_series by every sampling number to save time'''
if img_samp_index is None:
avg_img = np.average(data_series[:: sampling], axis=0)
else:
avg_img = np.zeros_like( data_series[0] )
n=0
for i in img_samp_index:
avg_img += data_series[i]
n +=1
avg_img = np.array( avg_img) / n
if plot_:
fig, ax = plt.subplots()
uid = 'uid'
if 'uid' in kwargs.keys():
uid = kwargs['uid']
im = ax.imshow(avg_img , cmap='viridis',origin='lower',
norm= LogNorm(vmin=0.001, vmax=1e2))
#ax.set_title("Masked Averaged Image")
ax.set_title('uid= %s--Masked Averaged Image'%uid)
fig.colorbar(im)
if save:
#dt =datetime.now()
#CurTime = '%s%02d%02d-%02d%02d-' % (dt.year, dt.month, dt.day,dt.hour,dt.minute)
path = kwargs['path']
if 'uid' in kwargs:
uid = kwargs['uid']
else:
uid = 'uid'
#fp = path + "uid= %s--Waterfall-"%uid + CurTime + '.png'
fp = path + "uid=%s--avg-img-"%uid + '.png'
fig.savefig( fp, dpi=fig.dpi)
#plt.show()
return avg_img
def kitty(self):
"""The cure of boredom."""
try:
async with self.session.get(self.caturl) as r:
result = await r.json()
cat = discord.Embed(description="\u2063", color=discord.Color(0xffb6c1))
cat.set_image(url=result['file'])
# await self.bot.say(result['file'])
await self.bot.say(embed=cat)
except:
await self.bot.say("Couldn't Get An Image")
def fox(self):
"""Another cure of boredom."""
try:
async with self.session.get(self.foxurl) as r:
result = await r.json()
fox = discord.Embed(description="\u2063", color=discord.Color(0xffb6c1))
fox.set_image(url=result['file'])
# await self.bot.say(result['file'])
await self.bot.say(embed=fox)
except:
await self.bot.say("Couldn't Get An Image")