Python PIL.ImageFilter.GaussianBlur() Examples

The following are 30 code examples of PIL.ImageFilter.GaussianBlur(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageFilter , or try the search function .
Example #1
Source File: multimedia.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def blur_image(
        self, extension: str = "png", gaussian: bool = False, radius: int = 2
    ):
        """Blur an image
        
        Args:
            extension (str, optional): File extension of loaded image. Defaults to png
            gaussian (bool, optional): If Gaussian blur is to be applied. Defaults to False.
            radius (int, optional): Radius for Gaussian blur. Defaults to 2.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> c = Chepy("logo.png").load_file().blur_image("png")
            >>> >>> c.write('/path/to/file.png', as_binary=True)

            To apply Gaussian blur, use:

            >>> c = Chepy("logo.png").load_file()
            >>> c.blur_image(extension="png", gaussian=True, radius=4)
            >>> >>> c.write('/path/to/file.png', as_binary=True)
        """
        image = Image.open(self._load_as_file())
        fh = io.BytesIO()
        if gaussian:
            blurred = image.filter(ImageFilter.GaussianBlur(radius=radius))
        else:
            blurred = image.filter(ImageFilter.BLUR)
        blurred.save(fh, extension)
        self.state = fh.getvalue()
        return self 
Example #2
Source File: test_image_filter.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_sanity(self):

        def filter(filter):
            for mode in ["L", "RGB", "CMYK"]:
                im = hopper(mode)
                out = im.filter(filter)
                self.assertEqual(out.mode, im.mode)
                self.assertEqual(out.size, im.size)

        filter(ImageFilter.BLUR)
        filter(ImageFilter.CONTOUR)
        filter(ImageFilter.DETAIL)
        filter(ImageFilter.EDGE_ENHANCE)
        filter(ImageFilter.EDGE_ENHANCE_MORE)
        filter(ImageFilter.EMBOSS)
        filter(ImageFilter.FIND_EDGES)
        filter(ImageFilter.SMOOTH)
        filter(ImageFilter.SMOOTH_MORE)
        filter(ImageFilter.SHARPEN)
        filter(ImageFilter.MaxFilter)
        filter(ImageFilter.MedianFilter)
        filter(ImageFilter.MinFilter)
        filter(ImageFilter.ModeFilter)
        filter(ImageFilter.GaussianBlur)
        filter(ImageFilter.GaussianBlur(5))
        filter(ImageFilter.BoxBlur(5))
        filter(ImageFilter.UnsharpMask)
        filter(ImageFilter.UnsharpMask(10))

        self.assertRaises(TypeError, filter, "hello") 
Example #3
Source File: test_imageops_usm.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_blur_accuracy(self):

        i = snakes.filter(ImageFilter.GaussianBlur(.4))
        # These pixels surrounded with pixels with 255 intensity.
        # They must be very close to 255.
        for x, y, c in [(1, 0, 1), (2, 0, 1), (7, 8, 1), (8, 8, 1), (2, 9, 1),
                        (7, 3, 0), (8, 3, 0), (5, 8, 0), (5, 9, 0), (1, 3, 0),
                        (4, 3, 2), (4, 2, 2)]:
            self.assertGreaterEqual(i.im.getpixel((x, y))[c], 250)
        # Fuzzy match.

        def gp(x, y):
            return i.im.getpixel((x, y))
        self.assertTrue(236 <= gp(7, 4)[0] <= 239)
        self.assertTrue(236 <= gp(7, 5)[2] <= 239)
        self.assertTrue(236 <= gp(7, 6)[2] <= 239)
        self.assertTrue(236 <= gp(7, 7)[1] <= 239)
        self.assertTrue(236 <= gp(8, 4)[0] <= 239)
        self.assertTrue(236 <= gp(8, 5)[2] <= 239)
        self.assertTrue(236 <= gp(8, 6)[2] <= 239)
        self.assertTrue(236 <= gp(8, 7)[1] <= 239) 
Example #4
Source File: folder.py    From dla with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __getitem__(self, index):
        path, target = self.imgs[index]
        img = self.loader(path)
        img_size = torch.LongTensor(img.size)
        # img = img.filter(ImageFilter.GaussianBlur(7))
        if self.transform is not None:
            img = self.transform(img)
        if self.target_transform is not None:
            target = self.target_transform(target)

        output = [img, target]
        if self.out_name:
            output.append(os.path.split(path)[1])
        if self.out_image_size:
            output.append(img_size)

        return tuple(output) 
Example #5
Source File: img_utility.py    From nova-ideo with GNU Affero General Public License v3.0 6 votes vote down vote up
def blur_img(fp, filename):
    try:
        img = Image.open(fp)
        if img.mode == 'P':
            img = img.convert('RGB')
    except OSError as e:
        log.warning(e)
        return {}

    img = img.filter(ImageFilter.GaussianBlur(radius=25))
    buf = io.BytesIO()
    ext = os.path.splitext(filename)[1].lower()
    img.save(buf, Image.EXTENSION.get(ext, 'jpeg'))
    buf.seek(0)
    return {'fp': buf,
            'id': 'blur'} 
Example #6
Source File: test_models.py    From nider with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: AttackEvaluations.py    From DEEPSEC with MIT License 6 votes vote down vote up
def gaussian_blur_transform(AdvSample, radius, oriDataset):
    if oriDataset.upper() == 'CIFAR10':
        assert AdvSample.shape == (3, 32, 32)
        sample = np.transpose(np.round(AdvSample * 255), (1, 2, 0))

        image = Image.fromarray(np.uint8(sample))
        gb_image = image.filter(ImageFilter.GaussianBlur(radius=radius))
        gb_image = np.transpose(np.array(gb_image), (2, 0, 1)).astype('float32') / 255.0
        return gb_image

    if oriDataset.upper() == 'MNIST':
        assert AdvSample.shape == (1, 28, 28)
        sample = np.transpose(np.round(AdvSample * 255), (1, 2, 0))
        # for MNIST, there is no RGB
        sample = np.squeeze(sample, axis=2)

        image = Image.fromarray(np.uint8(sample))
        gb_image = image.filter(ImageFilter.GaussianBlur(radius=radius))

        gb_image = np.expand_dims(np.array(gb_image).astype('float32'), axis=0) / 255.0
        return gb_image


# help function for the image compression transformation of images 
Example #8
Source File: uilt.py    From flask-Purchase_and_sale with MIT License 6 votes vote down vote up
def get_verify_code():
    '''生成验证码图形'''
    code = gene_text()
    # 图片大小120×50
    width, height = 120, 50
    # 新图片对象
    im = Image.new('RGB',(width, height),'white')
    # 字体
    font = ImageFont.truetype('app/static/arial.ttf', 40)
    # draw对象
    draw = ImageDraw.Draw(im)
    # 绘制字符串
    for item in range(4):
        draw.text((5+random.randint(-3,3)+23*item, 5+random.randint(-3,3)),
                  text=code[item], fill=rndColor(),font=font )
    # 划线
    draw_lines(draw, 2, width, height)
    # 高斯模糊
    im = im.filter(ImageFilter.GaussianBlur(radius=1.5))
    return im, code


# 进货表格
# 进货量 
Example #9
Source File: service.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 6 votes vote down vote up
def blur(self, source, radius=20):
        filename = '{}{}.png'.format(utils.md5hash(source), radius)
        destination = self.save_path + filename
        try:
            if xbmcvfs.exists(destination):
                os.utime(destination, None)
            else:
                img = _openimage(source, self.save_path, filename)
                img.thumbnail((256, 256))
                img = img.convert('RGB')
                img = img.filter(ImageFilter.GaussianBlur(radius))
                img.save(destination)
                img.close()

            return destination

        except Exception:
            return '' 
Example #10
Source File: utils_extra.py    From rlcard with MIT License 5 votes vote down vote up
def mask_rounded_rectangle_transparent(pil_img, corner_radius=8):  # FIXME: not used
    blur_radius = 0  # FIXME: what is this for ??? wch
    mask = Image.new("L", pil_img.size, 0)
    draw = ImageDraw.Draw(mask)
    rounded_rectangle(draw, xy=((0, 0), (pil_img.size[0], pil_img.size[1])), corner_radius=corner_radius, fill=255)

    mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
    result = pil_img.copy()
    result.putalpha(mask)
    return result 
Example #11
Source File: drawTriangles.py    From Delaunay_Triangulation with ISC License 5 votes vote down vote up
def loadAndFilterImage(name):
    start = time.clock()
    orig = Image.open(name)
    im = orig.convert("L")
    im = im.filter(ImageFilter.GaussianBlur(radius=5))
    im = im.filter(ImageFilter.FIND_EDGES)

    im = brightenImage(im, 20.0)

    im = im.filter(ImageFilter.GaussianBlur(radius=5))
    print "Bild laden: %.2fs" % (time.clock()-start)
    return (orig, im) 
Example #12
Source File: __init__.py    From Semi-supervised-segmentation-cycleGAN with MIT License 5 votes vote down vote up
def PILaugment(img, mask):
    if random.random() > 0.2:
        (w, h) = img.size
        (w_, h_) = mask.size
        assert (w == w_ and h == h_), 'The size should be the same.'
        crop = random.uniform(0.45, 0.75)
        W = int(crop * w)
        H = int(crop * h)
        start_x = w - W
        start_y = h - H
        x_pos = int(random.uniform(0, start_x))
        y_pos = int(random.uniform(0, start_y))
        img = img.crop((x_pos, y_pos, x_pos + W, y_pos + H))
        mask = mask.crop((x_pos, y_pos, x_pos + W, y_pos + H))

    if random.random() > 0.2:
        img = ImageOps.flip(img)
        mask = ImageOps.flip(mask)

    if random.random() > 0.2:
        img = ImageOps.mirror(img)
        mask = ImageOps.mirror(mask)

    if random.random() > 0.2:
        angle = random.random() * 90 - 45
        img = img.rotate(angle)
        mask = mask.rotate(angle)
    if random.random() > 0.95:
        img = img.filter(ImageFilter.GaussianBlur(2))

    if random.random() > 0.95:
        img = ImageEnhance.Contrast(img).enhance(1)

    if random.random() > 0.95:
        img = ImageEnhance.Brightness(img).enhance(1)

    return img, mask 
Example #13
Source File: selenium_hooks.py    From RobotEyes with MIT License 5 votes vote down vote up
def blur_regions(self, selectors, radius, path):
        selectors = selectors if isinstance(selectors, list) else [selectors]
        for region in selectors:
            try:
                prefix, locator, element = self.find_element(region)
            except NoSuchElementException:
                continue

            area_coordinates = self._get_coordinates_from_driver(element)

            if self.is_mobile():
                left, right = math.ceil(area_coordinates['left']), math.ceil(area_coordinates['right'])
                top, bottom = math.ceil(area_coordinates['top']), math.ceil(area_coordinates['bottom'])
            else:
                frame_abs_pos = self._get_current_frame_abs_position()
                left, right = math.ceil(area_coordinates['left'] + frame_abs_pos['x']), math.ceil(
                    area_coordinates['right'] + frame_abs_pos['x'])
                top, bottom = math.ceil(area_coordinates['top'] + frame_abs_pos['y']), math.ceil(
                    area_coordinates['bottom'] + frame_abs_pos['y'])

            left, right, top, bottom = self._update_coordinates(left, right, top, bottom)
            im = Image.open(path + '/img' + str(self.count) + '.png')
            cropped_image = im.crop((left, top, right, bottom))
            blurred_image = cropped_image.filter(ImageFilter.GaussianBlur(radius=int(radius)))
            im.paste(blurred_image, (left, top, right, bottom))
            im.save(path + '/img' + str(self.count) + '.png') 
Example #14
Source File: cityscapes.py    From Fast-SCNN-pytorch with Apache License 2.0 5 votes vote down vote up
def _sync_transform(self, img, mask):
        # random mirror
        if random.random() < 0.5:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
            mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
        crop_size = self.crop_size
        # random scale (short edge)
        short_size = random.randint(int(self.base_size * 0.5), int(self.base_size * 2.0))
        w, h = img.size
        if h > w:
            ow = short_size
            oh = int(1.0 * h * ow / w)
        else:
            oh = short_size
            ow = int(1.0 * w * oh / h)
        img = img.resize((ow, oh), Image.BILINEAR)
        mask = mask.resize((ow, oh), Image.NEAREST)
        # pad crop
        if short_size < crop_size:
            padh = crop_size - oh if oh < crop_size else 0
            padw = crop_size - ow if ow < crop_size else 0
            img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)
            mask = ImageOps.expand(mask, border=(0, 0, padw, padh), fill=0)
        # random crop crop_size
        w, h = img.size
        x1 = random.randint(0, w - crop_size)
        y1 = random.randint(0, h - crop_size)
        img = img.crop((x1, y1, x1 + crop_size, y1 + crop_size))
        mask = mask.crop((x1, y1, x1 + crop_size, y1 + crop_size))
        # gaussian blur as in PSP
        if random.random() < 0.5:
            img = img.filter(ImageFilter.GaussianBlur(
                radius=random.random()))
        # final transform
        img, mask = self._img_transform(img), self._mask_transform(mask)
        return img, mask 
