def setup(self): for st in self._imgs: w, h = self.pos['width'], self.pos['height'] x = (w - self._img_source.size[0]) / 2 y = (h - self._img_source.size[1]) / 2 buttonbg = image.hex_to_rgb(self.frame.colors[st]['buttonbg']) buttonfg = image.hex_to_rgb(self.frame.colors[st]['buttonfg']) # Create the "base" image normal = Image.new('RGBA', (w, h), color=buttonbg) normal.paste(self._img_source, box=(x, y), mask=self._img_source) imgd = ImageDraw.Draw(normal) imgd.bitmap((x, y), self._img_source, fill=buttonfg) # Make other two states before beveling hover = normal.copy() click = normal.copy() # Now add effects that differentiate the states rendering.bevel_up(normal) bright = ImageEnhance.Brightness(click) click = bright.enhance(1.2) rendering.bevel_down(click) bright = ImageEnhance.Brightness(hover) hover = bright.enhance(1.2) rendering.bevel_up(hover) self._imgs[st]['normal'] = image.get_data(normal) self._imgs[st]['click'] = image.get_data(click) self._imgs[st]['hover'] = image.get_data(hover)
def HighlightRects(self, pngfile, highlightrects): # large libraries. load only if necessary import Image, ImageDraw, ImageEnhance, ImageChops dkpercent = 70 p1 = Image.new("RGB", (500, 500)) ff = StringIO() pfp = Image.open(pngfile) swid, shig = pfp.getbbox()[2:] dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0) ddpfp = ImageDraw.Draw(dpfp) for highlightrect in highlightrects: mrect = re.match("rect_(\d+),(\d+)_(\d+),(\d+)$", highlightrect) if mrect: rect = (int(mrect.group(1)), int(mrect.group(2)), int(mrect.group(3)), int(mrect.group(4))) srect = (rect[0] * swid / 1000, rect[1] * swid / 1000, rect[2] * swid / 1000, rect[3] * swid / 1000) ddpfp.rectangle(srect, (255, 255, 255)) cpfp = ImageChops.darker(pfp, dpfp) ff = StringIO() cpfp.save(ff, "png") return ff.getvalue()
def run(self): ''' Limpia las imagenes empleando PIL ''' # notificar el inicio de operaciones self.notificador.inicio_operacion.emit() import Image, ImageChops, ImageOps, ImageEnhance for i in range(len(self.imagenesIn)): im = Image.open(self.imagenesIn[i]) if im: im1 = ImageChops.invert(im) im = ImageChops.subtract(im1, im) im = im.convert('L') im = ImageChops.invert(im) im = ImageEnhance.Brightness(im).enhance(2.0) im = ImageOps.colorize(im, (0, 0, 0), (255, 255, 255)) im.save(self.imagenesOut[i]) else: self.notificador.error.emit('Error al procesar la imagen: ' + self.imagenesIn[i]) return # notificar a la aplicacion el resultado de la operacion self.notificador.correcto.emit(self.plugin.nombre()) # notificar el fin de operaciones self.notificador.fin_operacion.emit() return
def __init__(self, **kwargs): kwargs.setdefault('filename', os.path.join('..', 'photoo', 'photo1.jpg')) if kwargs.get('filename') is None: raise Exception('No filename given to MTScatterImage') kwargs.setdefault('loader', None) super(ImageScatter, self).__init__(**kwargs) self.touch_positions = {} self.pim = Image.open(kwargs.get('filename')) self.contrast_enh = ImageEnhance.Contrast(self.pim) self.pim = self.contrast_enh.enhance(1.0) self.bright_enh = ImageEnhance.Brightness(self.pim) self.pim = self.bright_enh.enhance(1.0) self.color_enh = ImageEnhance.Color(self.pim) self.pim = self.color_enh.enhance(1.0) self.sharp_enh = ImageEnhance.Sharpness(self.pim) self.pim = self.sharp_enh.enhance(1.0) self.bdata = self.pim.tostring() self.img = ImageData(self.pim.size[0], self.pim.size[1], 'RGB', self.bdata, pitch=-self.pim.size[0] * 3) self.image = pyglet.sprite.Sprite(self.img) self.width = self.pim.size[0] self.height = self.pim.size[1]
def CodeFilter(fromfile='code.gif', tofile='code_temp.png'): ''' pre-process the image. ''' import Image,ImageEnhance,ImageFilter, ImageDraw import sys #image_name = "D:\\SUN\\HOME\\python\\guahao\\code.gif" image_name = 'code.gif' #image_name = "D:\\SUN\\HOME\\python\\guahao\\code.png" im = Image.open(image_name) #print im.format, im.size, im.mode #im.show() #print im.info #print im.palette im_new = im.convert('L') #im_new.show() #im_new.save('dd.png') # ɾ³ý±ß¿ò draw = ImageDraw.Draw(im_new) draw.line((0, 0, im.size[0], 0), fill=255) draw.line((0, 0, 0, im.size[1]), fill=255) draw.line((0, im.size[1]-1, im.size[0], im.size[1]-1), fill=255) draw.line((im.size[0]-1, 0, im.size[0]-1, im.size[1]-1), fill=255) enhancer = ImageEnhance.Brightness(im_new) im_new = enhancer.enhance(2.0) #¼ÓÁÁ£¬Ð§¹û¼ûͼ1 enhancer = ImageEnhance.Contrast(im_new) im_new = enhancer.enhance(4) #Ìá¸ß¶Ô±È¶È£¬Ð§¹û¼ûͼ2 im_new.convert('1') im_new.filter(ImageFilter.MedianFilter) im_new.save(tofile) return im_new
def add_watermark_text(im, text, angle=23, opacity=0.25, font='/Library/Fonts/Copperplate.ttc'): if im.mode != 'RGBA': im = im.convert('RGBA') watermark = Image.new('RGBA', im.size, (0, 0, 0, 0)) size = 2 n_font = ImageFont.truetype(font, size) n_width, n_height = n_font.getsize(text) # grow size until the limit is reached while n_width + n_height < watermark.size[0]: size += 2 n_font = ImageFont.truetype(font, size) n_width, n_height = n_font.getsize(text) draw = ImageDraw.Draw(watermark, 'RGBA') draw.text(((watermark.size[0] - n_width) / 2, (watermark.size[1] - n_height) / 2), text, (0, 0, 0), font=n_font) watermark = watermark.rotate(angle, Image.BICUBIC) alpha = watermark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) watermark.putalpha(alpha) return Image.composite(watermark, im, watermark)
def composeForFacebook(self,images): print("composing for facebook") strip = Image.new('RGB', (self.facebookLayout["width"], self.facebookLayout["width"]), (0,0,0)) count=0 dim=self.facebookLayout["photoDim"] positions={0:[5,5],1:[dim,5],2:[5,dim],3:[dim,dim]} #for inFile in glob.glob(os.path.join(imageDir, '*.JPG')): for img in images: if count>3:break # print("\t"+str(inFile)) #img=Image.open(inFile) posX,posY=positions[count] bbox=img.getbbox() img=img.crop(((bbox[2]/2)-(bbox[3]/2),0,(bbox[2]/2)+(bbox[3]/2),bbox[3])) img=img.resize((dim-10,dim-10)) #img = ImageOps.autocontrast(img, cutoff=2) if self.grey: img=ImageOps.grayscale(img) enh=ImageEnhance.Brightness(img) img=enh.enhance(0.8) enh=ImageEnhance.Contrast(img) img=enh.enhance(1.3) strip.paste(img,(posX,posY)) count=count+1 overlay=self.facebookLayout["overlay"] strip.paste(overlay,None,overlay) #path=os.path.join(imageDir, 'facebookStrip.PNG') #path=self.saveImageToOutgoing(strip,"facebook") #dateString=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M') #path=os.path.join(self.outgoingPath,dateString+'_facebook.PNG') #strip.save(path, 'PNG') print("\n") return [strip,"facebook"]
def adjustImage(infile, factor): outfile = os.path.splitext(infile)[0] + '-updated.png' im = Image.open(infile) width, height = im.size print im.size, im.mode enhancer = ImageEnhance.Brightness(im) enhancer.enhance(factor).save(outfile)
def reduce_opacity(mark, opacity): assert opacity >= 0 and opacity <= 1 mark = mark.convert('RGBA') if mark.mode != 'RGBA' else mark.copy() alpha = mark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) mark.putalpha(alpha) return mark
def watermark(self, img): import StringIO, Image, ImageEnhance tileImage = Image.open(StringIO.StringIO(img)) wmark = Image.open(self.watermarkimage) assert self.watermarkopacity >= 0 and self.watermarkopacity <= 1 if wmark.mode != 'RGBA': wmark = wmark.convert('RGBA') else: wmark = wmark.copy() alpha = wmark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(self.watermarkopacity) wmark.putalpha(alpha) if tileImage.mode != 'RGBA': tileImage = tileImage.convert('RGBA') watermarkedImage = Image.new('RGBA', tileImage.size, (0, 0, 0, 0)) watermarkedImage.paste(wmark, (0, 0)) watermarkedImage = Image.composite(watermarkedImage, tileImage, watermarkedImage) buffer = StringIO.StringIO() if watermarkedImage.info.has_key('transparency'): watermarkedImage.save( buffer, self.extension, transparency=compositeImage.info['transparency']) else: watermarkedImage.save(buffer, self.extension) buffer.seek(0) return buffer.read()
def brig(imagefile,factor=10,brightfile=None): im=Image.open(imagefile) enhancer = ImageEnhance.Brightness(im) if brightfile==None: brightfile=imagefile[:-4]+"_br"+str(factor)+".png" else: brightfile=os.path.dirname(imagefile)+"/Enhanced_Original/"+os.path.basename(imagefile)[:-4]+"_br"+str(factor)+".png" enhancer.enhance(factor).save(brightfile) return
def make_inset_shadow(alpha): mc = alpha.copy() for i in xrange(6): mc = mc.filter(ImageFilter.SMOOTH_MORE) mc = ImageChops.subtract(alpha, mc) mcb = ImageEnhance.Brightness(mc).enhance(0.35) m1 = alpha.copy() for i in xrange(6): m1 = m1.filter(ImageFilter.SMOOTH_MORE) m1 = m1.offset(0, OFFSET_S) m1 = ImageChops.subtract(alpha, m1) m1b = ImageEnhance.Brightness(m1).enhance(0.35) m = ImageChops.lighter(mc, m1) mb = ImageChops.lighter(mcb, m1b) return (m, mb)
def equalize(self): if self.image1 is not None: contr = ImageEnhance.Contrast(self.image1) image = contr.enhance(self.contrast) bright = ImageEnhance.Brightness(image) image = bright.enhance(self.brightness) image = image.resize((int(image.size[0] * self.scale), int(image.size[1] * self.scale))) self.wif = image.convert('1')
def equalize(image1, contrast, brightness): contr = ImageEnhance.Contrast(image1) image = contr.enhance(contrast) bright = ImageEnhance.Brightness(image) image = bright.enhance(brightness) image = image.resize((int(image.size[0]), int(image.size[1]))) out = image.convert('1') return out
def myEqualize(im, contrast=1, brightness=1): if im is not None: im = im.convert('L') contr = ImageEnhance.Contrast(im) im = contr.enhance(contrast) bright = ImageEnhance.Brightness(im) im = bright.enhance(brightness) #im.show() return im
def do_brightness(self): """usage: brightness <image:pic1> Enhance brightness in the top image. """ import ImageEnhance factor = float(self.do_pop()) image = self.do_pop() enhancer = ImageEnhance.Brightness(image) self.push(enhancer.enhance(factor))
def text_watermark(source_file, out_base_path='.', text='@Grayson', angle=23, opacity=0.50): ''''' 添加一个文字水印,做成透明水印的模样,应该是png图层合并 http://www.pythoncentral.io/watermark-images-python-2x/ 这里会产生著名的 ImportError("The _imagingft C module is not installed") 错误 Pillow通过安装来解决 pip install Pillow ''' img = Image.open(source_file) # watermark = Image.new('RGBA', img.size, (255, 255, 255)) # 我这里有一层白色的膜,去掉(255,255,255) 这个参数就好了 watermark = Image.new('RGBA', img.size) # 我这里有一层白色的膜,去掉(255,255,255) 这个参数就好了 # FONT = abspath + "/fonts/NewYork.ttf" FONT = "../../fonts/NewYork.ttf" size = 1 n_font = ImageFont.truetype(FONT, size) # 得到字体 n_width, n_height = n_font.getsize(text) text_box = min(watermark.size[0], watermark.size[1]) / 4 print(text_box) # text_box = 300 while (n_width + n_height < text_box): size += 2 n_font = ImageFont.truetype(FONT, size=size) n_width, n_height = n_font.getsize(text) # 文字逐渐放大,但是要小于图片的宽高最小值 # text_width = (watermark.size[0] - n_width) / 2 text_width = (watermark.size[0] - n_width) # text_height = (watermark.size[1] - n_height) / 2 text_height = (watermark.size[1] - n_height) # watermark = watermark.resize((text_width,text_height), Image.ANTIALIAS) print(text_width, text_height) draw = ImageDraw.Draw(watermark, 'RGBA') # 在水印层加画笔 delta_right = -text_width / 9 # 字体与右侧的距离 delta_bottom = -text_height / 24 # 字体与底部的距离 draw.text((delta_right + text_width, delta_bottom + text_height), text, font=n_font, fill="#ffffff") # watermark = watermark.rotate(angle, Image.BICUBIC) alpha = watermark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) watermark.putalpha(alpha) str_uuid = ''.join(str(uuid.uuid4()).split('-')) splits = source_file.split('.') image_suffix = splits[len(splits) - 1] out_file = out_base_path + '/' + str_uuid + '.' + image_suffix print(out_file) Image.composite(watermark, img, watermark).save(out_file, image_suffix) print(u"文字水印成功") return str_uuid
def adjustImage(infile): im = Image.open(infile) for f in range(40, 20, -1): factor = f / 20.0 outfile = os.path.splitext(infile)[0] + ('-%f.png' % factor) enhancer = ImageEnhance.Brightness(im) tmp = enhancer.enhance(factor) enhancer = ImageEnhance.Contrast(tmp) tmp = enhancer.enhance(1.15) enhancer = ImageEnhance.Color(tmp) enhancer.enhance(1.15).save(outfile)
def reduce_opacity(image, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if image.mode != RGBA: image = image.convert(RGBA) else: image = image.copy() alpha = image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) image.putalpha(alpha) return image
def composite_img_with_opacity(markImg, backgroundImg, opacity=1): markImg, backgroundImg = make_img_to_same_size(markImg, backgroundImg) if opacity <= 1: if markImg.mode != 'RGBA': mark = markImg.convert('RGBA') else: mark = markImg.copy() alpha = mark.split()[3] #r,g,b,alpha=im.split() alpha = ImageEnhance.Brightness(alpha).enhance(opacity) mark.putalpha(alpha) return Image.composite(markImg, backgroundImg, mark)
def fb_upload(cfg, fn): print "Uploading %s to facebook" % fn graph = facebook.GraphAPI(settings.FB_APP_TOKEN) if len(cfg['photopops_fb_album_id']) == 0: print "no album" fb_res = graph.put_object(settings.FB_PHOTOPOPS_PAGE_ID, "albums", name=cfg['title'], message=cfg['title']) cfg['photopops_fb_album_id'] = fb_res['id'] album_id = fb_res['id'] else: album_id = cfg['photopops_fb_album_id'] saveconfig(cfg) photo = Image.open("/opt/photopops/events/%s/proc/%s" % (cfg['shortname'], fn)) photo = photo.resize((800, 1200)) photo_fn = "fb-%s" % fn mark = Image.open("/opt/photopops/assets/logo-angled-240x102.png") if mark.mode != 'RGBA': print "Converting %s/%s" % (EV_ORIG_DIR, fn) mark = mark.convert('RGBA') # Set opacity on watermark alpha = mark.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(0.7) mark.putalpha(alpha) # Create a new transparent layer the size of the original image layer = Image.new('RGBA', photo.size, (0, 0, 0, 0)) layer.paste( mark, (photo.size[0] - mark.size[0] - 25, photo.size[1] - mark.size[1] - 25)) # Add watermark layer to original image and save in processed directory proc = Image.composite(layer, photo, layer) proc.save("/opt/photopops/events/%s/proc/%s" % (cfg['shortname'], photo_fn), 'JPEG', quality=70) fb_photo = open( "/opt/photopops/events/%s/proc/%s" % (cfg['shortname'], photo_fn), "rb") fb_res = graph.put_photo(fb_photo, album_id, photo_fn) fb_photo.close() del album_id
def reduce_opacity(im, opacity): assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] #r,g,b,alpha=im.split() print "alpha info:" print alpha alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) return im
def brightness_image(self, value): print "dans brihtness image" if self.current_image_entity == None: img = Image.open(self.cureent_image_path) else: img = self.current_image_entity #print img amelioration = ImageEnhance.Brightness(img) img_2 = amelioration.enhance(value) #img_2.show() self.current_image_entity = img_2 self.old_entity = img return img_2
def from_filename(name, width=None, brightness=None, contrast=None): '''Open an image file and return a string of its ASCII Art.''' image = Image.open(name) if width is not None: scale = float(width) / image.size[0] else: scale = 1 if contrast is not None: image = ImageEnhance.Contrast(image).enhance(contrast) if brightness is not None: image = ImageEnhance.Brightness(image).enhance(brightness) return ''.join(generate_art(image, int(image.size[0] * scale), int(image.size[1] * scale)))
def reduceOpacity(image, opacity): """ Vrati obrazek z upravenou opacity @image - Image instance """ assert opacity >= 0 and opacity <= 1 if image.mode != 'RGBA': image = image.convert('RGBA') else: image = image.copy() #endif alpha = image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) image.putalpha(alpha) return image
def enhance_signature(img): bw = ImageEnhance.Color(img).enhance(0.0) bright = ImageEnhance.Brightness(bw).enhance(2.2) contrast = ImageEnhance.Contrast(bright).enhance(2.0) sign = contrast.convert("RGBA") datas = sign.getdata() #--- Algo to detect non-signatured areas and reduce its alpha to zero --# newData = [] for item in datas: if item[0] > 200 and item[1] > 200 and item[2] > 200: newData.append((255, 255, 255, 0)) else: newData.append(item) sign.putdata(newData) sign.save("signature_alpha.png", "PNG")
def reduce_opacity(im, opacity): """Returns an image with reduced opacity if opacity is within ``[0, 1]``. :param im: source image :type im: pil.Image :param opacity: opacity within ``[0, 1]`` :type opacity: float :returns im: image :rtype: pil.Image >>> im = Image.new('RGBA', (1, 1), (255, 255, 255)) >>> im = reduce_opacity(im, 0.5) >>> im.getpixel((0,0)) (255, 255, 255, 127) """ if opacity < 0 or opacity > 1: return im alpha = get_alpha(im) alpha = ImageEnhance.Brightness(alpha).enhance(opacity) put_alpha(im, alpha) return im
def WritePNGpage(pdffile, npage, imgpixwidth, pngfile, highlightrects): #print 'Content-type: text/html\n\n<h1>%s</h1><p>pdffile %s' % (pngfile, pdffile); sys.exit(0) if not os.path.isfile(pngfile): cmd = 'convert -quiet -density 192 %s[%d] -resize %d %s > /dev/null 2>&1' % ( SubParen(pdffile), npage - 1, imgpixwidth, SubParen(pngfile)) os.system(cmd) if not highlightrects or not os.path.isfile(pngfile): fin = open(os.path.isfile(pngfile) and pngfile or "pngnotfound.png") print "Content-type: image/png\n" print fin.read() fin.close() return # large libraries. load only if necessary import Image, ImageDraw, ImageEnhance, ImageChops dkpercent = 70 p1 = Image.new("RGB", (500, 500)) ff = StringIO() pfp = Image.open(pngfile) swid, shig = pfp.getbbox()[2:] dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0) ddpfp = ImageDraw.Draw(dpfp) for rect in highlightrects: srect = (rect[0] * swid / 1000, rect[1] * swid / 1000, rect[2] * swid / 1000, rect[3] * swid / 1000) ddpfp.rectangle(srect, (255, 255, 255)) cpfp = ImageChops.darker(pfp, dpfp) ff = StringIO() cpfp.save(ff, "png") print "Content-type: image/png\n" print ff.getvalue() ff.close()
def get_fallback_tile (mode, zoom, x, y): for zdiff in range(1, fallback + 1): z = zoom - zdiff if z < 0: break zx = int(x / 2**zdiff) zy = int(y / 2**zdiff) tile = get_zoom_tile(mode, z, zx, zy) if tile == None: continue diffx = x - zx * 2**zdiff diffy = y - zy * 2**zdiff cropbounds = [int(256. * b / 2.**zdiff) for b in [diffx, diffy, diffx + 1, diffy + 1]] tile = tile.crop(cropbounds) tile = tile.resize((256, 256), BICUBIC) tile = ImageEnhance.Brightness(tile).enhance(.9**zdiff) return tile return None
def _blend_layers(self, imagecontent, z, x, y): """ Merge tiles of all layers into the specified tile path """ result = self._tile_image(imagecontent) # Paste each layer for (layer, opacity) in self._layers: try: # Prepare tile of overlay, if available overlay = self._tile_image(layer.tile((z, x, y))) except (IOError, DownloadError, ExtractionError) as e: logger.warn(e) continue # Extract alpha mask overlay = overlay.convert("RGBA") r, g, b, a = overlay.split() overlay = Image.merge("RGB", (r, g, b)) a = ImageEnhance.Brightness(a).enhance(opacity) overlay.putalpha(a) mask = Image.merge("L", (a, )) result.paste(overlay, (0, 0), mask) # Read result return self._image_tile(result)