我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用PIL.ImageFilter.GaussianBlur()。
def _generate_image(event): image_data = event_image.get_image(event) im = Image.open(StringIO.StringIO(image_data)) image_size = (im.width, im.height) scale = tuple(1.0 * x / y for x, y in zip(full_size, image_size)) # Generate the background-image that is blurred and backgrounds the main image max_scale = max(scale) background_image_new_size = tuple(int(round(max_scale * x)) for x in image_size) background_resized = im.resize(background_image_new_size, resample=Image.BICUBIC) background_blurred = background_resized.filter(ImageFilter.GaussianBlur(100)) background_offset = tuple((x - y) / 2 for x, y in zip(full_size, background_image_new_size)) # Generate the scaled-image that fits the frame exactly min_scale = min(scale) foreground_image_size = tuple(int(round(min_scale * x)) for x in image_size) foreground_resized = im.resize(foreground_image_size, resample=Image.BICUBIC) foreground_offset = tuple((x - y) / 2 for x, y in zip(full_size, foreground_image_size)) target = Image.new('RGB', full_size) target.paste(background_blurred, background_offset) target.paste(foreground_resized, foreground_offset) return target
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 blur(self, radius): """Save blur pamaters as well as returns a blurred image.""" self.edited = True self._blur = True self._blur_radius = radius return self.image.filter(ImageFilter.GaussianBlur( radius=float(radius)))
def blur(img, blur_radius=0.2): img = Image.fromarray(img) blurred = img.copy().filter(ImageFilter.GaussianBlur(radius=blur_radius)) blurred = np.asarray(blurred) return blurred
def blurCover(coverurl, cachepath): savepath = os.path.join(cachepath, coverurl.rsplit('/', 1)[-1] + '.jpg') if os.path.isfile(savepath): return savepath else: cover = Image.open(io.BytesIO(urllib.urlopen(coverurl).read())) cover_blurred = cover.filter(ImageFilter.GaussianBlur(80)) cover_blurred = cover_blurred.point(lambda p: p * 0.5) cover_blurred.save(savepath) return savepath
def manipulate_frame(self, frame_image, faces, index): # Read images dest = np.array(frame_image.convert('RGB')) dest_faces = faces mask = np.zeros(dest.shape, dtype = dest.dtype) if len(self.source_faces) == 0: for source in self.secondary_image: output = io.BytesIO() source.save(output, format="JPEG") secondary_faces = self.get_faces(output.getvalue()) output.close() converted_source = np.array(source.convert('RGB')); for face in secondary_faces: self.source_faces.append( (face, converted_source) ) j = 0 for dest_face in dest_faces: (source_face, source_image) = self.source_faces[j % len(self.source_faces)] try: (dest, mask) = self.pasteOne(source_image, dest, source_face, dest_face, mask) except Exception as e: pass j = j + 1 frame_image.paste(Image.fromarray(dest), mask=Image.fromarray(mask).convert('L').filter(ImageFilter.GaussianBlur(4))) return frame_image
def manipulate_frame(self, frame_image, faces, index): # Read images dest = np.array(frame_image.convert('RGB')) dest_faces = faces source = np.array(frame_image.convert('RGB')) source_faces = faces[:] random.shuffle(source_faces) mask = np.zeros(dest.shape, dtype = dest.dtype) for j in xrange(len(faces)): (dest, mask) = self.pasteOne(source, dest, source_faces[ j ], dest_faces[j], mask) frame_image.paste(Image.fromarray(dest), mask=Image.fromarray(mask).convert('L').filter(ImageFilter.GaussianBlur(4))) return frame_image
def add_shadow(self, color="black", blur=2, offset=(0,0), resize=True, shadow_only=False): """Add a drop shadow to an image""" if not self.mode.endswith('A'): return self shadow = Image.from_pattern(color, self.size) if isinstance(color, Image.Image) else Image.new("RGBA", self.size, color) shadow.putalpha(ImageChops.multiply(self.split()[-1], shadow.split()[-1])) shadow = shadow.pad(blur, 0) if blur: shadow = shadow.filter(ImageFilter.GaussianBlur(blur)) offsets = Padding(0) img = Image.new("RGBA", self.size, 0) img = img.pin(shadow, (offset[0]-blur,offset[1]-blur), align=0, offsets=offsets) if not shadow_only: img = img.pin(self, (0,0), align=0, offsets=offsets) if not resize: img = img.crop((offsets[0], offsets[1], img.width-offsets[2], img.height-offsets[3])) return img
def test_draw_on_image_with_filters(self, _draw_content_mock, _save, filter_mock): filters = (ImageFilter.BLUR, ImageFilter.GaussianBlur(2)) with create_test_image(): filter_mock.return_value = PIL_Image.open('test.png') self.img.draw_on_image( image_path=os.path.abspath('test.png'), image_filters=filters) self.assertTrue(filter_mock.called) self.assertTrue(_draw_content_mock.called)
def gaussian_blur(func_config): def f(image_config): radius = misc.uniform_sample_from_interval(func_config.min_radius, func_config.max_radius) image_config.image = image_config.image.filter(ImageFilter.GaussianBlur(radius)) return f
def GaussianBlur_random(img): gaussianidx = np.random.randint(0, len(gaussianbandwidths)) gaussianbandwidth = gaussianbandwidths[gaussianidx] return GaussianBlur(img, gaussianbandwidth)
def GaussianBlur(img, bandwidth): img = img.filter(ImageFilter.GaussianBlur(bandwidth)) return img
def call(self, img): if img is None: raise ValueError('img is None') im_n = img.copy() gauss_blur_low, gauss_blur_high = 0, self.gauss_blur blur_low, blur_high = gauss_blur_high, gauss_blur_high + self.blur smooth_low, smooth_high = blur_high, blur_high + self.smooth smooth_more_low, smooth_more_high = smooth_high, smooth_high + self.smooth_more rank_low, rank_high = smooth_more_high, smooth_more_high + self.rank_filter r = random() if gauss_blur_low <= r <= gauss_blur_high: im_n = im_n.filter(ImageFilter.GaussianBlur(1)) elif blur_low < r <= blur_high: im_n = im_n.filter(ImageFilter.BLUR) elif smooth_low < r <= smooth_high: im_n = im_n.filter(ImageFilter.SMOOTH) elif smooth_more_low < r <= smooth_more_high: im_n = im_n.filter(ImageFilter.SMOOTH_MORE) elif rank_low < r <= rank_high: im_n = im_n.filter(ImageFilter.RankFilter(size=3, rank=7)) else: pass return im_n
def process_iphone(self, dim, width, height): background = Image.new('RGBA', size=(1536, 2726), color=self.bg_color) # Maybe we should consider a blur background some other time, a plain background will do for now # scrshot2 = self.screenshot_image.resize((1536, 2726), PIL.Image.ANTIALIAS) # background = scrshot2.filter(ImageFilter.GaussianBlur(radius=12)) self.set_text(background, self.desc_text, self.desc_font, 'desc') self.set_text(background, self.title_text, self.title_font, 'title') # ------------------ iphone_type = ('iphone6plus' if dim > 4 else 'iphone5') iphone_device = Image.open("%s/devices/%s.png" % (get_script_dir(), iphone_type)) background.paste(iphone_device, (0, 0), iphone_device) if dim <= 4: img2 = self.screenshot_image.resize((1135, 1800), PIL.Image.ANTIALIAS) background.paste(img2, (200, 920)) else: img2 = self.screenshot_image.resize((1147, 1906), PIL.Image.ANTIALIAS) background.paste(img2, (190, 820)) if not os.path.isdir(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) destination_dir = OUTPUT_DIR + '/%s' % dim if not os.path.isdir(destination_dir): os.mkdir(destination_dir) background = background.resize((width, height), PIL.Image.ANTIALIAS) valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) file_name = ''.join(c for c in self.title_text if c in valid_chars) background.convert('RGB').save("%s/%s.jpg" % (destination_dir, file_name))
def blur(ctx): if ctx.subcommand_passed is None: if ctx.message.attachments != []: attachtoretrieve = urllib.request.Request( ctx.message.attachments[0]['url'], data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) actuallyretrieving = urllib.request.urlopen(attachtoretrieve) with open("OhYes.png", 'wb') as f: f.write(actuallyretrieving.read()) f.close() actuallyretrieving.close() image = Image.open('OhYes.png') inverted_image = image.filter(ImageFilter.GaussianBlur(radius=2)) inverted_image.save('result.png') await ctx.message.channel.send(file=discord.File("result.png")) os.remove("result.png") else: await say(ctx.message, "Please enter a link after the command.") else: attachtoretrieve = urllib.request.Request( ctx.subcommand_passed, data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) actuallyretrieving = urllib.request.urlopen(attachtoretrieve) with open("OhYes.png", 'wb') as f: f.write(actuallyretrieving.read()) f.close() actuallyretrieving.close() image = Image.open('OhYes.png') inverted_image = image.filter(ImageFilter.GaussianBlur(radius=2)) inverted_image.save('result.png') await ctx.message.channel.send(file=discord.File("result.png")) os.remove("result.png")
def blur(message, im): """ Applies a blur effect. Example:: /drawtext Hello there! | blur Requires an input image. """ parser = ArgumentParser() parser.add_argument("--radius", "-r", type=int, choices=range(2, 10), default=2) args = parser.parse_args(shlex.split(message.content)) return im.filter(ImageFilter.GaussianBlur(radius=args.radius))
def editar1(img):#Blurred imagen = Image.open(img).filter(ImageFilter.GaussianBlur(radius=15)) imagen.convert("RGB") imagen.save(img)
def filter_footer(self, img): """Filter to remove the hight quality footer for an image.""" # Some sites like MangaFox add an extra footer in the original # image. This footer remove importan space in the Kindle, and # we need to remove it. # # The algorithm use as a leverage the normal noise present in # an scanned image, that is higher than the one in the footer. # This means that this filter will only work in medium quality # scanners, but possibly not in high quality ones. # # The process is like this: # # 1.- Binarize the image, moving the noise at the same level # that the real information. # # 2.- Use a MinFilter of size 3 to a big mass of pixels that # containg high frequency data. That usually means # pixels surrounded with blanks. # # 3.- Do a Gaussian filter to lower more the high frequency # data, moving the mass close arround the pixel. This # will lower more the pixels surrounded with gaps. # # 4.- Discard the pixels with low mass. # _img = ImageOps.invert(img.convert(mode='L')) _img = _img.point(lambda x: x and 255) _img = _img.filter(ImageFilter.MinFilter(size=3)) _img = _img.filter(ImageFilter.GaussianBlur(radius=5)) _img = _img.point(lambda x: (x >= 48) and x) # If the image is white, we do not have bbox return img.crop(_img.getbbox()) if _img.getbbox() else img
def filter_margin(self, img): """Filter to remove empty margins in an image.""" # This filter is based on a simple Gaussian with a threshold _img = ImageOps.invert(img.convert(mode='L')) _img = _img.filter(ImageFilter.GaussianBlur(radius=3)) _img = _img.point(lambda x: (x >= 16) and x) # If the image is white, we do not have bbox return img.crop(self.bbox(_img)) if _img.getbbox() else img
def lens_blur(input_path, depthmap_path, min_focal, max_focal, transition, radius, brightness, output_dir, speed=1): """ lens blur """ im = Image.open(input_path) im.load() format = im.format depthmap = Image.open(depthmap_path) depth_px = depthmap.load() power = 10 ** brightness speed = int(min(speed, im.width, im.height)) # prepare gradient filters and filtered images gradient_filters = [] filtered_images = [] copy_box = (0, 0, im.width, im.height) for i in range(radius): gradient_filters.append(ImageFilter.GaussianBlur(1)) image_i = im.crop(copy_box) for j in range(i): image_i = image_i.filter(gradient_filters[i]) filtered_images.append(image_i) # manipulate pixel for i in range(0, im.width, speed): for j in range(0, im.height, speed): depth = depth_px[i,j][0] box = (i, j, i + speed, j + speed) pixel = im.crop(box) if depth - max_focal >= transition or min_focal - depth >= transition: pixel = filtered_images[radius - 1].crop(box) elif depth - max_focal > 0: pixel = filtered_images[int((depth - max_focal)/transition*radius) - 1].crop(box) elif min_focal - depth > 0: pixel = filtered_images[int((min_focal - depth)/transition*radius) - 1].crop(box) im.paste(pixel, box) # output image enhancer = ImageEnhance.Brightness(im) im = enhancer.enhance(power) name = hex(int(time.time() * 100000))[2:] path = output_dir + '/' + str(name) + '.' + format im.save(path) return path