Example #15
Source File: custom_transforms.py    From SCNN-pytorch with MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        if random.random() < 0.5:
            img = img.filter(ImageFilter.GaussianBlur(
                radius=random.random()))

        return {'image': img,
                'label': mask} 
Example #16
Source File: flowtransforms.py    From hd3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, img_list, label_list, radius=2):
        if random.random() < 0.5:
            img_list = [
                img.filter(ImageFilter.GaussianBlur(radius))
                for img in img_list
            ]
        return img_list, label_list 
Example #17
Source File: emby_actor.py    From AV_Data_Capture with GNU General Public License v3.0 5 votes vote down vote up
def fix_size(path):
    pic = Image.open(path)
    (x, y) = pic.size
    if not 2 / 3 - 0.05 <= x / y <= 2 / 3 + 0.05:  # 仅处理会过度拉伸的图片
        fixed_pic = pic.resize((int(x), int(3 / 2 * x)))  # 拉伸图片
        fixed_pic = fixed_pic.filter(ImageFilter.GaussianBlur(radius=50))  # 高斯模糊
        fixed_pic.paste(pic, (0, int((3 / 2 * x - y) / 2)))  # 粘贴原图
        fixed_pic.save(path) 
Example #18
Source File: custom_transforms.py    From overhaul-distillation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        if random.random() < 0.5:
            img = img.filter(ImageFilter.GaussianBlur(
                radius=random.random()))

        return {'image': img,
                'label': mask} 
