我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用PIL.Image.composite()。
def apply_watermark(im, mark, position, opacity=1): """Adds a watermark to an image.""" if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min( float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, (round((im.size[0] - w) / 2), round((im.size[1] - h) / 2))) else: layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer)
def img(self, Local_initial_address, i, local_store_address): print Local_initial_address, i, local_store_address # tt = u'lvziqing' im = Image.open(Local_initial_address) text = time.ctime() width, height = im.size print width, height txt = Image.new('RGB', im.size, (0, 0, 0, 0)) text_width = (txt.size[0] - 280) text_height = (txt.size[1] - 130) # watermark = txt.resize((text_width,text_height), Image.ANTIALIAS) draw = ImageDraw.Draw(txt, 'RGBA') # ??????? draw.text((text_width, text_height), text, fill=(255,255,255)) watermark = txt.rotate(23, Image.BICUBIC) alpha = watermark.split()[2] alpha = ImageEnhance.Brightness(alpha).enhance(0.50) watermark.putalpha(alpha) a = local_store_address + 'ceshi' + str(i) + '.jpg' Image.composite(watermark, im, watermark).save(a, 'JPEG') return a
def rotate(func_config): def f(image_config): angle = misc.uniform_sample_from_interval(func_config.min_angle, func_config.max_angle) image_config.angle = angle alpha_image = image_config.image.convert('RGBA') rotate_image = alpha_image.rotate(angle) canvas = Image.new('RGBA', rotate_image.size, (255, 255, 255, 255)) image = Image.composite(rotate_image, canvas, rotate_image) image_config.image = image.convert(image_config.image.mode) if 'points' in image_config: rad = math.radians(angle) rotate_matrix = np.array([ [math.cos(rad), -math.sin(rad)], [math.sin(rad), math.cos(rad)] ]) x_center, y_center = image_config.width // 2, image_config.height // 2 y = (image_config.up_edge + image_config.down_edge) // 2 for i, x in enumerate(image_config.points): vector = np.array([x - x_center, y - y_center]) vector = np.dot(vector, rotate_matrix) image_config.points[i] = int(vector[0]) + x_center return f
def lomoize (image,darkness,saturation): (width,height) = image.size max = width if height > width: max = height mask = Image.open("./lomolive/lomomask.jpg").resize((max,max)) left = round((max - width) / 2) upper = round((max - height) / 2) mask = mask.crop((left,upper,left+width,upper + height)) # mask = Image.open('mask_l.png') darker = ImageEnhance.Brightness(image).enhance(darkness) saturated = ImageEnhance.Color(image).enhance(saturation) lomoized = Image.composite(saturated,darker,mask) return lomoized
def composite(image1, image2, mask): """Create composite using transparency mask. Alias for :py:meth:`PIL.Image.Image.composite`. :rtype: :py:class:`~PIL.Image.Image` """ return Image.composite(image1, image2, mask)
def captcha_draw(label, fonts, dir_path, pic_id): # width, height = 512, 48 # size_cha = random.randint(24, 48) # ???? # derx = random.randint(0, 16) # im = Image.new(mode='L', size=(width, height), color='white') # color ?????size ???? # drawer = ImageDraw.Draw(im) # font = ImageFont.truetype(random.choice(fonts), size_cha) # drawer.text(xy=(derx, 0), text=label, font=font, fill='black') #text ???font ???????? # # im.show() # write2file(dir_path, label, im) width, height = 32, 32 size_cha = random.randint(16, 28) # ???? derx = random.randint(0, max(width-size_cha-10, 0)) dery = random.randint(0, max(height-size_cha-10, 0)) im = Image.new(mode='L', size=(width, height), color='white') # color ?????size ???? drawer = ImageDraw.Draw(im) font = ImageFont.truetype(random.choice(fonts), size_cha) drawer.text(xy=(derx, dery), text=label, font=font, fill='black') #text ???font ???????? # if label != ' ' and (img_as_float(im) == np.ones((48, 48))).all(): # # in case the label is not in this font, then the image will be all white # return 0 im = im.convert('RGBA') max_angle = 45 # to be tuned angle = random.randint(-max_angle, max_angle) im = im.rotate(angle, Image.BILINEAR, expand=0) fff = Image.new('RGBA', im.size, (255,)*4) im = Image.composite(im, fff, im) # if random.random() < 0.5: # im = Image.fromarray(grey_erosion(im, size=(2, 2))) # erosion # if random.random() < 0.5: # im = Image.fromarray((random_noise(img_as_float(im), mode='s&p')*255).astype(np.uint8)) # im = im.filter(ImageFilter.GaussianBlur(radius=random.random())) # im.show() write2file(dir_path, label, im, pic_id) return 1
def do_composite(self): """usage: composite <image:pic1> <image:pic2> <image:mask> Replace two images and a mask with their composite. """ image1 = self.do_pop() image2 = self.do_pop() mask = self.do_pop() self.push(Image.composite(image1, image2, mask))
def mask_image(img): mask = Image.new("RGBA", img.size, (255, 255, 255, 255)) return Image.composite(img, mask, img) # will adjust the canvas so that perspective transforms will not result in the image being cropped # also adjusts the image to be square along largest dimension - makes things easier later on # assumes the image background is white...
def watermark(im, mark, position): """Adds a watermark to an image.""" if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = Image.new('RGBA', im.size, (0,0,0,0)) layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer)
def draw_mask_on_image_array(image, mask, color='red', alpha=0.7): """Draws mask on an image. Args: image: uint8 numpy array with shape (img_height, img_height, 3) mask: a float numpy array of shape (img_height, img_height) with values between 0 and 1 color: color to draw the keypoints with. Default is red. alpha: transparency value between 0 and 1. (default: 0.7) Raises: ValueError: On incorrect data type for image or masks. """ if image.dtype != np.uint8: raise ValueError('`image` not of type np.uint8') if mask.dtype != np.float32: raise ValueError('`mask` not of type np.float32') if np.any(np.logical_or(mask > 1.0, mask < 0.0)): raise ValueError('`mask` elements should be in [0, 1]') rgb = ImageColor.getrgb(color) pil_image = Image.fromarray(image) solid_color = np.expand_dims( np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3]) pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA') pil_mask = Image.fromarray(np.uint8(255.0 * alpha * mask)).convert('L') pil_image = Image.composite(pil_solid_color, pil_image, pil_mask) np.copyto(image, np.array(pil_image.convert('RGB')))
def rotate(self): # ???0??????????????? img1 = self.image.rotate(random.randint(-5, 5), expand=0) img = Image.new('RGBA',img1.size,(255,)*4) self.image = Image.composite(img1,img,img1)
def draw_text_with_halo(img, position, text, font, col, halo_col): halo = Image.new('RGBA', img.size, (0, 0, 0, 0)) ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col) blurred_halo = halo.filter(ImageFilter.BLUR) ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col) return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))
def img(self): im = Image.open(self.lj).convert('RGBA') txt = Image.new('RGBA',im.size,(0,0,0,0)) # fnt = ImageFont.truetype("C:\\Windows\\Fonts\\COOPBL.TTF",20) d = ImageDraw.Draw(txt) d.text((txt.size[0]-280,txt.size[1]-30),time.ctime(),fill=(255,255,255,255)) out = Image.composite(im, txt,im) # out.show() # a = 'C:\\Users\\Administrator\\Desktop\\'+str(time.time())+'.jpg' a = self.Roadking+u'????'+str(self.num)+'.jpg' out.save(a) return out,a
def watermark(im, mark, position, opacity=1): """????""" try: if opacity < 1: mark = set_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]: print "The mark image size is larger size than original image file." return False #?????? if position == 'left_top': x = 0 y = 0 elif position == 'left_bottom': x = 0 y = im.size[1] - mark.size[1] elif position == 'right_top': x = im.size[0] - mark.size[0] y = 0 elif position == 'right_bottom': x = im.size[0] - mark.size[0] y = im.size[1] - mark.size[1] else: x = (im.size[0] - mark.size[0]) / 2 y = (im.size[1] - mark.size[1]) / 2 layer = Image.new('RGBA', im.size,) layer.paste(mark,(x,y)) return Image.composite(layer, im, layer) except Exception as e: print ">>>>>>>>>>> WaterMark EXCEPTION: " + str(e) return False
def render(self, stream, value): im = self.im.copy() im2 = self.im.copy() x = 0 r_i = sum(ord(c) for c in value) # ???????????????? for c in value: fgimg = Image.new('RGBA', self.size, self.font_color) charimg = Image.new('L', self.font.getsize(c), '#000000') draw = ImageDraw.Draw(charimg) draw.text((0, 0), c, font=self.font, fill='#ffffff') r = (int(time()) / 1000 + ord(c) + r_i) % 40 - 20 # ??????????????? charimg = charimg.rotate(r, expand=1, resample=Image.BICUBIC) charimg = charimg.crop(charimg.getbbox()) maskimg = Image.new('L', self.size) y = (im2.size[1] - charimg.size[1]) / 2 maskimg.paste(charimg, (x, y, charimg.size[0] + x, charimg.size[1] + y)) im2 = Image.composite(fgimg, im2, maskimg) x += charimg.size[0] - 5 # - X??? # ??????? x ?? center = (im.size[0] - x) / 2 im.paste(im2, (center, 0, im2.size[0]+center, im2.size[1])) im.save(stream, self.image_type)
def modify_image(directory, image, isNoiseFill): filled = "" img_path = directory+os.sep+image; # ?????????? ??? ??????????? output_directory = directory + os.sep + "out" # ???? ????? ?????????? ??? - ???????? if not os.path.exists(output_directory): os.makedirs(output_directory) # ?????? ??????????? im = Image.open(img_path).convert("RGBA") # ???????? ??????????? ?? 2 ?? 358 ???????? ? ????? 2(50) for k in range(2, 358, 50): im_rotate = im.rotate(k, expand = True) # ???? ?????????? ???????? ??? if(isNoiseFill): # ????????? ???? (????) ??? ?????? ??????????? img_noise = get_noise_image(im_rotate.width, im_rotate.height) # ??????? ??????????? im_rotate = Image.composite(im_rotate, img_noise, im_rotate) filled = "_filled" # ????? ??? ????? ? ?????????? ??? ??????????? = ???????????-???_rotated_????-????????.???????????-?????????? im_rotate_name = output_directory + os.sep +image[:image.rindex('.')]+"_rotated_"+k.__str__()+filled+image[image.rindex('.'):] # transparency = im_rotate.info['transparency'] im_rotate.save(im_rotate_name) #, transparency = transparency) # print("++"+im_rotate.width.__str__()+":"+im_rotate.height.__str__()) # ??????? ????? ??????????
def brand(wallpath, watermark): new_wallpath = '/tmp/auw/wallpaper%s' % wallpath[wallpath.rfind('.'):] shutil.copy(wallpath, new_wallpath) im = Image.open(new_wallpath) mark = Image.open(watermark) layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) layer.paste(mark, (im.size[0] - mark.size[0], mark.size[1])) out = Image.composite(layer, im, layer) out.save(new_wallpath) return new_wallpath
def draw_mask_on_image_array(image, mask, color='red', alpha=0.7): """Draws mask on an image. Args: image: uint8 numpy array with shape (img_height, img_height, 3) mask: a float numpy array of shape (img_height, img_height) with values between 0 and 1 color: color to draw the keypoints with. Default is red. alpha: transparency value between 0 and 1. (default: 0.7) Raises: ValueError: On incorrect data type for image or masks. """ if image.dtype != np.uint8: raise ValueError('`image` not of type np.uint8') if mask.dtype != np.float32: raise ValueError('`mask` not of type np.float32') if np.any(np.logical_or(mask > 1.0, mask < 0.0)): raise ValueError('`mask` elements should be in [0, 1]') rgb = ImageColor.getrgb(color) pil_image = Image.fromarray(image) solid_color = np.expand_dims( np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3]) pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA') pil_mask = Image.fromarray(np.uint8(255.0*alpha*mask)).convert('L') pil_image = Image.composite(pil_solid_color, pil_image, pil_mask) np.copyto(image, np.array(pil_image.convert('RGB')))
def add_reflection(im, bgcolor="#00000", amount=0.4, opacity=0.6): """ Returns the supplied PIL Image (im) with a reflection effect bgcolor The background color of the reflection gradient amount The height of the reflection as a percentage of the orignal image opacity The initial opacity of the reflection gradient Originally written for the Photologue image management system for Django and Based on the original concept by Bernd Schlapsi """ # convert bgcolor string to rgb value background_color = ImageColor.getrgb(bgcolor) # copy orignial image and flip the orientation reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM) # create a new image filled with the bgcolor the same size background = Image.new("RGB", im.size, background_color) # calculate our alpha mask start = int(255 - (255 * opacity)) # The start of our gradient steps = int(255 * amount) # the number of intermedite values increment = (255 - start) / float(steps) mask = Image.new('L', (1, 255)) for y in range(255): if y < steps: val = int(y * increment + start) else: val = 255 mask.putpixel((0, y), val) alpha_mask = mask.resize(im.size) # merge the reflection onto our background color using the alpha mask reflection = Image.composite(background, reflection, alpha_mask) # crop the reflection reflection_height = int(im.size[1] * amount) reflection = reflection.crop((0, 0, im.size[0], reflection_height)) # create new image sized to hold both the original image and the reflection composite = Image.new("RGB", (im.size[0], im.size[1] + reflection_height), background_color) # paste the orignal image and the reflection into the composite image composite.paste(im, (0, 0)) composite.paste(reflection, (0, im.size[1])) # return the image complete with reflection effect return composite
def _draw_watermark(self): '''Draws a watermark on the image''' watermark_image = PIL_Image.new('RGBA', self.image.size, (0, 0, 0, 0)) self.watermark._adjust_fontsize(self.image) draw = ImageDraw.Draw(watermark_image, 'RGBA') w_width, w_height = self.watermark.font.getsize(self.watermark.text) draw.text(((watermark_image.size[0] - w_width) / 2, (watermark_image.size[1] - w_height) / 2), self.watermark.text, font=self.watermark.font, fill=self.watermark.color) if self.watermark.rotate_angle: watermark_image = watermark_image.rotate( self.watermark.rotate_angle, PIL_Image.BICUBIC) alpha = watermark_image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(self.watermark.opacity) watermark_image.putalpha(alpha) # Because watermark can be rotated we create a separate image for cross # so that it doesn't get rotated also. + It's impossible to drawn # on a rotated image if self.watermark.cross: watermark_cross_image = PIL_Image.new( 'RGBA', self.image.size, (0, 0, 0, 0)) cross_draw = ImageDraw.Draw(watermark_cross_image, 'RGBA') line_width = 1 + int(sum(self.image.size) / 2 * 0.007) cross_draw.line( (0, 0) + watermark_image.size, fill=self.watermark.color, width=line_width ) cross_draw.line( (0, watermark_image.size[1], watermark_image.size[0], 0), fill=self.watermark.color, width=line_width ) watermark_cross_alpha = watermark_cross_image.split()[3] watermark_cross_alpha = ImageEnhance.Brightness( watermark_cross_alpha).enhance(self.watermark.opacity) watermark_cross_image.putalpha(watermark_cross_alpha) # Adds cross to the watermark watermark_image = PIL_Image.composite( watermark_cross_image, watermark_image, watermark_cross_image) self.image = PIL_Image.composite( watermark_image, self.image, watermark_image)
def generate_image(word): font = FONT size = settings.CAPTCHA_IMAGE_SIZE xpos = 2 from_top = 4 image = makeimg(size) for char in word: fgimage = Image.new('RGB', size, settings.CAPTCHA_FOREGROUND_COLOR) charimage = Image.new('L', getsize(font, ' %s ' % char), '#000000') chardraw = ImageDraw.Draw(charimage) chardraw.text((0, 0), ' %s ' % char, font=font, fill='#ffffff') if settings.CAPTCHA_LETTER_ROTATION: angle = random.randrange(*settings.CAPTCHA_LETTER_ROTATION) charimage = charimage.rotate( angle, expand=0, resample=Image.BICUBIC) charimage = charimage.crop(charimage.getbbox()) maskimage = Image.new('L', size) xpos2 = xpos + charimage.size[0] from_top2 = from_top + charimage.size[1] maskimage.paste(charimage, (xpos, from_top, xpos2, from_top2)) size = maskimage.size image = Image.composite(fgimage, image, maskimage) xpos = xpos + 2 + charimage.size[0] if settings.CAPTCHA_IMAGE_SIZE: # centering captcha on the image tmpimg = makeimg(size) xpos2 = int((size[0] - xpos) / 2) from_top2 = int((size[1] - charimage.size[1]) / 2 - from_top) tmpimg.paste(image, (xpos2, from_top2)) image = tmpimg.crop((0, 0, size[0], size[1])) else: image = image.crop((0, 0, xpos + 1, size[1])) draw = ImageDraw.Draw(image) settings.FILTER_FUNCTION(image) settings.NOISE_FUNCTION(image, draw) out = StringIO() image.save(out, 'PNG') content = out.getvalue() out.seek(0) out.close() return content