Python Image 模块,ANTIALIAS 实例源码
我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用Image.ANTIALIAS。
def convert(width,height):
im = Image.open("C:\\xxx\\test.jpg")
out = im.resize((width, height),Image.ANTIALIAS)
out.save("C:\\xxx\\test.jpg")
def resize(): # for resizing images to 256 by 256 and zooming in on the objects
for s in wanted_classes:
files = glob('data/overlays/' + labels[s]+'/*')
for f in tqdm(files):
images = glob(f+'/*')
for im in images:
# here I am maintianing the origional images and renaming them with a large_ prefix
actual = im
new = f+'/orig_' + im.split('/')[-1]
shutil.move(actual,new)
im = Image.open(new)
x,y = im.size
diff = (x-y)/2
im = im.crop((diff+100,100, x-diff-100, y-100)) # getting a square aspect ratio and zooming in on object by 100 pixels
im = ImageOps.fit(im, (256,256), Image.ANTIALIAS) # reshaping to 256 by 256
im.save(actual)
def resize_img(img_path, size=64,style='jpg', ch_width=200):
try:
img = Image.open(img_path)
(width,height) = img.size
new_width = ch_width
new_height = height * new_width / width
out = img.resize((new_width, new_height), Image.ANTIALIAS)
thumb_filename = gen_thumb_filename(img_path)
filename, ext = os.path.splitext(thumb_filename)
new_file_name = '%s.%s' % (filename, style)
#?????
filesize = os.path.getsize(img_path)/1024
if filesize > size:
quality = int(float(size) / float(filesize) * 100) - 1
else:
quality = 100
out.save(new_file_name, quality=quality)
return new_file_name
except Exception,e:
print Exception,':',e
def aboutCommand(self):
if self.aboutroot == None:
self.aboutroot = Toplevel()
self.aboutroot.title('About')
self.aboutroot.protocol("WM_DELETE_WINDOW", lambda: self.on_closing("aboutroot") )
canvas = Canvas(self.aboutroot, width=300, height=300)
image = Image.open("/usr/share/cownewsreader/media/background.png")
image = image.resize((100, 100), Image.ANTIALIAS)
self.img = ImageTk.PhotoImage(image)
canvas.create_image(100, 20, image = self.img, anchor="nw")
name = Label(canvas, text="CowNewsReader" ,anchor='w',font="monosa 11 bold")
name.pack()
canvas.create_window(80, 150, window=name, anchor='w')
version = Label(canvas, text="1.0.0" ,anchor='w')
version.pack()
canvas.create_window(120, 180, window=version, anchor='w')
copyright = Label(canvas, text="© 2016 Shkelqim Memolla" ,anchor='w')
copyright.pack()
canvas.create_window(80, 220, window=copyright, anchor='w')
canvas.pack()
def CropFace(image, eye_left=(0,0), eye_right=(0, offset_pct=(0.2,0.2), dest_sz = (70,70)):
# calculate offsets in original image
offset_h = math.floor(float(offset_pct[0])*dest_sz[0])
offset_v = math.floor(float(offset_pct[1])*dest_sz[1])
# get the direction
eye_direction = (eye_right[0] - eye_left[0], eye_right[1] - eye_left[1])
# calc rotation angle in radians
rotation = -math.atan(float(eye_direction[1])/float(eye_direction[0]))
# distance between them
dist = distance(eye_left, eye_right)
# calculate the reference eye-width
reference = dest_sz[0] - 2.0*offset_h
# scale factor
scale = float(dist)/float(reference)
# rotate original around the left eye
image = ScaleRotateTranslate(image, center=eye_left, angle=rotation)
# crop the rotated image
crop_xy = (eye_left[0] - scale*offset_h, eye_left[1] - scale*offset_v)
crop_size = (dest_sz[0]*scale, dest_sz[1]*scale)
image = image.crop((int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0]+crop_size[0]), int(crop_xy[1]+crop_size[1])))
# resize it
image = image.resize(dest_sz, Image.ANTIALIAS)
return image
def convert(dir,width,height):
file_list = os.listdir(dir)
print(file_list)
for filename in file_list:
path = ''
path = dir+filename
im = Image.open(path)
out = im.resize((256,Image.ANTIALIAS)
print "%s has been resized!"%filename
out.save(path)
def convert(width,height):
im = Image.open("C:\\workspace\\PythonLearn1\\test_1.jpg")
(x, y)= im.size
x_s = width
y_s = y * x_s / x
out = im.resize((x_s, y_s), Image.ANTIALIAS)
out.save("C:\\workspace\\PythonLearn1\\test_1_out.jpg")
def resizePhoto(photo):
thumbnail = photo.replace('.jpg', '.thumbnail.jpg')
try:
im = Image.open(photo)
im.thumbnail((380, 500), Image.ANTIALIAS)
im.save(thumbnail, "JPEG")
return thumbnail
except IOError:
print "cannot create thumbnail for '%s'" % photo
return False
def resize_image(self, im, photosize):
cur_width, cur_height = im.size
new_width, new_height = photosize.size
if photosize.crop:
ratio = max(float(new_width) / cur_width, float(new_height) / cur_height)
x = (cur_width * ratio)
y = (cur_height * ratio)
xd = abs(new_width - x)
yd = abs(new_height - y)
x_diff = int(xd / 2)
y_diff = int(yd / 2)
if self.crop_from == 'top':
Box = (int(x_diff), 0, int(x_diff + new_width), new_height)
elif self.crop_from == 'left':
Box = (0, int(y_diff), new_width, int(y_diff + new_height))
elif self.crop_from == 'bottom':
# y - yd = new_height
Box = (int(x_diff), int(yd), int(y))
elif self.crop_from == 'right':
# x - xd = new_width
Box = (int(xd), int(x), int(y_diff + new_height))
else:
Box = (int(x_diff), int(y_diff + new_height))
im = im.resize((int(x), int(y)), Image.ANTIALIAS).crop(Box)
else:
if not new_width == 0 and not new_height == 0:
ratio = min(float(new_width) / cur_width,
float(new_height) / cur_height)
else:
if new_width == 0:
ratio = float(new_height) / cur_height
else:
ratio = float(new_width) / cur_width
new_dimensions = (int(round(cur_width * ratio)),
int(round(cur_height * ratio)))
if new_dimensions[0] > cur_width or \
new_dimensions[1] > cur_height:
if not photosize.upscale:
return im
im = im.resize(new_dimensions, Image.ANTIALIAS)
return im
def scale_image(self, in_fname, out_fname, max_width, max_height):
"""Scales an image with the same aspect ratio centered in an
image with a given max_width and max_height
if in_fname == out_fname the image can only be scaled down
"""
# local import to avoid testing dependency on PIL:
try:
from PIL import Image
except ImportError:
import Image
img = Image.open(in_fname)
width_in, height_in = img.size
scale_w = max_width / float(width_in)
scale_h = max_height / float(height_in)
if height_in * scale_w <= max_height:
scale = scale_w
else:
scale = scale_h
if scale >= 1.0 and in_fname == out_fname:
return
width_sc = int(round(scale * width_in))
height_sc = int(round(scale * height_in))
# resize the image
img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)
# insert centered
thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))
pos_insert = (
(max_width - width_sc) // 2, (max_height - height_sc) // 2)
thumb.paste(img, pos_insert)
thumb.save(out_fname)
def create_thumb(self,im):
x = 800
y = 800
size = (y,x)
image = Image.fromarray(im)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', size, "black")
background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
return np.array(background)[:,:,0:3]
def make_thumbnail(in_fname, width, height):
"""Make a thumbnail with the same aspect ratio centered in an
image with a given width and height
"""
img = Image.open(in_fname)
width_in, height_in = img.size
scale_w = width / float(width_in)
scale_h = height / float(height_in)
if height_in * scale_w <= height:
scale = scale_w
else:
scale = scale_h
width_sc = int(round(scale * width_in))
height_sc = int(round(scale * height_in))
# resize the image
img.thumbnail((width_sc, Image.ANTIALIAS)
# insert centered
thumb = Image.new('RGB', (width, 255))
pos_insert = ((width - width_sc) / 2, (height - height_sc) / 2)
thumb.paste(img, pos_insert)
thumb.save(out_fname)
# Use optipng to perform lossless compression on the resized image if
# software is installed
if os.environ.get('SKLEARN_DOC_OPTIPNG', False):
try:
subprocess.call(["optipng", "-quiet", "-o", "9", out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the generated images')
def make_thumbnail(in_fname, height):
"""Make a thumbnail with the same aspect ratio centered in an
image with a given width and height
"""
# local import to avoid testing dependency on PIL:
try:
from PIL import Image
except ImportError:
import Image
img = Image.open(in_fname)
width_in, 255))
pos_insert = ((width - width_sc) // 2, (height - height_sc) // 2)
thumb.paste(img, out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the generated images')
def draw_with_alpha(source_image, image_to_draw, coordinates):
"""
Draws a partially transparent image over another image.
:param source_image: Image to draw over.
:param image_to_draw: Image to draw.
:param coordinates: Coordinates to draw an image at. Tuple of x,y,width and height.
"""
x, y, w, h = coordinates
image_to_draw = image_to_draw.resize((h, w), Image.ANTIALIAS)
image_array = image_as_nparray(image_to_draw)
for c in range(0, 3):
source_image[y:y + h, x:x + w, c] = image_array[:, :, c] * (image_array[:, 3] / 255.0) \
+ source_image[y:y + h, c] * (1.0 - image_array[:, 3] / 255.0)
def make_thumbnail(in_fname, out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the generated images')
def resize_image(im, r=None, newh=None, neww=None, filtering=Image.BILINEAR):
dt = im.dtype
I = Image.fromarray(im)
if r is not None:
h = im.shape[0]
w = im.shape[1]
newh = int(round(r*h))
neww = int(round(r*w))
if neww is None:
neww = int(newh*im.shape[1]/float(im.shape[0]))
if newh > im.shape[0]:
I = I.resize([neww, newh], Image.ANTIALIAS)
else:
I.thumbnail([neww, filtering)
return n.array(I).astype(dt)
def getPicture(self, imgPath):
File = imgPath
image = Image.open(File)
image = image.resize((100, Image.ANTIALIAS)
self.img = ImageTk.PhotoImage(image)
def create_thumbnail(file_path):
thumbnail_filename = utils.get_thumb_filename(file_path)
thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1])
image = default_storage.open(file_path)
image = Image.open(image)
file_format = image.format
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
# http://www.djangosnippets.org/snippets/20/
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
# scale and crop to thumbnail
imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS)
thumbnail_io = BytesIO()
imagefit.save(thumbnail_io, format=file_format)
thumbnail = InMemoryUploadedFile(
thumbnail_io,
None,
thumbnail_filename,
thumbnail_format,
len(thumbnail_io.getvalue()),
None)
thumbnail.seek(0)
return default_storage.save(thumbnail_filename, thumbnail)
def downscale_image(im, max_dim=2048):
"""Shrink im until its longest dimension is <= max_dim.
Returns new_image,scale (where scale <= 1).
"""
a, b = im.size
if max(a, b) <= max_dim:
return 1.0, im
scale = 1.0 * max_dim / max(a, b)
new_im = im.resize((int(a * scale), int(b * scale)), Image.ANTIALIAS)
return scale, new_im
def saveImageto(self, destinationFilename):
''' Generates an image and save to the destination filename.
destinationFilename (string): file path and name for destination file.
Supported file formats: png jpg bmp (and those supported by the PIL module)
This call is blocking.
'''
self._logInfo("Generating image and saving to %s" %
destinationFilename)
image = self.pool.getimageB()
if image.mode != 'RGB':
image = image.convert('RGB')
(imagex, imagey) = image.size
if (imagex != self.CONfig["assembler.sizex"] or imagey != self.CONfig["assembler.sizey"]):
image.thumbnail((self.CONfig["assembler.sizex"], self.CONfig[
"assembler.sizey"]), Image.ANTIALIAS)
if self.CONfig["assembler.mirror"]:
image = ImageOps.mirror(image)
if self.CONfig["assembler.emboss"]:
finalimage_embossed = image.filter(ImageFilter.embosS).filter(
ImageFilter.SMOOTH) # emboss image
image = ImageOps.equalize(ImageChops.multiply(
image, finalimage_embossed)) # Compose images
image = Image.blend(image, finalimage_embossed, 0.1)
if self.CONfig["assembler.invert"]:
image = ImageOps.invert(image)
image.save(destinationFilename)
self._logInfo("Done.")
# FIXME: Also create an asynchronous,threaded image creation method ?
def crawl_dns_info(only_new=False):
from_date = datetime.datetime.today() - datetime.timedelta(days=7)
if only_new:
blacklist_details = Blacklist.query.filter_by(last_crawl=None)
else:
blacklist_details = Blacklist.query.filter(or_(Blacklist.last_crawl < from_date, Blacklist.last_crawl == None))
for blacklist_detail in blacklist_details:
try:
file_path = os.path.join(app.config['THUMBNAIL_FOLDER'], '{}.png'.format(blacklist_detail.id))
thumbnail_file_path = os.path.join(app.config['THUMBNAIL_FOLDER'], 'thumbnail_{}.png'.format(blacklist_detail.id))
subprocess.call(["xvfb-run", "--", "wkhtmltoimage", '--width', '1280', blacklist_detail.dns, file_path])
size = (100, 200)
image = Image.open(file_path)
image.thumbnail(size, Image.ANTIALIAS)
background = Image.new('RGBA', 0))
background.paste(
image, (int((size[0] - image.size[0]) // 2), int((size[1] - image.size[1]) // 2))
)
background.save(thumbnail_file_path)
blacklist_detail.thumbnail = True
except Exception as e:
print('Failed to obtain DNS thumbnail: {}'.format(e))
blacklist_detail.thumbnail = False
blacklist_detail.last_crawl = datetime.datetime.Now()
db.session.add(blacklist_detail)
db.session.commit()
def make_thumbnail(in_fname, out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the generated images')
def fillImgArray(self, x, height, image, display = True):
buff = self.disp.buffer
actx = self.screenXFromImageCoords(x,y)
acty = self.screenYFromImageCoords(x,y)
image = Image.fromarray(image)
image = image.resize((width,height), Image.ANTIALIAS)
cr = self.currentRotation
if(cr == 1):
actx -= height
image = image.transpose(Image.ROTATE_270)
if(cr == 2):
acty -= height
actx -= width
image = image.transpose(Image.ROTATE_180)
if(cr == 3):
acty -= width
image = image.transpose(Image.ROTATE_90)
buff.paste(image, (actx,acty))
if(display):
self.disp.display()
## Rotates the screen orientation 90 degrees to the right (-90 degrees)
# @param self The object pointer.
# @remark
# To use this function in your program:
# @code
# ...
# screen.rotateRight()
# @endcode
def scale_image(in_fname, max_height):
"""Scales an image with the same aspect ratio centered in an
image with a given max_width and max_height
if in_fname == out_fname the image can only be scaled down
"""
# local import to avoid testing dependency on PIL:
try:
from PIL import Image
except ImportError:
import Image
img = Image.open(in_fname)
width_in, height_in = img.size
scale_w = max_width / float(width_in)
scale_h = max_height / float(height_in)
if height_in * scale_w <= max_height:
scale = scale_w
else:
scale = scale_h
if scale >= 1.0 and in_fname == out_fname:
return
width_sc = int(round(scale * width_in))
height_sc = int(round(scale * height_in))
# resize the image
img.thumbnail((width_sc, 255))
pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
thumb.paste(img, out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the \
generated images')
def main(j, args, params, tags, tasklet):
page = args.page
try:
import Image
except ImportError:
# pyflakes.ignore
from PIL import Image
space_name = args.doc.getSpaceName()
space_path = j.core.portal.active.getSpace(space_name).model.path
macro_params = args.cmdstr.split(' ')
img_url = macro_params[0]
if len(macro_params) >= 2:
thumb_size = macro_params[1]
else:
thumb_size = args.doc.docparams.get('thumb_size', DEFAULT_THUMB_SIZE)
if len(macro_params) >= 3:
exact_size = macro_params[2]
else:
exact_size = False
thumb_size = thumb_size or args.doc.docparams.get('thumb_size', DEFAULT_THUMB_SIZE)
width, height = [int(x) for x in thumb_size.split('x')]
img_path = img_url.strip('/')
full_img_path = os.path.join(space_path, img_path)
# Add 's_' to file name to tell that this is a thumbnail,and add width & height too
thumbnail_path = ('{0}s_{1}x{2}_').format(os.path.sep, height).join(os.path.split(full_img_path))
img_url_base, img_name = os.path.split(img_url)
thumbnail_url = os.path.join(space_name, img_url_base.strip('/'), r's_{0}x{1}_{2}'.format(width, img_name))
# If the thumbnail doesn't exist on the desk,generate it
if not os.path.exists(thumbnail_path):
im = Image.open(full_img_path)
if exact_size:
im = im.resize((width, Image.ANTIALIAS)
else:
im.thumbnail((width, Image.ANTIALIAS)
im.save(thumbnail_path)
page.addMessage('<img src="/{0}" />'.format(thumbnail_url))
params.result = page
return params
def scale_image(in_fname, out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the \
generated images')
def add_one_profile_cover(img_path, name):
'''?????????????'''
document = {}
document['name'] = name
document['content_type'] = 'JPEG'
existed = yield ImageDocument.find_one(document)
if existed:
return
path = os.path.join(img_path, name)
image = Image.open(path)
scale = image.size[0] * 1.0 / 960
width = int(image.size[0])
height = int(300 * scale)
Box = (0, height)
image = image.crop(Box)
image = image.resize((969, 300), Image.ANTIALIAS)
output = StringIO()
image.save(output, document['content_type'], quality=100)
document['body'] = Binary(output.getvalue())
output.close()
image = Image.open(path)
image = image.resize((260, 160), quality=100)
document['thumbnail'] = Binary(output.getvalue())
output.close()
image_id = yield ImageDocument.insert(document)
document = {
'image': DBRef(ImageDocument.Meta['collection'], ObjectId(image_id))
}
yield OfficialProfileCoverDocument.insert(document)
raise gen.Return()
def resize_and_crop(img_path, modified_path, crop_type='top'):
"""
Resize and crop an image to fit the specified size.
args:
img_path: path for the image to resize.
modified_path: path to store the modified image.
size: `(width,height)` tuple.
crop_type: can be 'top','middle' or 'bottom',depending on this
value,the image will cropped getting the 'top/left','middle' or
'bottom/right' of the image to fit the size.
raises:
Exception: if can not open the file in img_path of there is problems
to save the image.
ValueError: if an invalid `crop_type` is provided.
"""
# If height is higher we resize vertically,if not we resize horizontally
img = Image.open(img_path)
# Get current and desired ratio for the images
img_ratio = img.size[0] / float(img.size[1])
ratio = size[0] / float(size[1])
#The image is scaled/cropped vertically or horizontally depending on the ratio
if ratio > img_ratio:
img = img.resize((size[0], int(round(size[0] * img.size[1] / img.size[0]))),
Image.ANTIALIAS)
# Crop in the top,middle or bottom
if crop_type == 'top':
Box = (0, img.size[0], size[1])
elif crop_type == 'middle':
Box = (0, int(round((img.size[1] - size[1]) / 2)),
int(round((img.size[1] + size[1]) / 2)))
elif crop_type == 'bottom':
Box = (0, img.size[1] - size[1], img.size[1])
else :
raise ValueError('ERROR: invalid value for crop_type')
img = img.crop(Box)
elif ratio < img_ratio:
img = img.resize((int(round(size[1] * img.size[0] / img.size[1])), size[1]), size[0], img.size[1])
elif crop_type == 'middle':
Box = (int(round((img.size[0] - size[0]) / 2)),
int(round((img.size[0] + size[0]) / 2)), img.size[1])
elif crop_type == 'bottom':
Box = (img.size[0] - size[0], img.size[1])
else :
raise ValueError('ERROR: invalid value for crop_type')
img = img.crop(Box)
else :
img = img.resize((size[0],
Image.ANTIALIAS)
# If the scale is the same,we do not need to crop
img.save(modified_path)
def scale_image(in_fname, out_fname])
except Exception:
logger.warning(
'Install optipng to reduce the size of the generated images')
def _Resize(self, transform):
"""Use PIL to resize the given image with the given transform.
Args:
image: PIL.Image.Image object to resize.
transform: images_service_pb.Transform to use when resizing.
Returns:
PIL.Image.Image with transforms performed on it.
Raises:
ApplicationError: The resize data given was bad.
"""
width = 0
height = 0
if transform.has_width():
width = transform.width()
if width < 0 or 4000 < width:
raise apiproxy_errors.ApplicationError(
images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
if transform.has_height():
height = transform.height()
if height < 0 or 4000 < height:
raise apiproxy_errors.ApplicationError(
images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
crop_to_fit = transform.crop_to_fit()
allow_stretch = transform.allow_stretch()
current_width, current_height = image.size
new_width, new_height = self._CalculateNewDimensions(
current_width, current_height, crop_to_fit,
allow_stretch)
new_image = image.resize((new_width, Image.ANTIALIAS)
if crop_to_fit and (new_width > width or new_height > height):
left = int((new_width - width) * transform.crop_offset_x())
top = int((new_height - height) * transform.crop_offset_y())
right = left + width
bottom = top + height
new_image = new_image.crop((left, top, right, bottom))
return new_image
def preprocess(X):
#no preprocessing - just rescale the pixel values to the interval [0.0,1.0]
#return X / 255.0
#this preprocessor crops one pixel along each of the sides of the images
#this is a teeny tiny improvement on the "no preprocessing" option
#return X[:,1:-1,1:-1] / 255.0
#this preprocessor adds pixels along the bottom and side of the images
#t = np.zeros((X.shape[0],X.shape[1],36,36))
#t[:,0:X.shape[2],0:X.shape[3]] = X/255.0
#return t
#if data is in training set,then the chunk size is 1.
#if data is in training set,randomly scale the image size up or down
if X.shape[0] == 1:
#randomly scale the size of the image up or down
ns = np.random.randint(25, 33)
#Python Image Library expects arrays of format [width,height,3] or [width,height]
#theano/keras expects images of format [colours,width,height]
if X.shape[1] == 3:
im = Image.fromarray(np.rollaxis(X[0, :], 3).astype(np.uint8))
im.thumbnail((ns, ns),Image.ANTIALIAS)
X = np.rollaxis(np.array(im), 2,0).reshape((1,-1, im.size[0], im.size[1]))
if X.shape[1] == 1:
im = Image.fromarray(X[0, :].astype(np.uint8))
im.thumbnail((ns,Image.ANTIALIAS)
X = np.array(im).reshape((1, im.size[1]))
#print(X.shape)
#pad with greyscale checkerboard
t = 0.2*np.ones((X.shape[1], 4,4))
t[:, 0:2, 0:2] = 0.1*np.ones((X.shape[1],2))
t[:, 2:4, 2:4] = 0.1*np.ones((X.shape[1],2))
t = np.tile(t, (1, 9, 9))
t = np.tile(t.reshape((1,t.shape[0], t.shape[1], t.shape[2])), (X.shape[0], 1, 1))
#padding only one side and the bottom means that the training loss -> nan after a few
#epochs because there is never any information in these regions!
#t = np.zeros((X.shape[1],4,4))
#i = np.random.randint(0,4*9-X.shape[2])
#j = np.random.randint(0,4*9-X.shape[3])
#t[:,i : i+X.shape[2],j:j+X.shape[3]] = X/255.0
return t
def get_image_src2():
filename = "test.png"
image0 = Image.open(filename)
image1 = Image.open(filename)
datas = image0.getdata()
newdata = []
for item in datas:
if item[0] == 0 and item[1] == 0 and item[2] == 0: # Black -> White
newdata.append((255, 255))
else:
newdata.append((0, 0))
image0.putdata(newdata)
image0.save("st1.png")
image1 = image0.crop(image1.getbBox())
image1.save("step3.5.png")
w1, h1 = image1.size
image2 = Image.new("RGB", (28, 28), 255))
image1.thumbnail((20, 20), Image.ANTIALIAS)
image2.paste(image1, (0, 0))
image2.save("step4.png")
digit_image = mpimg.imread("step4.png")
gray_digit = np.dot(digit_image[...,:3], [0.299, 0.587, 0.114])
gray_digit = gray_digit.flatten()
for i in range(len(gray_digit)):
gray_digit[i] = 1.0 - gray_digit[i]
gray_digit[i] = round(gray_digit[i], 8)
# Calculating center of mass of the image
x, y = ndimage.measurements.center_of_mass(gray_digit.reshape(28, 28))
image2 = image2.transform(image2.size, Image.AFFINE, y - 14, x - 14), fill=0)
image2 = Image.new("RGB", 255))
image2.paste(image1, (14 - int(round(y, 0)), 14 - int(round(x, 0))))
image2.save("step6.png")
return "step6.png"
def convert_im(code, image1):
image1 = image1.crop(image1.getbBox())
w1, 255))
datas = image1.getdata()
newdata = []
"""
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255: # Red -> Black
newdata.append(white)
elif item[0] == 0 and item[1] == 0 and item[2] == 0: # Black -> White
newdata.append(white)
else:
newdata.append(black)
"""
#image1.putdata(newdata)
image1.thumbnail((20, 0))))
image2.save(chr(code) + str(time.time()) + ".png")
def convert_im(code, 28))
if math.isnan(x) or math.isnan(y):
return
image2 = image2.transform(image2.size, 0))))
image2.save(chr(code) + str(time.time()) + ".png")
def saveImageto(self, destinationFilename, resizeMethod=2):
''' Generates an image and save to the destination filename.
destinationFilename (string): file path and name for destination file.
Supported file formats: png jpg bmp (and those supported by the PIL module)
This call is blocking.
sizeMethod (integer): determines how the pictures will be resized/cropped
to fit the thumbnail size.
0 = fit whole picture,keep ratio
1 = fit smaller edge and crop largest,keep ratio
2 = fit,do not keep ratio
'''
self._logInfo("Generating image and saving to %s" %
destinationFilename)
finalImage = Image.new(
'RGB', (self.CONfig["assembler.sizex"], self.CONfig["assembler.sizey"]))
imageSizeX = self.CONfig["assembler.sizex"] // self.nbX
imageSizeY = self.CONfig["assembler.sizex"] // self.nbY
for y in range(self.nbY):
for x in range(self.nbX):
image = self.pool.getimageB()
if image.mode != 'RGB':
image = image.convert('RGB')
if resizeMethod == 1:
image = ImageOps.fit(image, size=(
imageSizeX, imageSizeY), method=Image.ANTIALIAS, bleed=0, centering=(0.5, 0.5))
if resizeMethod == 2:
image = image.resize(
(imageSizeX, Image.ANTIALIAS)
else:
image.thumbnail((imageSizeX, Image.ANTIALIAS)
finalImage.paste(image, (x * imageSizeX, y * imageSizeY))
if self.CONfig["assembler.mirror"]:
finalImage = ImageOps.mirror(finalImage)
if self.CONfig["assembler.emboss"]:
finalimage_embossed = finalImage.filter(
ImageFilter.embosS).filter(ImageFilter.SMOOTH) # emboss image
finalImage = ImageOps.equalize(ImageChops.multiply(
finalImage, finalimage_embossed)) # Compose images
if self.CONfig["assembler.invert"]:
finalImage = ImageOps.invert(finalImage)
finalImage.save(destinationFilename)
self._logInfo("Done.")
def _loadPrevIoUsImage(self, ignorePrevIoUsImage=False):
''' Try to get persisted image (image from prevIoUs run of program)
(file to self.currentimage)
Input:
ignorePrevIoUsImage (boolean) : If True,will ignore prevIoUs image and start a new from scratch.
'''
try:
if ignorePrevIoUsImage:
raise IOError # Force to create a new image.
self.currentimage = Image.open(os.path.join(
self.CONfig["persistencedirectory"], "assembler_superpose_current.bmp"))
# If the image does not have the same size,resize it.
(imagex, imagey) = self.currentimage.size
if (imagex != self.CONfig["assembler.sizex"]) or (imagey != self.CONfig["assembler.sizey"]):
if self.currentimage.mode != 'RGB':
self.currentimage = self.currentimage.convert('RGB')
self.currentimage = self.currentimage.resize(
(self.CONfig["assembler.sizex"], self.CONfig["assembler.sizey"]), Image.ANTIALIAS)
self._logDebug("Starting from prevIoUs image resized.")
else:
self._logDebug("Starting from prevIoUs image.")
except IOError:
# Could not read image,create a new one.
self.currentimage = Image.new(
'RGB', self.CONfig["assembler.sizey"]))
# Before the first images are superposed,we display "Please wait while the first images are downloaded..."
# self.currentimage.paste(PLEASE_WAIT_IMAGE,(self.CONfig["assembler.sizex"]/2-PLEASE_WAIT_IMAGE.size[0]/2,self.CONfig["assembler.sizey"]/2-PLEASE_WAIT_IMAGE.size[1]/2+20))
self.currentimage.paste(PLEASE_WAIT_IMAGE, (30, 30))
self._logDebug("Starting a new image.")
# Tell the superpose method to blank image when starting to superpose
# (in order to remove the "Please wait while.." message.)
self.blankImage = True
# Prepare image for output so that it's immediately available.
finalImage = self._postProcessImage(self.currentimage)
self.finalImageLock.acquire()
self.finalImage = finalImage
self.finalImageCompletionDate = time.time()
self.finalImageLock.release()
# --------------------------------------------------------------------------
# Public methods:
def fillBmp(self, path = "/usr/local/mindsensors/images/Pane1.png",y)
# if the caller only provided icon name,assume it is in our system repository
if (path[0] != "/"):
path = "/usr/local/mindsensors/images/" + path
# if the image is missing,use a default X image.
if (os.path.isfile(path)):
image = Image.open(path)
else:
image = Image.open("/usr/local/mindsensors/images/missing.png")
image = image.resize((width,acty))
if(display):
self.disp.display()
## Draw a image on the screen using supplied image data
# @param self The object pointer.
# @param x The upper left x coordinate of the image.
# @param y The upper left y coordinate of the image.
# @param width The width of the image.
# @param height The width of the image.
# @param image data
# @param display Choose to immediately push the drawing to the screen. Optional,defaults to True.
# @remark
# To use this function in your program:
# @code
# ...
# screen.screen.fillBmp(40,240,image)
# @endcode