Example #19
Source File: segbase.py    From cascade_rcnn_gluon with Apache License 2.0 5 votes vote down vote up
def _sync_transform(self, img, mask):
        # random mirror
        if random.random() < 0.5:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
            mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
        crop_size = self.crop_size
        # random scale (short edge from 480 to 720)
        short_size = random.randint(int(self.base_size*0.5), int(self.base_size*2.0))
        w, h = img.size
        if h > w:
            ow = short_size
            oh = int(1.0 * h * ow / w)
        else:
            oh = short_size
            ow = int(1.0 * w * oh / h)
        img = img.resize((ow, oh), Image.BILINEAR)
        mask = mask.resize((ow, oh), Image.NEAREST)
        # random rotate -10~10, mask using NN rotate
        deg = random.uniform(-10, 10)
        img = img.rotate(deg, resample=Image.BILINEAR)
        mask = mask.rotate(deg, resample=Image.NEAREST)
        # pad crop
        if short_size < crop_size:
            padh = crop_size - oh if oh < crop_size else 0
            padw = crop_size - ow if ow < crop_size else 0
            img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)
            mask = ImageOps.expand(mask, border=(0, 0, padw, padh), fill=0)
        # random crop crop_size
        w, h = img.size
        x1 = random.randint(0, w - crop_size)
        y1 = random.randint(0, h - crop_size)
        img = img.crop((x1, y1, x1+crop_size, y1+crop_size))
        mask = mask.crop((x1, y1, x1+crop_size, y1+crop_size))
        # gaussian blur as in PSP
        if random.random() < 0.5:
            img = img.filter(ImageFilter.GaussianBlur(
                radius=random.random()))
        # final transform
        img, mask = self._img_transform(img), self._mask_transform(mask)
        return img, mask 
