def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0, opacity=100, include_image=True): if not has_transparency(image): return put_border(image, size, offset, contour_color, fill_color, opacity, include_image) image = image.convert('RGBA') mask = imtools.get_alpha(image) w, h = image.size outer_mask = mask.resize( (w + 2 * (size + offset), h + 2 * (size + offset)), Image.ANTIALIAS) inner_mask = mask.resize((w + 2 * offset, h + 2 * offset), Image.ANTIALIAS) inner_mask = ImageOps.expand(inner_mask, border=size, fill=0) paste(outer_mask, (255 * opacity) / 100, mask=inner_mask) if include_image: image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0)) mask = ImageOps.expand(mask, border=size + offset, fill=0) paste(outer_mask, 255, mask=mask) contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color) paste(contour, fill_color, mask=inner_mask) if include_image: paste(contour, image, mask=image) contour.putalpha(outer_mask) return contour
def load_image(self, idx): filename = self.X[idx] import Image import ImageOps # print "loading ", self.X[idx] image = Image.open(self.X[idx]) width, height = image.size if width > height: delta2 = int((width - height)/2) image = ImageOps.expand(image, border=(0, delta2, 0, delta2)) else: delta2 = int((height - width)/2) image = ImageOps.expand(image, border=(delta2, 0, delta2, 0)) image = image.resize((self.width, self.width), resample=Image.BICUBIC) try: imagenp = np.array(image.getdata()).reshape((self.width,self.width,3)) imagenp = imagenp.transpose((2,0,1)) # move color channels to beginning except: # print "reshape failure (black and white?)" imagenp = self.load_image(np.random.randint(len(self.X))) return imagenp.astype(theano.config.floatX)
def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0, opacity=100, include_image=True): if not has_transparency(image): return put_border( image, size, offset, contour_color, fill_color, opacity, include_image) image = image.convert('RGBA') mask = imtools.get_alpha(image) w, h = image.size outer_mask = mask.resize( (w + 2 * (size + offset), h + 2 * (size + offset)), Image.ANTIALIAS) inner_mask = mask.resize( (w + 2 * offset, h + 2 * offset), Image.ANTIALIAS) inner_mask = ImageOps.expand(inner_mask, border=size, fill=0) paste(outer_mask, (255 * opacity) / 100, mask=inner_mask) if include_image: image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0)) mask = ImageOps.expand(mask, border=size + offset, fill=0) paste(outer_mask, 255, mask=mask) contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color) paste(contour, fill_color, mask=inner_mask) if include_image: paste(contour, image, mask=image) contour.putalpha(outer_mask) return contour
def make_image_square(image, img_sz, outfile=None, overwrite=False): """ Will resize an image. Parameters ---------- image : Image.Image or str The image to transform. If str it is interpreted to be a path. img_sz : int New size for that image. Returns ------- image : Image.image The transformed image. """ if isinstance(image, basestring): image = Image.open(image) #NEAREST, BILINEAR, BICUBIC, ANTIALIAS #image = image.resize((img_sz, img_sz), resample=Image.BICUBIC) width, height = image.size if width > height: delta2 = int((width - height)/2) image = ImageOps.expand(image, border=(0, delta2, 0, delta2)) else: delta2 = int((height - width)/2) image = ImageOps.expand(image, border=(delta2, 0, delta2, 0)) image = image.resize((img_sz, img_sz), resample=Image.BICUBIC) if not outfile is None: if image.mode == 'P': fbase, ext = os.path.splitext(outfile) if ext == '.jpg' or ext == '.jpeg': orig_out = outfile outfile = '%s.png' % fbase logging.info('%s renamed to %s because jpg ' 'does not support palletes', orig_out, outfile) if os.path.isfile(outfile): if not overwrite: logging.info('%s exists; skipping', outfile) return image orig_out = outfile for ext in ('%s.png', '%s.jpg', '%s.bmp', '%s.tiff', '%s'): try: image.save(outfile) break except (KeyError, IOError): fbase, old_ext = os.path.splitext(outfile) outfile = ext % fbase if ext == '%s': logging.error('unable to save %s', orig_out) return image
def draw_histogram(pixbuf, height=170, fill=170, text=True): """Draw a histogram from <pixbuf> and return it as another pixbuf. The returned prixbuf will be 262x<height> px. The value of <fill> determines the colour intensity of the filled graphs, valid values are between 0 and 255. If <text> is True a label with the maximum pixel value will be added to one corner. """ im = Image.new('RGB', (258, height - 4), (30, 30, 30)) hist_data = image.pixbuf_to_pil(pixbuf).histogram() maximum = max(hist_data[:768] + [1]) y_scale = float(height - 6) / maximum r = [int(hist_data[n] * y_scale) for n in xrange(256)] g = [int(hist_data[n] * y_scale) for n in xrange(256, 512)] b = [int(hist_data[n] * y_scale) for n in xrange(512, 768)] im_data = im.getdata() # Draw the filling colours for x in xrange(256): for y in xrange(1, max(r[x], g[x], b[x]) + 1): r_px = y <= r[x] and fill or 0 g_px = y <= g[x] and fill or 0 b_px = y <= b[x] and fill or 0 im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, b_px)) # Draw the outlines for x in xrange(1, 256): for y in range(r[x-1] + 1, r[x] + 1) + [r[x]] * (r[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (255, g_px, b_px)) for y in range(r[x] + 1, r[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (255, g_px, b_px)) for y in range(g[x-1] + 1, g[x] + 1) + [g[x]] * (g[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, 255, b_px)) for y in range(g[x] + 1, g[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, 255, b_px)) for y in range(b[x-1] + 1, b[x] + 1) + [b[x]] * (b[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, 255)) for y in range(b[x] + 1, b[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, g_px, 255)) if text: maxstr = 'max: ' + str(maximum) draw = ImageDraw.Draw(im) draw.rectangle((0, 0, len(maxstr) * 6 + 2, 10), fill=(30, 30, 30)) draw.text((2, 0), maxstr, fill=(255, 255, 255)) im = ImageOps.expand(im, 1, (80, 80, 80)) im = ImageOps.expand(im, 1, (0, 0, 0)) return image.pil_to_pixbuf(im)
def draw_histogram(pixbuf, height=170, fill=170, text=True): """Draw a histogram from <pixbuf> and return it as another pixbuf. The returned prixbuf will be 262x<height> px. The value of <fill> determines the colour intensity of the filled graphs, valid values are between 0 and 255. If <text> is True a label with the maximum pixel value will be added to one corner. """ im = Image.new('RGB', (258, height - 4), (30, 30, 30)) hist_data = image.pixbuf_to_pil(pixbuf).histogram() maximum = max(hist_data[:768] + [1]) y_scale = float(height - 6) / maximum r = [int(hist_data[n] * y_scale) for n in xrange(256)] g = [int(hist_data[n] * y_scale) for n in xrange(256, 512)] b = [int(hist_data[n] * y_scale) for n in xrange(512, 768)] im_data = im.getdata() # Draw the filling colours for x in xrange(256): for y in xrange(1, max(r[x], g[x], b[x]) + 1): r_px = y <= r[x] and fill or 0 g_px = y <= g[x] and fill or 0 b_px = y <= b[x] and fill or 0 im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, b_px)) # Draw the outlines for x in xrange(1, 256): for y in range(r[x-1] + 1, r[x] + 1) + [r[x]] * (r[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (255, g_px, b_px)) for y in range(r[x] + 1, r[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (255, g_px, b_px)) for y in range(g[x-1] + 1, g[x] + 1) + [g[x]] * (g[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, 255, b_px)) for y in range(g[x] + 1, g[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, 255, b_px)) for y in range(b[x-1] + 1, b[x] + 1) + [b[x]] * (b[x] != 0): r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y)) im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, 255)) for y in range(b[x] + 1, b[x-1] + 1): r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y)) im_data.putpixel((x, height - 5 - y), (r_px, g_px, 255)) if text: maxstr = 'max: ' + str(maximum) draw = ImageDraw.Draw(im) draw.rectangle((0, 0, len(maxstr) * 6 + 2, 10), fill=(30, 30, 30)) draw.text((2, 0), maxstr, fill=(255, 255, 255)) im = ImageOps.expand(im, 1, (80, 80, 80)) im = ImageOps.expand(im, 1, (0, 0, 0)) return image.pil_to_pixbuf(im)
def put_border(image, size, offset, contour_color, fill_color, opacity, include_image): if opacity < 100: fill_color = HTMLColorToRGBA(fill_color, (255 * opacity) / 100) if not include_image: w, h = image.size image = Image.new('RGBA', (w + 2 * offset, h + 2 * offset), fill_color) else: image = image.convert('RGBA') image = ImageOps.expand(image, border=offset, fill=fill_color) image = ImageOps.expand(image, border=size, fill=contour_color) return image
def put_border(image, size, offset, contour_color, fill_color, opacity, include_image): if opacity < 100: fill_color = HTMLColorToRGBA(fill_color, (255 * opacity) / 100) if not include_image: w, h = image.size image = Image.new('RGBA', (w + 2 * offset, h + 2 * offset), fill_color) else: image = image.convert('RGBA') image = ImageOps.expand(image, border=offset, fill=fill_color) image = ImageOps.expand(image, border=size, fill=contour_color) return image
def update_preview(self, *args): self.im_cropped = self.im_source.crop((self.adj_x1.value,self.adj_y1.value,\ self.adj_x2.value,self.adj_y2.value)) prev = self.im_cropped prev = ImageOps.expand(prev, border=10, fill=(208, 32, 144)) self.image2.set_from_pixbuf(Image_to_GdkPixbuf(prev))
def img_from_tex(tex, font_size=20): figure = matplotlib.figure.Figure(None, facecolor='white') #canvas = matplotlib.backends.backend_wxagg.FigureCanvasWxAgg(None, -1, figure) canvas = matplotlib.backends.backend_wxagg.FigureCanvasAgg(figure) font_size = font_size tex = "${0}$".format(tex) figure.clear() figure.text(0.05, 0.5, tex, size=font_size) canvas.draw() filename = 'equ.png' figure.savefig(filename, dpi=600) img = Image.open(filename) imginv = ImageChops.invert(img.convert('L')) box = imginv.getbbox() img = img.crop(box) img = ImageOps.expand(img, border=10, fill=(255, 255, 255)) img.save(filename) return img
def OnSaveToFileBtn(self, event): if not self.math_panel.renderError: filename = 'equ.png' self.math_panel.figure.savefig(filename, dpi=300) pilImg = Image.open(filename) # Find the ordinates of the minimally enclosing bounding box. # # Create a simplified and inverted version of the original image to examine. invertedImage = ImageChops.invert(pilImg.convert('L')) # Get the bounding box's ordinates. Works on any image with a black background. box = invertedImage.getbbox() pilImg = pilImg.crop(box) # Add back a thin border padding pilImg = ImageOps.expand(pilImg, border=10, fill=(255, 255, 255)) # Save the image to a disk file. Only PNG and TIFF formats are non-destructive. pilImg.save(filename) else: pass
def main(): numpy.set_printoptions(threshold=numpy.nan) # Open the image img = Image.open(sys.argv[1]) # Threshold the image img = img.convert('L') img = ImageOps.expand(img, border=1, fill='white') img = numpy.array(img) img = binarize(img) """ img = [ [0,0,0,0,0,0,0,0,0,0], [0,1,1,0,1,1,1,0,1,0], [0,1,1,0,1,0,1,0,1,0], [0,1,1,1,1,0,0,0,1,0], [0,0,0,0,0,0,0,0,1,0], [0,1,1,1,1,0,1,0,1,0], [0,0,0,0,1,0,1,0,1,0], [0,1,1,1,1,0,0,0,1,0], [0,1,1,1,1,0,1,1,1,0], [0,0,0,0,0,0,0,0,0,0]] """ img = ccl4(img) # Colour the image using labels coloured_img = colourize(img) # Show the coloured image coloured_img.show()
def tex2img(tex, filename="equ.png", font_size=20): font_size = 20 figure = matplotlib.figure.Figure(None, facecolor=(0, 0, 0, 0)) canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(figure) font_size = font_size tex = "${0}$".format(tex) figure.clear() figure.text(0.05, 0.5, tex, size=font_size) canvas.draw() png = "equ.png" figure.savefig(png, transparent=True, dpi=300, format="png") img = Image.open(png) imginv = ImageChops.invert(img.convert('L')) box = imginv.getbbox() img = img.crop(box) img = ImageOps.expand(img, border=10, fill=(255, 255, 255, 0)) img.save(png, format="png") return img
def update_preview(self,*args): self.im_cropped = self.im_source.crop((self.adj_x1.value,self.adj_y1.value,\ self.adj_x2.value,self.adj_y2.value)) prev = self.im_cropped prev = ImageOps.expand(prev, border=10, fill=(208,32,144)) self.image2.set_from_pixbuf(Image_to_GdkPixbuf(prev))
def resizeForPrinter(self,img): width,height=img.size if width>384: img=img.crop(((width/2)-(height/2),0,(width/2)+(height/2),height)) img = ImageOps.expand(img,border=5,fill='white') img=img.resize((384,384)) return img
def dynamicBanner(request, serverid): """ Create dynamic banner """ # variables info = Server.objects.get(pk=serverid) servername = str(info.name).upper() address = str(info.ip).upper() port = str(info.port).upper() online = str("Online").upper() offline = str("Offline").upper() players = str(info.players) maxplayers = str(info.maxplayers) text = str("Players online.").upper() #loading minotar head fd = urllib.urlopen("https://minotar.net/avatar/" + info.owner + "/30") head = cStringIO.StringIO(fd.read()) # image setup + creation im = Image.open(STATIC_ROOT + "/images/serverbanner.png") im2 = Image.open(head) ImageOps.expand(im2,border=5, fill=(255,255,255)) im.paste(im2,(300,5)) draw = ImageDraw.Draw(im) # image text + options font = ImageFont.truetype(STATIC_ROOT + "/images/heavy_dock11.otf", 15) upfont = ImageFont.truetype(STATIC_ROOT + "/images/heavy_dock11.otf", 30) colour = (255, 255, 255) draw.text((5, 0), servername, font=font, fill=colour) draw.text((5, 45), address + ":" + port, font=font, fill=colour) if info.online == True: draw.text((350, 10), online, font=upfont, fill=(0, 255, 0)) draw.text((5, 30), players + "/" + maxplayers + " " + text , font=font, fill=colour) else: draw.text((340, 10), offline, font=upfont, fill=(255, 0, 0)) draw.text((5, 30), '0' + "/" + '0' + " " + text , font=font, fill=colour) # rendering for response in browser response = HttpResponse(mimetype="image/png") im.save(response, "PNG") return response
def faiesalva(urlo, i): URL = goo_shorten_url(urlo) qr = QRCode(version=1, error_correction=ERROR_CORRECT_H, box_size=20) qr.add_data(URL) qr.make() im = qr.make_image() im = ImageOps.expand(im,border=(0,50,0,80),fill='white') draw = ImageDraw.Draw(im) lines = textwrap.wrap(URL, width = 41) y_text = 760 for line in lines: width, height = font.getsize(line) draw.text((80, y_text), line, font = font, fill = 'black') y_text += height im = ImageOps.expand(im,border=(0,0,2,2),fill='black') im.save("%s/%d.png" %(outdir, i))
def generate_thumbnail(self, im, size, file_name): if size in [50, 25]: # ensure that perfect squares: im.thumbnail((size * 2, size * 2), Image.ANTIALIAS) im = im.crop([0, 0, size - 2, size - 2]) # for some reason, ImageOps.expand throws an error # for some files: im = ImageOps.expand(im, border=2, fill=(255, 255, 255, 255)) else: im.thumbnail((size, size), Image.ANTIALIAS) return self.pil_to_django_file(im, file_name)
def generate_thumbnail(self, im, size, file_name): if size in [50, 25]: # ensure that perfect squares: im.thumbnail((size * 2, size * 2), Image.ANTIALIAS) im = im.crop([0, 0, size - 2, size - 2]) # for some reason, ImageOps.expand throws an error # for some files: im = ImageOps.expand(im, border=2, fill=(255, 255, 255, 255)) else: im.thumbnail((size, size), Image.ANTIALIAS) return self.pil_to_django_file(im, file_name)
def outliner(orig_image): orig_data = orig_image.load() image = ImageOps.expand(orig_image, 1, 255) polygons = [] ds = [(1,0), (0,1), (-1,0), (0,-1)] ns = [(0,0), (-1,0), (-1,-1), (0,-1)] data = image.load() while True: polygon = [] d = 0 (px, py) = find_first(image) if (px, py) == (-1, -1): # no more black pixels, terminate return polygons polygon.append((px, py)) done = False while not done: (x,y) = map(sum, zip((px,py),ns[d])) (x1,y1) = map(sum, zip((px,py),ns[(d+3)%4])) nextr = data[x,y] nextl = data[x1,y1] if nextl == nextr: polygon.append((px,py)) if nextr > 0: # both white, turn right d = (d+1)%4 else: # both black, turn left d = (d+3)%4 (px,py) = map(sum, zip((px,py),ds[d])) else: if nextl > 0: # left white, right black - go straight (px,py) = map(sum, zip((px,py),ds[d])) # dont append else: # turning dilemma, go ... left polygon.append((px, py)) d = (d+3)%4 (px,py) = map(sum, zip((px,py),ds[d])) if (px, py) == polygon[0]: done = True invert_pixels(image, polygon) polygons.append([tuple(map(sum, zip(x,(-1,-1)))) for x in polygon])
def generate_barcode(input_string, tempdir): ean = barcode.get("UPCA") # select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file. # dpi is the conversion from svg image size in mm, to what the image writer thinks is inches. options = { 'dpi': 130, 'module_height': 5.0, 'text_distance': 1, 'font_size': 6, 'quiet_zone': 2 } # ean.default_writer_options['dpi'] = int(130) # # module height is the barcode bar height in mm # ean.default_writer_options['module_height'] = float(5) # # text distance is the distance between the bottom of the barcode, and the top of the text in mm # ean.default_writer_options['text_distance'] = 1 # # font size is the text size in pt # ean.default_writer_options['font_size'] = int(6) # # quiet zone is the distance from the ends of the barcode to the ends of the image in mm # ean.default_writer_options['quiet_zone'] = 2 # save barcode image with generated filename print("generating barcode image") with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file: ean(input_string, writer=ImageWriter()).write(initial_temp_file, options=options) filename = initial_temp_file.name print(filename) print("success, barcode image path is: " + filename) print("opening " + str(filename) + " to add border") barcode_image = pil_Image.open( str(filename)) # open image as pil object print("success") print("adding barcode and saving") img_save = pil_ImageOps.expand(barcode_image, border=0, fill='white') # add border around image width, height = img_save.size # get image size of barcode with border # write out image to file with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path: img_save.save(final_barcode_path.name) print("success, final barcode path is: " + final_barcode_path.name) return final_barcode_path.name, width, height
def OnSaveToFileBtn( self, event ) : if not self.math_panel.renderError : filename = 'Rendered_Equation.png' self.math_panel.figure.savefig( filename, dpi=300 ) print('\n---- Equation Graphic Saved to File [ %s ]' % filename) # See if the PIL package is installed. pilIsInstalled = True try : # Try to crop the image to its near-minimum extent. import Image # PIL (Python Image Library) import ImageChops # Image Channel Operations library import ImageStat # Image Statistics library import ImageOps # Various whole image operations. except : pilIsInstalled = False # Image will not get auto-cropped. #end try if pilIsInstalled : # Auto-crop the image. pilImg = Image.open( filename ) # Find the ordinates of the minimally enclosing bounding box. # # Create a simplified and inverted version of the original image to examine. invertedImage = ImageChops.invert( pilImg.convert( 'L' ) ) # BG must be black to examine. # Get the bounding box's ordinates. Works on any image with a black background. box = invertedImage.getbbox() pilImg = pilImg.crop( box ) # Add back a thin border padding. This is arbitrary, but seems reasonable. pilImg = ImageOps.expand( pilImg, border=10, fill=(255, 255, 255) ) # Save the image to a disk file. Only PNG and TIFF formats are non-destructive. pilImg.save( filename ) print(' Cropped Equation Graphic Saved') #end if else : print('\n---- Tex Rendering Error: Figure Image NOT SAVED to a File.')
def download_and_collage(self,imgsrc_list): #empty the temp path folder self.delete_images() #collage image object collage = Image.new('RGB',(self.collage_width, self.collage_height)) #calculate the number of images that fit horizontally effective_img_width = 192 + self.image_border*2 no_of_columns = (self.collage_width / effective_img_width) col_index = [0]*no_of_columns print "Downloading and creating collage[", #status bar for i,each in enumerate(imgsrc_list): print ".", #status bar update #fetch the image from the list img_fn = os.path.join(self.path, str(i)+".jpg") urllib.urlretrieve(each, img_fn) orig_img = Image.open(img_fn) #add border to it bordered_img = ImageOps.expand(orig_img, border=self.image_border, fill=self.image_border_color) width, height = bordered_img.size collage.paste(bordered_img, ((i%no_of_columns)*width, col_index[i%no_of_columns])) col_index[i%no_of_columns] += height print "]"#status bar end #insert Pintrest logo on the top left conrner pinterest_logo = Image.open(os.path.abspath('./pinterest_logo.png')) collage.paste(pinterest_logo,(0,0), mask=pinterest_logo) #output the collage collage_fn = os.path.join(self.path, 'collage.jpg') collage.save(collage_fn) return collage_fn
screenshot1 = photos.pick_image(show_albums=True) screenshot2 = photos.pick_image(show_albums=True) screenshot3 = photos.pick_image(show_albums=True) mode = console.alert('Create or Clean', 'Select a mode below.', 'Create Now', 'Clean First') if mode == 2: from Cleanbar import cleanbar cleanbar(screenshot1) cleanbar(screenshot2) cleanbar(screenshot3) # Creates final image console.clear() print "Creating final image..." background = Image.new('RGBA', (1850,1275), (255, 255, 255, 255)) file1 = screenshot1.resize((545,969),Image.ANTIALIAS) file2 = screenshot2.resize((700,1245),Image.ANTIALIAS) file3 = screenshot3.resize((545,969),Image.ANTIALIAS) file1 = ImageOps.expand(file1,border=1,fill='gray') file2 = ImageOps.expand(file2,border=1,fill='gray') file3 = ImageOps.expand(file3,border=1,fill='gray') background.paste(file1,(10,138)) background.paste(file2,(575,15)) background.paste(file3,(1295,138)) console.hide_activity() background.show() print "\n\n Image created"
#input argument check if (len(sys.argv) != 2): print "Usage: python bmp2array.py <Image.bmp>" sys.exit(1) else: inputImage = Image.open(sys.argv[1],'r') #convert the image to gray scale image, 8 bit per pixel inputImage = inputImage.convert('L') #resize the image to 512 by 512 pixels inputImage = inputImage.resize((512,512),Image.ANTIALIAS) #create 4-pixel border inputImage = ImageOps.expand(inputImage,border=4,fill='black') #convert image to pixel array imageArray = numpy.array(inputImage) #inputArray = open('inputArray','w') #inputArray.write(imageArray) #inputArray.close() #open the pixel array file to write to outputArray = open('pixelArray','w') row_number = 0
def border(original_image): original_image = ImageOps.expand(original_image, border=45) original_image.save('test_overlay.png')
def do_process_workbook(): # this is called as a background thread to ensure the interface is responsive print_if_debug("creating temp directory") if not args.keep_barcodes_in_cwd: tempdir = tempfile.mkdtemp() else: temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images') os.mkdir(temp_dir_in_cwd) tempdir = temp_dir_in_cwd print_if_debug("temp directory created as: " + tempdir) progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text="opening workbook") wb = openpyxl.load_workbook(old_workbook_path) ws = wb.worksheets[0] progress_numbers.configure(text="testing workbook save") wb.save(new_workbook_path) count = 0 save_counter = 0 progress_bar.configure(maximum=ws.max_row, value=count) progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) border_size = int(border_spinbox.get()) for _ in ws.iter_rows(): # iterate over all rows in current worksheet if not process_workbook_keep_alive: break try: count += 1 progress_bar.configure(maximum=ws.max_row, value=count, mode='determinate') progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) progress_bar.configure(value=count) # get code from column selected in input_colum_spinbox, on current row, # add a zeroes to the end if option is selected to make seven or 12 digits print_if_debug("getting cell contents on line number " + str(count)) upc_barcode_string = str(ws[input_column_spinbox.get() + str(count)].value) print_if_debug("cell contents are: " + upc_barcode_string) if not upc_barcode_string == '': if barcode_type_variable.get() == "ean13" or barcode_type_variable.get() == "ean8": try: _ = int(upc_barcode_string) # check that "upc_barcode_string" can be cast to int except ValueError: raise ValueError("Cell contents are not an integer, skipping") # select barcode type, specify barcode, and select image writer to save as png if barcode_type_variable.get() == "ean8": if pad_ean_option.get() is True: if len(upc_barcode_string) < 6: upc_barcode_string = upc_barcode_string.rjust(6, '0') if len(upc_barcode_string) <= 7: upc_barcode_string = upc_barcode_string.ljust(7, '0') else: raise ValueError("Cell contents are more than 7 characters, skipping row") else: if len(upc_barcode_string) != 7: raise ValueError("Cell contents are not 7 characters, skipping row") elif barcode_type_variable.get() == "ean13": if pad_ean_option.get() is True: if len(upc_barcode_string) < 11: upc_barcode_string = upc_barcode_string.rjust(11, '0') if len(upc_barcode_string) <= 12: upc_barcode_string = upc_barcode_string.ljust(12, '0') else: raise ValueError("Cell contents are more than 12 characters, skipping row") else: if len(upc_barcode_string) != 12: raise ValueError("Cell contents are not 12 characters, skipping row") elif barcode_type_variable.get() == "code39": upc_barcode_string = upc_barcode_string.upper() upc_barcode_string = re.sub('[^A-Z0-9./*$%+\- ]+', ' ', upc_barcode_string) else: raise ValueError("Cell is empty, skipping row") ean = barcode.get(barcode_type_variable.get(), upc_barcode_string, writer=ImageWriter()) # select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file. # dpi is the conversion from svg image size in mm, to what the image writer thinks is inches. ean.default_writer_options['dpi'] = int(dpi_spinbox.get()) # module height is the barcode bar height in mm ean.default_writer_options['module_height'] = float(height_spinbox.get()) # text distance is the distance between the bottom of the barcode, and the top of the text in mm ean.default_writer_options['text_distance'] = 1 # font size is the text size in pt ean.default_writer_options['font_size'] = int(font_size_spinbox.get()) # quiet zone is the distance from the ends of the barcode to the ends of the image in mm ean.default_writer_options['quiet_zone'] = 2 # save barcode image with generated filename print_if_debug("generating barcode image") with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file_path: filename = ean.save(initial_temp_file_path.name[0:-4]) print_if_debug("success, barcode image path is: " + filename) print_if_debug("opening " + str(filename) + " to add border") barcode_image = pil_Image.open(str(filename)) # open image as pil object print_if_debug("success") print_if_debug("adding barcode and saving") img_save = pil_ImageOps.expand(barcode_image, border=border_size, fill='white') # add border around image width, height = img_save.size # get image size of barcode with border # resize cell to size of image ws.column_dimensions[output_column_spinbox.get()].width = int(math.ceil(float(width) * .15)) ws.row_dimensions[count].height = int(math.ceil(float(height) * .75)) # write out image to file with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path: img_save.save(final_barcode_path.name) print_if_debug("success, final barcode path is: " + final_barcode_path.name) # open image with as openpyxl image object print_if_debug("opening " + final_barcode_path.name + " to insert into output spreadsheet") img = OpenPyXlImage(final_barcode_path.name) print_if_debug("success") # attach image to cell print_if_debug("adding image to cell") # add image to cell ws.add_image(img, anchor=output_column_spinbox.get() + str(count)) save_counter += 1 print_if_debug("success") except Exception as barcode_error: print_if_debug(barcode_error) # This save in the loop frees references to the barcode images, # so that python's garbage collector can clear them if save_counter >= file_limit - 50: print_if_debug("saving intermediate workbook to free file handles") progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text=str(count) + "/" + str(ws.max_row) + " saving") wb.save(new_workbook_path) print_if_debug("success") save_counter = 1 progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) progress_bar.configure(value=0) print_if_debug("saving workbook to file") progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text="saving") wb.save(new_workbook_path) print_if_debug("success") if not args.keep_barcode_files: print_if_debug("removing temp folder " + tempdir) shutil.rmtree(tempdir) print_if_debug("success")
def __init__(self, image): self.image = image.convert('RGBA') if self.any_translucent_pixels(): image = self.image background = Image.open(join(dirname(__file__), 'iconfade.png')) scale_w = int(background.size[0] * 0.70) w, h = background.size x = (w - scale_w) / 2 #alpha = alpha.filter(ImageFilter.BLUR) #image = ImageOps.expand(image, 2) alpha = image.split()[-1] #iw, ih = image.size #getpixel = alpha.getpixel #putpixel = alpha.putpixel #for ay in xrange(iw): # for ax in xrange(ih): # c = getpixel((ax, ay)) # if c: # putpixel((ax, ay), 255) # # #if c[-1]: # c = [i/255.0 for i in c] # r, g, b, a = c # r = a * r + 1.-a # g = a * g + 1.-a # b = a * b + 1.-a # a = 255 # alpha.putpixel((x, y), tuple(int(c*255.0) for c in (r, g, b, a))) alpha = alpha.resize((scale_w, scale_w), Image.BILINEAR) border_alpha = Image.new('L', (scale_w+40, scale_w+40)) border_alpha.paste(alpha, (20, 20)) alpha = border_alpha #alpha = ImageOps.expand(image, 20) alpha = alpha.filter(ImageFilter.MaxFilter(7)) alpha = alpha.filter(ImageFilter.MaxFilter(7)) alpha = alpha.filter(ImageFilter.BLUR) #alpha = alpha.filter(ImageFilter.SHARPEN) #alpha = ImageEnhance.Contrast(alpha).enhance(1.3) image = image.resize((scale_w, scale_w), Image.NEAREST) image = ImageOps.expand(image, 20) edge = Image.new('RGBA',alpha.size, (255, 255, 255, 0)) edge.putalpha(alpha) x = (background.size[0]-edge.size[0])/2 background.paste((255, 255, 255), (x, x), edge) background.paste(image, (x, x), image) #image.paste(alpha, None, alpha) #image.putalpha(alpha) #image.show() self.image = image #background = Image.open(join(dirname(__file__), 'iconfade.png')) #background.thumbnail(self.image.size) #background.paste(self.image, (x, x), self.image) self.image = background self.scan()
# Make sure we were handed something sane # FIXME: Future rev - deal with paths if len(sys.argv) < 2: print "Usage: python img.py filename.jpg" sys.exit(1) # Get set up source_filename = sys.argv[1] source_basename = source_filename.split('.')[0] source_image = Image.open(source_filename) font = ImageFont.truetype('Inconsolata.otf', 7) # Add our black border/frame framed_image = ImageOps.expand(source_image, border=border_size, fill='black') # Add our footer text # FIXME: That 90 is a magic number, figure it out later drawer = ImageDraw.Draw(framed_image) text_size = drawer.textsize(footer) drawer.text((framed_image.size[0]-text_size[0]+90, framed_image.size[1]-border_size), footer, font=font) # Save out the new image, in PNG format framed_image.save(source_basename + '.png', 'png') # Make the thumbnails - yes, I know, this is a proportional
def add_border(path, newpath): # print newpath image_file = Image.open(path) new_image_file = ImageOps.expand(image_file, border=2, fill='black') new_image_file.save(newpath)
bg_color=(np.array(bw.getdata()).mean(axis=0)) if color: bg_color=tuple(bg_color) mask=Image.new("RGB",(newsize,newsize),bg_color) else: mask=Image.new("L",(newsize,newsize),bg_color) x_noise= y_noise=0 for it in xrange(jitter_count): x0=(newsize-bw.size[0])/2+x_noise y0=(newsize-bw.size[1])/2+y_noise x1=x0+bw.size[0] y1=y0+bw.size[1] x = (x0,y0,x1,y1) offset=20 x_ = (x0+offset,y0+offset,x1+offset,y1+offset) mask=ImageOps.expand(mask,offset,fill=bg_color) mask.paste(bw,x_) for i in xrange(20): mask=mask.filter(ImageFilter.SMOOTH) mask.paste(bw,x_) mask=ImageOps.crop(mask,offset) newdata=np.array(mask.getdata()).T.flatten().copy() #mask.show() #pdb.set_trace() #plt.imshow(np.array(mask.getdata()).reshape(newsize,newsize,3)) #plt.show() data.append(newdata) labels.append(label) x_noise,y_noise=np.random.normal(0,5,2) x_noise=max(-20,min(x_noise,20)) y_noise=max(-20,min(y_noise,20))
import os import Image, ImageOps """ This parser requires ImageMagick (http://www.imagemagick.org/) library. You can install it by typing: sudo apt-get install imagemagick """ commands =[\ 'wget http://www.ini.uzh.ch/~acardona/data/membranes-neurites-glia.tif.tar.bz2 -O atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'bunzip2 -f atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'tar -xvvf atlases/tem/src/membranes-neurites-glia.tif.tar -C atlases/tem/src/', 'convert atlases/tem/src/membranes-neurites-glia.tif -level 0,255 -depth 8 -type grayscale atlases/tem/src/membranes-neurites-glia.png'] map(os.system, commands) for index in range(30): filename = 'atlases/tem/src/membranes-neurites-glia-%d.png' % index frame = Image.open(filename) frame = ImageOps.expand(frame, border=4, fill=168) frame.save(filename)
def add_frame(image): '''Add frame for image.''' im = ImageOps.expand(image, border=int(0.01 * max(image.size)), fill=0xffffff) return im
def add_frame(image): '''Add frame for image.''' im = ImageOps.expand(image, border=int(0.01 * max(image.size)), fill=0xffffff) return im
#input argument check if (len(sys.argv) != 2): print "Usage: python bmp2array.py <Image.bmp>" sys.exit(1) else: inputImage = Image.open(sys.argv[1], 'r') #convert the image to gray scale image, 8 bit per pixel inputImage = inputImage.convert('L') #resize the image to 512 by 512 pixels inputImage = inputImage.resize((512, 512), Image.ANTIALIAS) #create 4-pixel border inputImage = ImageOps.expand(inputImage, border=4, fill='black') #convert image to pixel array imageArray = numpy.array(inputImage) #inputArray = open('inputArray','w') #inputArray.write(imageArray) #inputArray.close() #open the pixel array file to write to outputArray = open('pixelArray', 'w') row_number = 0
def do_process_workbook(): print_if_debug("creating temp directory") if not args.keep_barcodes_in_home: tempdir = tempfile.mkdtemp() else: temp_dir_in_cwd = os.path.join(program_launch_cwd, 'barcode images') os.mkdir(temp_dir_in_cwd) tempdir = temp_dir_in_cwd print_if_debug("temp directory created as: " + tempdir) progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text="opening workbook") wb = openpyxl.load_workbook(old_workbook_path) ws = wb.worksheets[0] progress_numbers.configure(text="testing workbook save") wb.save(new_workbook_path) count = 0 save_counter = 0 progress_bar.configure(maximum=ws.max_row, value=count) progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) border_size = int(border_spinbox.get()) for _ in ws.iter_rows(): # iterate over all rows in current worksheet if not process_workbook_keep_alive: break try: count += 1 progress_bar.configure(maximum=ws.max_row, value=count, mode='determinate') progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) progress_bar.configure(value=count) # get code from column "B", on current row, add a zero to the end to make seven digits print_if_debug("getting cell contents on line number " + str(count)) upc_barcode_number = ws["B" + str(count)].value + "0" print_if_debug("cell contents are: " + upc_barcode_number) # select barcode type, specify barcode, and select image writer to save as png ean = barcode.get('ean8', upc_barcode_number, writer=ImageWriter()) # select output image size via dpi. internally, pybarcode renders as svg, then renders that as a png file. # dpi is the conversion from svg image size in mm, to what the image writer thinks is inches. ean.default_writer_options['dpi'] = int(dpi_spinbox.get()) # module height is the barcode bar height in mm ean.default_writer_options['module_height'] = float(height_spinbox.get()) # text distance is the distance between the bottom of the barcode, and the top of the text in mm ean.default_writer_options['text_distance'] = 1 # font size is the text size in pt ean.default_writer_options['font_size'] = int(font_size_spinbox.get()) # quiet zone is the distance from the ends of the barcode to the ends of the image in mm ean.default_writer_options['quiet_zone'] = 2 # save barcode image with generated filename print_if_debug("generating barcode image") with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as initial_temp_file_path: filename = ean.save(initial_temp_file_path.name[0:-4]) print_if_debug("success, barcode image path is: " + filename) print_if_debug("opening " + str(filename) + " to add border") barcode_image = pil_Image.open(str(filename)) # open image as pil object print_if_debug("success") print_if_debug("adding barcode and saving") img_save = pil_ImageOps.expand(barcode_image, border=border_size, fill='white') # add border around image width, height = img_save.size # get image size of barcode with border # resize cell to size of image ws.column_dimensions['A'].width = int(math.ceil(float(width) * .15)) ws.row_dimensions[count].height = int(math.ceil(float(height) * .75)) # write out image to file with tempfile.NamedTemporaryFile(dir=tempdir, suffix='.png', delete=False) as final_barcode_path: img_save.save(final_barcode_path.name) print_if_debug("success, final barcode path is: " + final_barcode_path.name) # open image with as openpyxl image object print_if_debug("opening " + final_barcode_path.name + " to insert into output spreadsheet") img = OpenPyXlImage(final_barcode_path.name) print_if_debug("success") # attach image to cell print_if_debug("adding image to cell") img.anchor(ws.cell('A' + str(count)), anchortype='oneCell') # add image to cell ws.add_image(img) save_counter += 1 print_if_debug("success") # This save in the loop frees references to the barcode images, # so that python's garbage collector can clear them except Exception as barcode_error: print_if_debug(barcode_error) if save_counter >= file_limit - 50: print_if_debug("saving intermediate workbook to free file handles") progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text=str(count) + "/" + str(ws.max_row) + " saving") wb.save(new_workbook_path) print_if_debug("success") save_counter = 1 progress_numbers.configure(text=str(count) + "/" + str(ws.max_row)) progress_bar.configure(value=0) print_if_debug("saving workbook to file") progress_bar.configure(mode='indeterminate', maximum=100) progress_bar.start() progress_numbers.configure(text="saving") wb.save(new_workbook_path) print_if_debug("success") if not args.keep_barcode_files: print_if_debug("removing temp folder " + tempdir) shutil.rmtree(tempdir) print_if_debug("success") progress_bar.stop() progress_bar.configure(maximum=100, value=0, mode='determinate') progress_numbers.configure(text="")
img.putpixel([w,h], not b[a]) a += 1 c = 0 # TODO: fix this (eof) ''' for i in range(8): if w >= a4_width: w = 0 h += 1 img.putpixel([w+i,h], 0) ''' # add border img = ImageOps.expand(img,border=2,fill="white") img = ImageOps.expand(img,border=2,fill="black") # move to bigger canvas out = Image.new("1", (a4_width+4,a4_height+8+12), "white") out.paste(img, (0,0)) # add text drw = ImageDraw.Draw(out) drw.text( (5, a4_height+7), "File: %s, page: %i/%i, file size: %i B, " \ "page size: %i B, interval: %i, est. ppi: %i, width: %ipx, height: %ipx." \ % (filename, p + 1, pages, len(b)/8, a/8, interval, ppi, a4_width, a4_height) ) out.save("out" + str(p) + ".bmp") print("Page %s saved to: out%s.bmp." % (str(p+1), str(p)))
import os import Image, ImageOps """ This parser requires ImageMagick (http://www.imagemagick.org/) library. You can install it by typing: sudo apt-get install imagemagick """ commands =[\ 'wget http://www.ini.uzh.ch/~acardona/data/membranes-neurites-glia.tif.tar.bz2 -O atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'bunzip2 -f atlases/tem/src/membranes-neurites-glia.tif.tar.bz2', 'tar -xvvf atlases/tem/src/membranes-neurites-glia.tif.tar -C atlases/tem/src/', 'convert atlases/tem/src/membranes-neurites-glia.tif -level 0,255 -depth 8 -type grayscale atlases/tem/src/membranes-neurites-glia.png'] map(os.system, commands) for index in range(30): filename = 'atlases/tem/src/membranes-neurites-glia-%d.png' % index frame = Image.open(filename) frame = ImageOps.expand(frame, border=4, fill=168) frame.save(filename)
def rotate(image_path, degrees_to_rotate, saved_location): image_obj = Image.open(image_path) rotated_image = image_obj.rotate(degrees_to_rotate) rotated_image.save(saved_location) rotated_image.show() image = Image.open('test.jpg') image = 'test.jpg' rotate(image, 90, 'rotated_mantis.jpg') def flip_image(image_path, saved_location): image_obj = Image.open(image_path) rotated_image = image_obj.transpose(Image.FLIP_LEFT_RIGHT) rotated_image.save(saved_location) rotated_image.show() image = 'flipped_2_mantis.jpg' flip_image(image, 'test_2.jpg') rotate(image, 10, 'rotated_10.jpg') import Image, ImageOps img = Image.open('rotated_5.jpg') img_with_border = ImageOps.expand(img,border=300,fill='black') img_with_border.save('imaged-with-border.jpg')
bg_color = (np.array(bw.getdata()).mean(axis=0)) if color: bg_color = tuple(bg_color) mask = Image.new("RGB", (newsize, newsize), bg_color) else: mask = Image.new("L", (newsize, newsize), bg_color) x_noise = y_noise = 0 for it in xrange(jitter_count): x0 = (newsize - bw.size[0]) / 2 + x_noise y0 = (newsize - bw.size[1]) / 2 + y_noise x1 = x0 + bw.size[0] y1 = y0 + bw.size[1] x = (x0, y0, x1, y1) offset = 20 x_ = (x0 + offset, y0 + offset, x1 + offset, y1 + offset) mask = ImageOps.expand(mask, offset, fill=bg_color) mask.paste(bw, x_) for i in xrange(20): mask = mask.filter(ImageFilter.SMOOTH) mask.paste(bw, x_) mask = ImageOps.crop(mask, offset) newdata = np.array(mask.getdata()).T.flatten().copy() #mask.show() #pdb.set_trace() #plt.imshow(np.array(mask.getdata()).reshape(newsize,newsize,3)) #plt.show() data.append(newdata) labels.append(label) x_noise, y_noise = np.random.normal(0, 5, 2) x_noise = max(-20, min(x_noise, 20)) y_noise = max(-20, min(y_noise, 20))
def Segmentacao(caminho, diretorio): # cria o direotorio novo para a captura try: os.stat('Imagens/Cortes/' + diretorio) except: os.mkdir('Imagens/Cortes/' + diretorio) imagem = cv2.imread(caminho) #le a imagem resultante do resultado anterior peb = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) # tons de cinza _, segmentacao = cv2.threshold( peb, 150, 255, cv2.THRESH_BINARY_INV) # segmentacao threshold holding = cv2.getStructuringElement( cv2.MORPH_CROSS, (1, 2)) #1 e 2 sao porporcoes de descoberta dilated = cv2.dilate(segmentacao, holding, iterations=2) #dilatacao dos resultados encontrados contornos, hierarchy = cv2.findContours( dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # gera array de contornos media = 0 b = 0 for cont in contornos: # para cada contorno gerado [x, y, w, h] = cv2.boundingRect(cont) #gera um retangulo da area dos contornos largimg, altimg = imagem.shape[:2] contorno = int(largimg / 110) corte = imagem[y:y + h, x:x + w] #gera a imagem de corte com margens de 3 e 4 px largura, altura = corte.shape[: 2] #pega a largura e altura da imagem de corte if altura == 0: #caso nao haja altura, se atribui 0,001 para evitar divisao por 0 altura = 0.001 proporcao = largura / altura #gera a proporcao entre largura e altura min = largimg / 15 #f largura > 30 and proporcao > 1.28 and proporcao < 2.55: print(str(x + y) + ".jpg " + str(proporcao) + " " + str(largura) ) #printa a proporcao e largura da imagem de corte atual media = media + altura if largura > b: b = largura cv2.imwrite('Imagens/Cortes/' + diretorio + '/' + str(x + y) + '.jpg', corte) #salva imagem de corte imag = Image.open('Imagens/Cortes/' + diretorio + '/' + str(x + y) + '.jpg') img_borda = ImageOps.expand(imag, border=10, fill='white') img_borda.save('Imagens/Cortes/' + diretorio + '/' + str(x + y) + '.jpg') #cv2.rectangle(imagem,(x,y),(x+w,y+h),(255,0,255),2) print(b)
def apply_border(self, padding_size=4, border_size=1, fill_color="white", border_color="#ccc"): self.img = ImageOps.expand(self.img, border=padding_size, fill=fill_color) self.img = ImageOps.expand(self.img, border=border_size, fill=border_color)
screenshot2 = photos.pick_image(show_albums=True) screenshot3 = photos.pick_image(show_albums=True) mode = console.alert('Create or Clean', 'Select a mode below.', 'Create Now', 'Clean First') if mode == 2: from Cleanbar import cleanbar cleanbar(screenshot1) cleanbar(screenshot2) cleanbar(screenshot3) # Creates final image console.clear() print("Creating final image...") background = Image.new('RGBA', (1850, 1275), (255, 255, 255, 255)) file1 = screenshot1.resize((545, 969), Image.ANTIALIAS) file2 = screenshot2.resize((700, 1245), Image.ANTIALIAS) file3 = screenshot3.resize((545, 969), Image.ANTIALIAS) file1 = ImageOps.expand(file1, border=1, fill='gray') file2 = ImageOps.expand(file2, border=1, fill='gray') file3 = ImageOps.expand(file3, border=1, fill='gray') background.paste(file1, (10, 138)) background.paste(file2, (575, 15)) background.paste(file3, (1295, 138)) console.hide_activity() background.show() print("\n\n Image created")