Example #20
Source File: custom_transforms.py    From RMI with MIT License 5 votes vote down vote up
def __call__(self, sample):
        image = sample['image']
        label = sample['label']
        if random.random() < 0.5:
            image = image.filter(ImageFilter.GaussianBlur(
                radius=random.random()))

        return {'image': image,
                'label': label} 
Example #21
Source File: mobi.py    From kmanga with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #22
Source File: mobi.py    From kmanga with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #23
Source File: generator.py    From DeepLearning-OCR with Apache License 2.0 5 votes vote down vote up
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 
Example #24
Source File: trans.py    From ocr.pytorch with MIT License 5 votes vote down vote up
def tranfun(self, image):
        image = getpilimage(image)
        image = image.filter(ImageFilter.GaussianBlur(radius=1))
        # blurred_image = image.filter(ImageFilter.Kernel((3,3), (1,1,1,0,0,0,2,0,2)))
        # Kernel
        return image 
Example #25
Source File: util.py    From elegance with MIT License 5 votes vote down vote up
def blur_image(pil_img,mode,r):
    if mode == "g":
        kernel = ImageFilter.GaussianBlur(radius=r)
    elif mode == "m":
        kernel = ImageFilter.MedianFilter(size=r)
    else:
        raise ValueError("{} not support".format(mode))
    return pil_img.filter(kernel) 
Example #26
Source File: weather-and-light.py    From enviroplus-python with MIT License 5 votes vote down vote up
def draw_background(progress, period, day):
    """Given an amount of progress through the day or night, draw the
       background colour and overlay a blurred sun/moon."""

    # x-coordinate for sun/moon
    x = x_from_sun_moon_time(progress, period, WIDTH)

    # If it's day, then move right to left
    if day:
        x = WIDTH - x

    # Calculate position on sun/moon's curve
    centre = WIDTH / 2
    y = calculate_y_pos(x, centre)

    # Background colour
    background = map_colour(x, 80, mid_hue, day_hue, day)

    # New image for background colour
    img = Image.new('RGBA', (WIDTH, HEIGHT), color=background)
    # draw = ImageDraw.Draw(img)

    # New image for sun/moon overlay
    overlay = Image.new('RGBA', (WIDTH, HEIGHT), color=(0, 0, 0, 0))
    overlay_draw = ImageDraw.Draw(overlay)

    # Draw the sun/moon
    circle = circle_coordinates(x, y, sun_radius)
    overlay_draw.ellipse(circle, fill=(200, 200, 50, opacity))

    # Overlay the sun/moon on the background as an alpha matte
    composite = Image.alpha_composite(img, overlay).filter(ImageFilter.GaussianBlur(radius=blur))

    return composite 
Example #27
Source File: cityscapes.py    From mobilenetv3-segmentation with Apache License 2.0 5 votes vote down vote up
def _sync_transform(self, img, mask):
        # random mirror
        if random.random() < 0.5:
            img = img.transpose(Image.FLIP_LEFT_RIGHT)
            mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
        crop_size = self.crop_size
        # random scale (short edge)
        short_size = random.randint(int(self.base_size * 0.5), int(self.base_size * 2.0))
        w, h = img.size
        if h > w:
            ow = short_size
            oh = int(1.0 * h * ow / w)
        else:
            oh = short_size
            ow = int(1.0 * w * oh / h)
        img = img.resize((ow, oh), Image.BILINEAR)
        mask = mask.resize((ow, oh), Image.NEAREST)
        # pad crop
        if short_size < crop_size:
            padh = crop_size - oh if oh < crop_size else 0
            padw = crop_size - ow if ow < crop_size else 0
            img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)
            mask = ImageOps.expand(mask, border=(0, 0, padw, padh), fill=0)
        # random crop crop_size
        w, h = img.size
        x1 = random.randint(0, w - crop_size)
        y1 = random.randint(0, h - crop_size)
        img = img.crop((x1, y1, x1 + crop_size, y1 + crop_size))
        mask = mask.crop((x1, y1, x1 + crop_size, y1 + crop_size))
        # gaussian blur as in PSP
        if random.random() < 0.5:
            img = img.filter(ImageFilter.GaussianBlur(
                radius=random.random()))
        # final transform
        img, mask = self._img_transform(img), self._mask_transform(mask)
        return img, mask 
Example #28
Source File: __init__.py    From knockoffnets with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, image):
        radius = np.random.uniform(self.min_radius, self.max_radius)
        return image.filter(ImageFilter.GaussianBlur(radius))


# Create a mapping of dataset -> dataset_type
# This is helpful to determine which (a) family of model needs to be loaded e.g., imagenet and
# (b) input transform to apply 
Example #29
Source File: GaussianBlur.py    From pyblur with MIT License 5 votes vote down vote up
def GaussianBlur(img, bandwidth):
    img = img.filter(ImageFilter.GaussianBlur(bandwidth))
    return img 
Example #30
Source File: GaussianBlur.py    From pyblur with MIT License 5 votes vote down vote up
def GaussianBlur_random(img):
    gaussianidx = np.random.randint(0, len(gaussianbandwidths))
    gaussianbandwidth = gaussianbandwidths[gaussianidx]
    return GaussianBlur(img, gaussianbandwidth)