Esempio n. 1
0
 def __call__(self, img, grnd):
     if random.random() < 0.5:
         img = img.filter(ImageFilter.GaussianBlur(radius=random.random()))
     return img, grnd
Esempio n. 2
0
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points3,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points4,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points5,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points6,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points7,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
drawable_image.line(points8,
                    fill=(180, 180, 180, random.randint(100, 255)),
                    width=random.randint(1, 4),
                    joint='curve')
out = Image.alpha_composite(new_image, base)
converted_out = out.convert("LA")
blured = converted_out.filter(ImageFilter.GaussianBlur(radius=2))
blured = blured.filter(ImageFilter.SHARPEN)
blured.show()
Esempio n. 3
0
import numpy as np

##Imagen de muestra en el mismo directorio del archivo
RGB = np.array(io.imread("balloon.jpg"))

RGB2 = PIL.Image.open("jakob-nielsen-thumbs-up.jpg")

LAB = np.array(color.rgb2lab(RGB2))

HSV = np.array(color.rgb2hsv(RGB2))

##Aplicamos los filtros gaussianos y almacenamos en variables
GAUSSIAN_KERNELS = [1, 3, 5]

#RGB1 = filters.gaussian(RGB,GAUSSIAN_KERNELS[0])
RGB2 = RGB2.filter(ImageFilter.GaussianBlur(GAUSSIAN_KERNELS[1]))

RGB2.save('blurred.png', 'png')

#RGB3 = filters.gaussian(RGB,GAUSSIAN_KERNELS[2])
#
#LAB1 = filters.gaussian(LAB,GAUSSIAN_KERNELS[0])
LAB2 = filters.gaussian(LAB, GAUSSIAN_KERNELS[1])
#LAB3 = filters.gaussian(LAB,GAUSSIAN_KERNELS[2])
#
#HSV1 = filters.gaussian(HSV,GAUSSIAN_KERNELS[0])
HSV2 = filters.gaussian(HSV, GAUSSIAN_KERNELS[1])
#HSV3 = filters.gaussian(HSV,GAUSSIAN_KERNELS[2])

import foreground_estimation
import bayesian
Esempio n. 4
0
unlabeledset = torchvision.datasets.STL10(root='./data',
                                          split='unlabeled',
                                          download=True,
                                          transform=transform)

unlabeledloader = torch.utils.data.DataLoader(unlabeledset,
                                              batch_size=4,
                                              shuffle=False,
                                              num_workers=2)

print(type(unlabeledset.__getitem__(10)[0]))
print(len(unlabeledset.__getitem__(10)[0]))

print(unlabeledset.__getitem__(10)[1])

conv = transforms.ToPILImage()
unconv = transforms.ToTensor()

a = unlabeledset.__getitem__(10)[0] / 2. + 0.5
a = conv(a)
a = a.filter(ImageFilter.GaussianBlur(radius=0.1))

b = unconv(a)

print(type(a))
print(type(b))

a.show()
imshow(b)
 def __call__(self, x):
     sigma = random.uniform(self.sigma[0], self.sigma[1])
     x = x.filter(ImageFilter.GaussianBlur(radius=sigma))
     return x
Esempio n. 6
0
 def blurr(self, degree):
     self.image = self.image.filter(ImageFilter.GaussianBlur(radius=degree))
     return self
Esempio n. 7
0
 def to_image(self):
     return self.img.filter(ImageFilter.GaussianBlur(self.blur_radius))
Esempio n. 8
0
    def generate(
        cls,
        index,
        text,
        font,
        out_dir,
        size,
        extension,
        skewing_angle,
        random_skew,
        blur,
        random_blur,
        background_type,
        distorsion_type,
        distorsion_orientation,
        is_handwritten,
        name_format,
        width,
        alignment,
        text_color,
        orientation,
        space_width,
        character_spacing,
        margins,
        fit,
        output_mask,
        word_split,
        image_dir,
        stroke_width=0,
        stroke_fill="#282828",
        image_mode="RGB",
    ):
        image = None

        margin_top, margin_left, margin_bottom, margin_right = margins
        horizontal_margin = margin_left + margin_right
        vertical_margin = margin_top + margin_bottom

        ##########################
        # Create picture of text #
        ##########################
        if is_handwritten:
            if orientation == 1:
                raise ValueError("Vertical handwritten text is unavailable")
            image, mask = handwritten_text_generator.generate(text, text_color)
        else:
            image, mask = computer_text_generator.generate(
                text,
                font,
                text_color,
                size,
                orientation,
                space_width,
                character_spacing,
                fit,
                word_split,
                stroke_width,
                stroke_fill,
            )
        random_angle = rnd.randint(0 - skewing_angle, skewing_angle)

        rotated_img = image.rotate(
            skewing_angle if not random_skew else random_angle, expand=1)

        rotated_mask = mask.rotate(
            skewing_angle if not random_skew else random_angle, expand=1)

        #############################
        # Apply distorsion to image #
        #############################
        if distorsion_type == 0:
            distorted_img = rotated_img  # Mind = blown
            distorted_mask = rotated_mask
        elif distorsion_type == 1:
            distorted_img, distorted_mask = distorsion_generator.sin(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0
                          or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1
                            or distorsion_orientation == 2),
            )
        elif distorsion_type == 2:
            distorted_img, distorted_mask = distorsion_generator.cos(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0
                          or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1
                            or distorsion_orientation == 2),
            )
        else:
            distorted_img, distorted_mask = distorsion_generator.random(
                rotated_img,
                rotated_mask,
                vertical=(distorsion_orientation == 0
                          or distorsion_orientation == 2),
                horizontal=(distorsion_orientation == 1
                            or distorsion_orientation == 2),
            )

        ##################################
        # Resize image to desired format #
        ##################################

        # Horizontal text
        if orientation == 0:
            new_width = int(
                distorted_img.size[0] *
                (float(size - vertical_margin) / float(distorted_img.size[1])))
            resized_img = distorted_img.resize(
                (new_width, size - vertical_margin), Image.ANTIALIAS)
            resized_mask = distorted_mask.resize(
                (new_width, size - vertical_margin), Image.NEAREST)
            background_width = width if width > 0 else new_width + horizontal_margin
            background_height = size
        # Vertical text
        elif orientation == 1:
            new_height = int(
                float(distorted_img.size[1]) *
                (float(size - horizontal_margin) /
                 float(distorted_img.size[0])))
            resized_img = distorted_img.resize(
                (size - horizontal_margin, new_height), Image.ANTIALIAS)
            resized_mask = distorted_mask.resize(
                (size - horizontal_margin, new_height), Image.NEAREST)
            background_width = size
            background_height = new_height + vertical_margin
        else:
            raise ValueError("Invalid orientation")

        #############################
        # Generate background image #
        #############################
        if background_type == 0:
            background_img = background_generator.gaussian_noise(
                background_height, background_width)
        elif background_type == 1:
            background_img = background_generator.plain_white(
                background_height, background_width)
        elif background_type == 2:
            background_img = background_generator.quasicrystal(
                background_height, background_width)
        else:
            background_img = background_generator.image(
                background_height, background_width, image_dir)
        background_mask = Image.new("RGB",
                                    (background_width, background_height),
                                    (0, 0, 0))

        #############################
        # Place text with alignment #
        #############################

        new_text_width, _ = resized_img.size

        if alignment == 0 or width == -1:
            background_img.paste(resized_img, (margin_left, margin_top),
                                 resized_img)
            background_mask.paste(resized_mask, (margin_left, margin_top))
        elif alignment == 1:
            background_img.paste(
                resized_img,
                (int(background_width / 2 - new_text_width / 2), margin_top),
                resized_img,
            )
            background_mask.paste(
                resized_mask,
                (int(background_width / 2 - new_text_width / 2), margin_top),
            )
        else:
            background_img.paste(
                resized_img,
                (background_width - new_text_width - margin_right, margin_top),
                resized_img,
            )
            background_mask.paste(
                resized_mask,
                (background_width - new_text_width - margin_right, margin_top),
            )

        #######################
        # Apply gaussian blur #
        #######################

        gaussian_filter = ImageFilter.GaussianBlur(
            radius=blur if not random_blur else rnd.randint(0, blur))
        final_image = background_img.filter(gaussian_filter)
        final_mask = background_mask.filter(gaussian_filter)

        ############################################
        # Change image mode (RGB, grayscale, etc.) #
        ############################################

        final_image = final_image.convert(image_mode)
        final_mask = final_mask.convert(image_mode)

        #####################################
        # Generate name for resulting image #
        #####################################
        # We remove spaces if space_width == 0
        if space_width == 0:
            text = text.replace(" ", "")
        if name_format == 0:
            image_name = "{}_{}.{}".format(text, str(index), extension)
            mask_name = "{}_{}_mask.png".format(text, str(index))
        elif name_format == 1:
            image_name = "{}_{}.{}".format(str(index), text, extension)
            mask_name = "{}_{}_mask.png".format(str(index), text)
        elif name_format == 2:
            image_name = "{}.{}".format(str(index), extension)
            mask_name = "{}_mask.png".format(str(index))
        else:
            print("{} is not a valid name format. Using default.".format(
                name_format))
            image_name = "{}_{}.{}".format(text, str(index), extension)
            mask_name = "{}_{}_mask.png".format(text, str(index))

        # Save the image
        if out_dir is not None:
            name = uuid.uuid4().hex + '.' + extension
            final_image.save(os.path.join(out_dir, name))
            #print(np.array(final_image))
            if output_mask == 1:
                final_mask.save(os.path.join(out_dir, mask_name))
        else:
            if output_mask == 1:
                return final_image, final_mask
        return final_image, name
Esempio n. 9
0
    def process(self, image_width, image_height, image_translate_x,
                image_translate_y, image_flip_x, image_flip_y,
                image_rotate_degree, image_contrast, image_brightness,
                image_blur, image_saturate, image_opacity, frame_width,
                frame_height):
        """
        Run process operations under image and return edited image path.
        If USE_CACHE is enabled and cache exists, method returns cached image path.

        :Args:
          - self (:class:`BkImageEditor`): BkImageEditor instance.
          - image_width (:class:`int`): Resize image to selected width.
          - image_height (:class:`int`): Resize image to selected height.
          - image_translate_x (:class:`int`): Move image by X axis. 0:0 is frame left top corner.
          - image_translate_y (:class:`int`): Move image by Y axis. 0:0 is frame left top corner.
          - image_flip_x (:class:`bool`): Flip image X axis.
          - image_flip_y (:class:`bool`): Flip image Y axis.
          - image_rotate_degree (:class:`int`): Rotate image degree.
          - image_contrast (:class:`int`): Image contrast level.
          - image_brightness (:class:`int`): Image brightness level.
          - image_blur (:class:`int`): Image blur level.
          - image_saturate (:class:`int`): Image saturate level.
          - image_opacity (:class:`int`): Image opacity level.
          - frame_width (:class:`int`): Frame/crop area width.
          - frame_height (:class:`int`): Frame/crop area height.

        :Returns:
          Path to edited image
        """

        self._image_width = image_width
        self._image_height = image_height
        self._image_translate_x = image_translate_x
        self._image_translate_y = image_translate_y
        self._image_flip_x = image_flip_x
        self._image_flip_y = image_flip_y
        self._image_rotate_degree = image_rotate_degree
        self._image_contrast = image_contrast
        self._image_brightness = image_brightness
        self._image_blur = image_blur
        self._image_saturate = image_saturate
        self._image_opacity = image_opacity
        self._frame_width = frame_width
        self._frame_height = frame_height

        output_filepath = os.path.join(self._cache_folder,
                                       self.output_filename)

        # cache folder
        if not os.path.exists(self._cache_folder):
            # folder can be created by another process between os.path.exists and os.makedirs
            try:
                os.makedirs(self._cache_folder)
            except OSError:
                pass

        if self.USE_CACHE:
            if os.path.exists(output_filepath):
                return output_filepath

        try:

            # converted to have an alpha layer
            pil_region = self._input_image_file.convert(
                self._input_image_file.mode)

            # try to get icc profile
            try:
                icc_profile = self._input_image_file.info.get("icc_profile")
            except:
                icc_profile = None

            # resize image (not frame)
            pil_region = pil_region.resize(
                (self._image_width, self._image_height), Image.ANTIALIAS)

            # scale image (flip)
            if self._image_flip_x:
                pil_region = pil_region.transpose(Image.FLIP_LEFT_RIGHT)

            if self._image_flip_y:
                pil_region = pil_region.transpose(Image.FLIP_TOP_BOTTOM)

            # rotate image
            if self._image_rotate_degree != 0:
                pil_region = pil_region.rotate(self._image_rotate_degree)

            # apply frame cropping
            if self._image_rotate_degree in (-270, -90, 90, 270):
                xsize, ysize = self._image_width, self._image_height

                # initial image left-top coordiantes relatively to the frame
                x, y = self._image_translate_x, self._image_translate_y

                # image center coordinates
                xc = x + xsize / 2
                yc = y + ysize / 2

                # rotate degree
                rotate_deg = self._image_rotate_degree
                rotate_radians = math.radians(rotate_deg)

                # calculate left-top image coordinates (relatively to the frame) after rotation
                # used formula:
                # X = x0 + (x - x0) * cos(a) - (y - y0) * sin(a)
                # Y = y0 + (y - y0) * cos(a) + (x - x0) * sin(a)
                x1 = xc + (x - xc) * math.cos(rotate_radians) - (
                    y - yc) * math.sin(rotate_radians)
                y1 = yc + (y - yc) * math.cos(rotate_radians) + (
                    x - xc) * math.sin(rotate_radians)

                if rotate_deg in (-270, 90):
                    x1 -= ysize
                # -90, 270
                else:
                    y1 -= xsize

                frame = (int(x1) * (-1),
                         int(y1) * (-1), int(x1) * (-1) + self._frame_width,
                         int(y1) * (-1) + self._frame_height)
            else:
                frame = (self._image_translate_x * (-1),
                         self._image_translate_y * (-1),
                         self._image_translate_x * (-1) + self._frame_width,
                         self._image_translate_y * (-1) + self._frame_height)

            pil_region = pil_region.crop(frame)

            # contrast
            contr = ImageEnhance.Contrast(pil_region)
            pil_region = contr.enhance(self._image_contrast)

            # brightness
            brightness = ImageEnhance.Brightness(pil_region)
            pil_region = brightness.enhance(self._image_brightness)

            # saturate
            saturate = ImageEnhance.Color(pil_region)
            pil_region = saturate.enhance(self._image_saturate)

            # blur
            # TODO test this part one more time
            pil_region = pil_region.filter(
                ImageFilter.GaussianBlur(self._image_blur))

            if icc_profile:
                pil_region.save(output_filepath,
                                quality=self.QUALITY,
                                dpi=(self.DPI, self.DPI),
                                icc_profile=icc_profile)
            else:
                pil_region.save(output_filepath,
                                quality=self.QUALITY,
                                dpi=(self.DPI, self.DPI))

            return output_filepath

        except (IOError, Exception) as e:
            logger.exception("BkImageEditor: {}. Image: {}".format(
                e.message, self._input_image_file))
            return None
def Blur(path):
    img = Image.open(path)
    img_blur = img.filter(ImageFilter.GaussianBlur(2))
    img_blur.save('a1.png')
    pat = 'a1.png'
    display(pat)
Esempio n. 11
0
from PIL import Image, ImageFilter
import os

size = (725, 480)
for i in os.listdir('.'):
    if i.endswith('.jfif'):
        image = Image.open(i)
        fileName, File_ext = os.path.splitext(i)
        print('{} and {}'.format(fileName, File_ext))
        image.thumbnail(
            size)  #this will helps to resize the image into 500,500 pixel
        image.save('Kohli png/{}.png'.format(fileName))

show_image = Image.open('kohli1.jpg')  #show image
show_image.show()

rotate_image = Image.open(
    'kohli2.jpg')  #see the current directory(rotate an image into 90 deg)
rotate_image.rotate(90).save('kohli2_90.jpg')

bw_image = Image.open('kohli3.jpg')  #grayscale image
bw_image.convert(mode="L").save('kohli3_b&w.jpg')

blur_image = Image.open('kohli4.jpg')  #blur image
blur_image.filter(ImageFilter.GaussianBlur(2)).save('kohli4_blur.jpg')
Esempio n. 12
0
    def execute_on(self, *args, **kwargs):
        super(TransformationGaussianBlur, self).execute_on(*args, **kwargs)

        return self.image.filter(ImageFilter.GaussianBlur(radius=self.radius))
Esempio n. 13
0
image.save("kuş2.jpg")

image.rotate(180).save("kuş3.jpg")

image.rotate(90).save("kuş4.jpg")

image.convert(mode="L").save("kuş5.jpg")

degistir = (960, 600)

image.thumbnail(degistir)

image.save("kuş6.jpg")

image.filter(ImageFilter.GaussianBlur(10)).save("kuş8.jpg")

kırpılacak_alan = (340, 0, 950, 600)

image2 = Image.open("atatürk.jpg")
image2.crop(kırpılacak_alan).save("kuş9.jpg")

# image.show()

# image1.save("kuş2.jpg")

# image1.rotate(180).save("kuş2.jpg")

# image1.convert(mode = 'L').save("kuş2.jpg")

# image1.thumbnail((300,300))
Esempio n. 14
0
def captcha_to_string(img):

    rgb_dict = defaultdict(int)
    ans = ""

    # show_image(img)

    pix = img.load()
    width = img.size[0]
    height = img.size[1]
    for x in range(width):
        for y in range(height):
            res_code = validation(width, height, x, y, pix)
            if res_code == 1:
                for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                    nx, ny = x + dx, y + dy
                    rgb_dict[pix[nx, ny]] += 10
                rgb_dict[pix[x, y]] += 10
            elif res_code == 3:
                rgb_dict[pix[x, y]] += 1
            else:
                img.putpixel((x, y), (255, 255, 255))

    # show_image(img)

    rank = sorted(rgb_dict.items(), key=lambda k_v: k_v[1])
    color_set = set([colr[0] for colr in rank[-4:]])

    pix = img.load()

    for x in range(width):
        for y in range(height):
            p = (255, 255, 255) if pix[x, y] not in color_set else (0, 0, 0)
            img.putpixel((x, y), p)

    # phase2 = "phase2_" + filename
    # img.save(phase2)
    # show_image(img)

    # cut image vertically for recognition
    left = right = top = 0
    bottom = height - 1
    is_white = True
    is_char = False

    for x in range(width):
        for y in range(height):

            rgb = pix[x, y][:3]

            if y == 0:
                is_white = True
            elif rgb == (0, 0, 0):
                is_white = False

            if not is_white and not is_char:
                is_char = True
                left = x - 3

        if is_char and is_white:
            is_char = False
            right = x + 3
            c_img = img.crop((left, top, right, bottom))
            c_img = c_img.resize((c_img.size[0] * 2, c_img.size[1] * 2))
            c_img = c_img.filter(ImageFilter.GaussianBlur(radius=1))

            # show_image(c_img)

            char = refine(
                pytesseract.image_to_string(c_img,
                                            lang='eng',
                                            config='--psm 7'))
            ans += char

    return ans
Esempio n. 15
0
def filter(b64_img, filter_type):
    censor_str = Censor.censor
    logo_str = Logo.logo
    meta_data = b64_img[0:b64_img.index(',') + 1]
    img, info = convert_from_b64(b64_img)
    width, height = img.size

    #applies a black and white filter over the image
    if filter_type == 'black_and_white':
        img = img.convert('L')

    #applies a sepia filter over the image
    elif filter_type == 'sepia':
        sepia = make_linear_ramp()
        img = img.convert('L')
        img.putpalette(sepia)
        img = img.convert('RGB')

    #applies a blur to the image and adds a 'censored' image on top
    elif filter_type == 'censor':
        img = img.filter(ImageFilter.GaussianBlur(10))
        censor_img = Image.open(
            BytesIO(b64decode(censor_str[censor_str.index(',') + 1:])))
        censor_img = censor_img.resize((width, int(height / 5)))
        img.paste(censor_img, (0, int(height * 2 / 5)))

    #splits the image and half and shows the mirror image
    elif filter_type == 'mirror':
        for i in range(int(width / 2)):
            for j in range(height):
                img.putpixel((i, j), img.getpixel((width - i - 1, j)))

    #rotates image by 90 degrees counter clockwise
    elif filter_type == 'rotate_cc':
        img = img.rotate(90)

    #flips the image to show the 'opposite' verision
    elif filter_type == 'flip':
        img = img.transpose(Image.FLIP_LEFT_RIGHT)

    #applies several provided ImageFilter's to make the image seem a forgotten memory
    elif filter_type == 'blocked_out':
        img = img.filter(ImageFilter.CONTOUR)
        img = img.filter(ImageFilter.SHARPEN)
        img = img.filter(ImageFilter.DETAIL)
        img = img.filter(ImageFilter.SMOOTH)
        img = img.filter(ImageFilter.FIND_EDGES)

    #changes the color space from rgb to xyz
    elif filter_type == 'feeling_green':
        mat = (0.412453, 0.357580, 0.180423, 0, 0.212671, 0.715160, 0.072169,
               0, 0.019334, 0.119193, 0.950227, 0)
        img = img.convert("RGB", mat)

    #applies a jester hat logo on the bottom right corner of the image
    elif filter_type == 'joker_logo':
        logo_img = Image.open(
            BytesIO(b64decode(logo_str[logo_str.index(',') + 1:])))
        position = ((img.width - logo_img.width),
                    (img.height - logo_img.height))
        img.paste(logo_img, position, logo_img)

    #swaps color channels blue and red
    elif filter_type == 'swap_blue_red':
        r, g, b = img.split()
        img = Image.merge('RGB', (b, g, r))

    #negate the image using ImageOps
    elif filter_type == 'forgotten_memory':
        img = ImageOps.invert(img)

    #apply a black border around the image
    elif filter_type == 'border_black':
        img = ImageOps.expand(img, border=50, fill='black')
        img = img.resize((width, height))

    #apply a gold border around the image
    elif filter_type == 'border_gold':
        img = ImageOps.expand(img, border=50, fill='#FFD700')
        img = img.resize((width, height))

    #blurs the perimeter of the image
    elif filter_type == 'border_blur':
        RADIUS = 20
        perim = 2 * RADIUS
        back = Image.new('RGB', (width + perim, height + perim),
                         (255, 255, 255))
        back.paste(img, (RADIUS, RADIUS))

        mask = Image.new('L', (width + perim, height + perim), 255)
        blck = Image.new('L', (width - perim, height - perim), 0)
        mask.paste(blck, (perim, perim))

        blur = back.filter(ImageFilter.GaussianBlur(RADIUS / 2))
        back.paste(blur, mask=mask)
        img = back
        img = img.resize((width, height))

    #add text to image
    elif filter_type == 'quote_it':
        draw = ImageDraw.Draw(img)
        font1 = ImageFont.truetype('app/filterfonts/Roboto-BoldItalic.ttf',
                                   size=35)
        font2 = ImageFont.truetype('app/filterfonts/Roboto-Thin.ttf', size=40)
        font3 = ImageFont.truetype('app/filterfonts/Satisfy-Regular.ttf',
                                   size=40)
        font4 = ImageFont.truetype(
            'app/filterfonts/JustAnotherHand-Regular.ttf', size=40)
        font5 = ImageFont.truetype('app/filterfonts/Schoolbell-Regular.ttf',
                                   size=40)
        font6 = ImageFont.truetype('app/filterfonts/Tinos-Regular.ttf',
                                   size=40)
        font = random.choice([font1, font2, font3, font4, font5, font6])
        quotes = "Don't cry because it's over, smile because it happened.",\
                 "Not my circus, not my monkeys.",\
                 "Goals transform a random walk into a chase.",\
                 "WE LOVE TRELLO.",\
                 "Why are you dressed like someone died?",\
                 "Life Saving Tip: Do not eat erasers. Even if they smell like Japanese blue soda candy!",\
                 "YOU'RE*",\
                 "Can you get in done by tonight?",\
                 "I red dictionaries durig my childhood, thas why i splle goo",\
                 "I love deadlines. I love the whooshing noise they make as they go by."
        quote = random.choice(quotes)
        x, y = font.getsize(quote)
        white_text = 'rgb(255,255,255)'
        black_text = 'rgb(0, 0, 0)'
        gold_text = 'rgb(255, 215, 0)'
        steel_blue_text = 'rgb(176, 196, 222)'
        color = random.choice(
            [white_text, black_text, gold_text, steel_blue_text])
        quote = textwrap.fill(quote, width=35)
        draw.text(((width - x) / width, (height - y) / 2),
                  quote,
                  fill=color,
                  font=font)

    return convert_to_b64(img, meta_data)
Esempio n. 16
0
                    break
                if n >= n_max:
                    break
                for i in range(1, n + 1):
                    if 0 in [
                            pixb[x + i, y + n], pixb[x + i, y - n],
                            pixb[x - i, y + n], pixb[x - i, y - n],
                            pixb[x + n, y + i], pixb[x + n, y - i],
                            pixb[x - n, y + i], pixb[x - n, y - i]
                    ]:
                        flag = False
                        l = sqrt(n**2 + i**2)
                        a = (1 - l / n_max) / 2
        if result_bit == sourse_bit:
            b1 = b0
        else:
            b1 = int(r_end * (0.5 + (b0 - s_mid) /
                              (2 * max(abs(b_min), b_max))))
        x1 = x - img0.size[0] / 2
        if 0 <= x1 < img0.size[0]:
            draw_surf.point((x1, y), b1)
            draw_mask.point((x1, y), int(a * r_end))
    p = x * 200 / img0.size[0]
    if p % 5 < 0.01:
        print(str(int(p / 4)) + " %")

img1.paste(back, (0, 0), mask)
img1_blur = img1.filter(ImageFilter.GaussianBlur(n_max))
img1.paste(img1_blur, (0, 0), mask)
img1.save(save_path)
print("100 %")
def postprocess(outputs, ctx):
    num_detection = int(outputs['num_detections'][0])

    def return_original():
        image_bytes = io.BytesIO()
        ctx.image.save(image_bytes, format='PNG')
        outputs['output'] = image_bytes.getvalue()
        return outputs

    if num_detection < 1:
        return return_original()

    width = ctx.image.size[0]
    height = ctx.image.size[1]
    image_area = width * height
    detection_boxes = outputs["detection_boxes"][0][:num_detection]
    detection_boxes = detection_boxes * [height, width, height, width]
    detection_boxes = detection_boxes.astype(np.int32)
    # detection_scores = outputs["detection_scores"][0][:num_detection]
    detection_classes = outputs["detection_classes"][0][:num_detection]
    detection_masks = outputs["detection_masks"][0][:num_detection]

    masks = []
    for i in range(num_detection):
        if int(detection_classes[i]) not in ctx.object_classes:
            continue
        mask_image = Image.fromarray(detection_masks[i])
        box = detection_boxes[i]
        mask_image = mask_image.resize((box[3] - box[1], box[2] - box[0]), ctx.interpolation)
        box_mask = np.array(mask_image)
        box_mask = np.pad(box_mask, ((box[0], height - box[2]), (box[1], width - box[3])), 'constant')
        area = int(np.sum(np.greater_equal(box_mask, ctx.pixel_threshold).astype(np.int32)))
        if area * 100 / image_area < ctx.area_threshold:
            continue
        masks.append((area, box_mask))

    if len(masks) < 1:
        return return_original()
    masks = sorted(masks, key=lambda row: -row[0])
    total_mask = np.zeros((height, width), np.float32)
    for i in range(min(len(masks), ctx.max_objects)):
        total_mask = np.maximum(total_mask,masks[i][1])
    if ctx.image_filter == 0:
        mask = np.less(total_mask, ctx.pixel_threshold)
        image = np.array(ctx.image)
        image = np.dstack((image, np.ones((height, width)) * 255))
        image[mask] = 0
        image = Image.fromarray(np.uint8(image))
    elif ctx.image_filter == 5:
        #mask = np.less(total_mask, ctx.pixel_threshold)
        #total_mask[mask] = 0
        total_mask = total_mask*255
        image = Image.fromarray(np.uint8(total_mask))
    else:
        mask = np.greater_equal(total_mask, ctx.pixel_threshold)
        image = np.array(ctx.image)
        objects = image[mask]
        radius = min(max(ctx.blur_radius,2),10)
        image = ctx.image.filter(ImageFilter.GaussianBlur(radius=radius))
        image = np.array(image)
        image[mask] = objects
        image = Image.fromarray(np.uint8(image))

    image_bytes = io.BytesIO()
    image.save(image_bytes, format='PNG')
    outputs['output'] = image_bytes.getvalue()
    return outputs
Esempio n. 18
0
    scaled_im = im.resize((w,h))
    st.image(scaled_im)
    if sv:
        scaled_im.save('output.png',format='png')
deg = st.slider('degrees',min_value==0,max_value=360)
svr = st.checkbox('save rotated image?')
if st.button('rotate image') and im:
    rot_img = img.rotate(deg,fillcolor=colr)
    st.image(rot_img)
    if svr:
        rot_img.save('rotated.png',format='png')
if st.checkbox('show filters'):
    cols = st.beta_column(3) 
    with cols[0]:
        st.image(im.filter(ImageFilter.EMBOSS,use_column_width=True))
    with cols[1]:
        st.image(im.filter(ImageFilter.CONTOUR),use_column_width=True)
    with cols[2]:
        st.image(im.filter(ImageFilter.GaussianBlur(10)),use_column_width=True)


    cols = st.beta_column(3) 
    with cols[0]:
        st.image(im.filter(ImageFilter.MinFilter,use_column_width=True))
    with cols[1]:
        st.image(im.filter(ImageFilter.MaxFilter),use_column_width=True)
    with cols[2]:
        st.image(im.filter(ImageFilter.MedianFilter(7)),use_column_width=True)


 
Esempio n. 19
0
 def to_image(self, flip=False):
     if flip:
         return self.img.transpose(Image.FLIP_LEFT_RIGHT).filter(ImageFilter.GaussianBlur(self.blur_radius))
     else:
         return self.img.filter(ImageFilter.GaussianBlur(self.blur_radius))
Esempio n. 20
0
def gblur_patches(Iclean):
    Pclean = getPatchesDict(Iclean, [32, 32],
                            noPatches=4000,
                            entropy_th=1.0,
                            stride=[32, 32])
    idx = Pclean.shape[0]
    x_clean = np.zeros((13 * idx, 32, 32, 3))
    x_dist = np.zeros((13 * idx, 32, 32, 3))
    im = Image.fromarray(np.uint8(Iclean))
    # No distortion
    Pdist = Pclean
    x_clean[0:idx, :, :, :] = Pclean
    x_dist[0:idx, :, :, :] = Pdist
    # Distortion level 1
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=0.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[idx:2 * idx, :, :, :] = Pclean
    x_dist[idx:2 * idx, :, :, :] = Pdist
    # Distortion level 2
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=1)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[2 * idx:3 * idx, :, :, :] = Pclean
    x_dist[2 * idx:3 * idx, :, :, :] = Pdist
    # Distortion level 3
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=1.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[3 * idx:4 * idx, :, :, :] = Pclean
    x_dist[3 * idx:4 * idx, :, :, :] = Pdist
    # Distortion level 4
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=2)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[4 * idx:5 * idx, :, :, :] = Pclean
    x_dist[4 * idx:5 * idx, :, :, :] = Pdist
    # Distortion level 5
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=2.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[5 * idx:6 * idx, :, :, :] = Pclean
    x_dist[5 * idx:6 * idx, :, :, :] = Pdist
    # Distortion level 6
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=3)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[6 * idx:7 * idx, :, :, :] = Pclean
    x_dist[6 * idx:7 * idx, :, :, :] = Pdist
    # Distortion level 7
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=3.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[7 * idx:8 * idx, :, :, :] = Pclean
    x_dist[7 * idx:8 * idx, :, :, :] = Pdist
    # Distortion level 8
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=4)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[8 * idx:9 * idx, :, :, :] = Pclean
    x_dist[8 * idx:9 * idx, :, :, :] = Pdist
    # Distortion level 9
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=4.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[9 * idx:10 * idx, :, :, :] = Pclean
    x_dist[9 * idx:10 * idx, :, :, :] = Pdist
    # Distortion level 10
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[10 * idx:11 * idx, :, :, :] = Pclean
    x_dist[10 * idx:11 * idx, :, :, :] = Pdist
    # Distortion level 11
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=5.5)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[11 * idx:12 * idx, :, :, :] = Pclean
    x_dist[11 * idx:12 * idx, :, :, :] = Pdist
    # Distortion level 12
    Idist = np.array(im.filter(ImageFilter.GaussianBlur(radius=6)))
    Pdist = getPatchesDict(Idist, [32, 32],
                           noPatches=4000,
                           entropy_th=1.0,
                           stride=[32, 32])
    x_clean[12 * idx:13 * idx, :, :, :] = Pclean
    x_dist[12 * idx:13 * idx, :, :, :] = Pdist

    return x_clean, x_dist
Esempio n. 21
0
 def to_image(self, canvas_color=(255, 255, 255)):
     canvas = Image.new('RGBA', self.size, canvas_color + (0,))
     paste_with_blured_borders(canvas, self.img, self.position, border_width=self.blured_border_width)
     if self.as_negative:
         canvas = canvas.filter(ImageFilter.GaussianBlur(self.blur_radius))
     return canvas
Esempio n. 22
0
def genBG(img, size, blur=41, bright=0.35):
    img = cropBG(img, size)
    img_blur = img.filter(ImageFilter.GaussianBlur(radius=blur))
    enhancer = ImageEnhance.Brightness(img_blur)
    output = enhancer.enhance(bright)
    return output
def post_process_particle_layer(particle_layer):
    particle_layer = ImageEnhance.Contrast(particle_layer).enhance(1.5)
    particle_layer = ImageEnhance.Brightness(particle_layer).enhance(2.2)
    particle_layer = particle_layer.filter(
        ImageFilter.GaussianBlur(radius=1.5))
    return particle_layer
Esempio n. 24
0
def glowText(img,
             text=None,
             font_size=35,
             font_set=None,
             color=(255, 255, 255, 255),
             blur=2,
             logo=None,
             use_glow=True,
             yoffset=0):
    width, height = img.size
    ratio = 2
    width = width * ratio
    height = height * ratio
    font_size = font_size * ratio
    blur = blur * ratio

    if font_set is None:
        _font = ImageFont.truetype("arial.ttf", font_size)
    else:
        _font = "arial.ttf"
        for font_i in [
                font_set,
                getPath("Source/font.otf"),
                getPath("Source/font.otf"), "arial.ttf"
        ]:
            try:
                _font = ImageFont.truetype(font_i, font_size)
                break
            except:
                print("Cannot Use Font: {0}".format(font_i))

    canvas = Image.new('RGBA', (width, height), color[:-1] + (0, ))
    draw = ImageDraw.Draw(canvas)
    if text:
        w, h = draw.textsize(text, font=_font)
    else:
        w, h = 0, 0
    xoffset = 0
    if logo is not None:
        lg_w, lg_h = logo.size
        hoffset = 1.1
        lg_nh = round(font_size * hoffset)
        lg_nw = round(lg_w * lg_nh / lg_h)
        logo = logo.resize((lg_nw, lg_nh), Image.ANTIALIAS)
        if text:
            xoffset = lg_nw + font_size / 4
        else:
            xoffset = lg_nw
        w = w + xoffset
        _x_logo = int(round((width - w) / 2))
        _y_logo = int(round(yoffset * ratio - font_size * (hoffset - 1) / 2))
        try:
            canvas.paste(logo, (_x_logo, _y_logo), logo)
        except:
            canvas.paste(logo, (_x_logo, _y_logo))
    if text:
        draw.text(((width - w) / 2 + xoffset, yoffset * ratio),
                  text,
                  fill=color,
                  font=_font)
    if use_glow:
        mask_blur = canvas.split()[-1]
        mask_blur = mask_blur.filter(ImageFilter.GaussianBlur(radius=blur * 2))
        fg_blur = canvas.split()[0]
        fg_blur = fg_blur.filter(ImageFilter.GaussianBlur(radius=blur * 2))
        glow_text = Image.merge("RGBA", (fg_blur, fg_blur, fg_blur, mask_blur))
        glow_text = glow_text.resize(img.size, Image.ANTIALIAS)
        canvas = canvas.resize(img.size, Image.ANTIALIAS)
        img.paste(glow_text, (0, 0), mask=glow_text)
        img.paste(canvas, (0, 0), mask=canvas)
    else:
        canvas = canvas.resize(img.size, Image.ANTIALIAS)
        img.paste(canvas, (0, 0), mask=canvas)
    return img
Esempio n. 25
0
 def __call__(self, img):
     radius = np.random.uniform(0, self.max_radius)
     if np.random.random() < self.rand_prob:
         return img.filter(ImageFilter.GaussianBlur(radius))
     else:
         return img
Esempio n. 26
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Find latent representation of reference images using perceptual losses',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('src_dir', help='Directory with images for encoding')
    parser.add_argument('generated_images_dir',
                        help='Directory for storing generated images')
    parser.add_argument('dlatent_dir',
                        help='Directory for storing dlatent representations')
    parser.add_argument('--data_dir',
                        default='data',
                        help='Directory for storing optional models')
    parser.add_argument('--mask_dir',
                        default='masks',
                        help='Directory for storing optional masks')
    parser.add_argument('--load_last',
                        default='',
                        help='Start with embeddings from directory')
    parser.add_argument(
        '--dlatent_avg',
        default='',
        help=
        'Use dlatent from file specified here for truncation instead of dlatent_avg from Gs'
    )
    parser.add_argument(
        '--model_url',
        default=
        'https://drive.google.com/uc?id=1MEGjdvVpUsu1jB4zrXZN7Y4kBBOzizDQ',
        help='Fetch a StyleGAN model to train on from this URL'
    )  # karras2019stylegan-ffhq-1024x1024.pkl
    parser.add_argument('--model_res',
                        default=1024,
                        help='The dimension of images in the StyleGAN model',
                        type=int)
    parser.add_argument('--batch_size',
                        default=1,
                        help='Batch size for generator and perceptual model',
                        type=int)
    parser.add_argument(
        '--optimizer',
        default='ggt',
        help='Optimization algorithm used for optimizing dlatents')

    # Perceptual model params
    parser.add_argument('--image_size',
                        default=256,
                        help='Size of images for perceptual model',
                        type=int)
    parser.add_argument('--resnet_image_size',
                        default=256,
                        help='Size of images for the Resnet model',
                        type=int)
    parser.add_argument('--lr',
                        default=0.25,
                        help='Learning rate for perceptual model',
                        type=float)
    parser.add_argument('--decay_rate',
                        default=0.9,
                        help='Decay rate for learning rate',
                        type=float)
    parser.add_argument('--iterations',
                        default=100,
                        help='Number of optimization steps for each batch',
                        type=int)
    parser.add_argument(
        '--decay_steps',
        default=4,
        help='Decay steps for learning rate decay (as a percent of iterations)',
        type=float)
    parser.add_argument('--early_stopping',
                        default=True,
                        help='Stop early once training stabilizes',
                        type=str2bool,
                        nargs='?',
                        const=True)
    parser.add_argument('--early_stopping_threshold',
                        default=0.5,
                        help='Stop after this threshold has been reached',
                        type=float)
    parser.add_argument('--early_stopping_patience',
                        default=10,
                        help='Number of iterations to wait below threshold',
                        type=int)
    parser.add_argument(
        '--load_effnet',
        default='data/finetuned_effnet.h5',
        help='Model to load for EfficientNet approximation of dlatents')
    parser.add_argument(
        '--load_resnet',
        default='data/finetuned_resnet.h5',
        help='Model to load for ResNet approximation of dlatents')
    parser.add_argument(
        '--use_preprocess_input',
        default=True,
        help='Call process_input() first before using feed forward net',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--use_best_loss',
        default=True,
        help='Output the lowest loss value found as the solution',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--average_best_loss',
        default=0.25,
        help=
        'Do a running weighted average with the previous best dlatents found',
        type=float)
    parser.add_argument('--sharpen_input',
                        default=True,
                        help='Sharpen the input images',
                        type=str2bool,
                        nargs='?',
                        const=True)

    # Loss function options
    parser.add_argument(
        '--use_vgg_loss',
        default=0.4,
        help='Use VGG perceptual loss; 0 to disable, > 0 to scale.',
        type=float)
    parser.add_argument('--use_vgg_layer',
                        default=9,
                        help='Pick which VGG layer to use.',
                        type=int)
    parser.add_argument(
        '--use_pixel_loss',
        default=1.5,
        help='Use logcosh image pixel loss; 0 to disable, > 0 to scale.',
        type=float)
    parser.add_argument(
        '--use_mssim_loss',
        default=200,
        help='Use MS-SIM perceptual loss; 0 to disable, > 0 to scale.',
        type=float)
    parser.add_argument(
        '--use_lpips_loss',
        default=100,
        help='Use LPIPS perceptual loss; 0 to disable, > 0 to scale.',
        type=float)
    parser.add_argument(
        '--use_l1_penalty',
        default=0.5,
        help='Use L1 penalty on latents; 0 to disable, > 0 to scale.',
        type=float)
    parser.add_argument('--use_discriminator_loss',
                        default=0.5,
                        help='Use trained discriminator to evaluate realism.',
                        type=float)
    parser.add_argument(
        '--use_adaptive_loss',
        default=False,
        help=
        'Use the adaptive robust loss function from Google Research for pixel and VGG feature loss.',
        type=str2bool,
        nargs='?',
        const=True)

    # Generator params
    parser.add_argument('--randomize_noise',
                        default=False,
                        help='Add noise to dlatents during optimization',
                        type=str2bool,
                        nargs='?',
                        const=True)
    parser.add_argument(
        '--tile_dlatents',
        default=False,
        help='Tile dlatents to use a single vector at each scale',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--clipping_threshold',
        default=2.0,
        help='Stochastic clipping of gradient values outside of this threshold',
        type=float)

    # Masking params
    parser.add_argument('--load_mask',
                        default=False,
                        help='Load segmentation masks',
                        type=str2bool,
                        nargs='?',
                        const=True)
    parser.add_argument(
        '--face_mask',
        default=True,
        help='Generate a mask for predicting only the face area',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--use_grabcut',
        default=True,
        help=
        'Use grabcut algorithm on the face mask to better segment the foreground',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--scale_mask',
        default=1.4,
        help='Look over a wider section of foreground for grabcut',
        type=float)
    parser.add_argument(
        '--composite_mask',
        default=True,
        help='Merge the unmasked area back into the generated image',
        type=str2bool,
        nargs='?',
        const=True)
    parser.add_argument(
        '--composite_blur',
        default=8,
        help='Size of blur filter to smoothly composite the images',
        type=int)

    # Video params
    parser.add_argument('--video_dir',
                        default='videos',
                        help='Directory for storing training videos')
    parser.add_argument('--output_video',
                        default=False,
                        help='Generate videos of the optimization process',
                        type=bool)
    parser.add_argument('--video_codec',
                        default='MJPG',
                        help='FOURCC-supported video codec name')
    parser.add_argument('--video_frame_rate',
                        default=24,
                        help='Video frames per second',
                        type=int)
    parser.add_argument('--video_size',
                        default=512,
                        help='Video size in pixels',
                        type=int)
    parser.add_argument(
        '--video_skip',
        default=1,
        help='Only write every n frames (1 = write every frame)',
        type=int)

    args, other_args = parser.parse_known_args()

    args.decay_steps *= 0.01 * args.iterations  # Calculate steps as a percent of total iterations

    if args.output_video:
        import cv2
        synthesis_kwargs = dict(output_transform=dict(
            func=tflib.convert_images_to_uint8, nchw_to_nhwc=False),
                                minibatch_size=args.batch_size)

    ref_images = [
        os.path.join(args.src_dir, x) for x in os.listdir(args.src_dir)
    ]
    ref_images = list(filter(os.path.isfile, ref_images))

    if len(ref_images) == 0:
        raise Exception('%s is empty' % args.src_dir)

    os.makedirs(args.data_dir, exist_ok=True)
    os.makedirs(args.mask_dir, exist_ok=True)
    os.makedirs(args.generated_images_dir, exist_ok=True)
    os.makedirs(args.dlatent_dir, exist_ok=True)
    os.makedirs(args.video_dir, exist_ok=True)

    # Initialize generator and perceptual model
    tflib.init_tf()
    with open(args.model_url, 'rb') as f:
        #with dnnlib.util.open_url(args.model_url, cache_dir=config.cache_dir) as f:
        generator_network, discriminator_network, Gs_network = pickle.load(f)

    generator = Generator(Gs_network,
                          args.batch_size,
                          clipping_threshold=args.clipping_threshold,
                          tiled_dlatent=args.tile_dlatents,
                          model_res=args.model_res,
                          randomize_noise=args.randomize_noise)
    if (args.dlatent_avg != ''):
        generator.set_dlatent_avg(np.load(args.dlatent_avg))

    perc_model = None
    if (args.use_lpips_loss > 0.00000001):
        with open('model/vgg.pkl', 'rb') as f:
            #with dnnlib.util.open_url('https://drive.google.com/uc?id=1pTDtnnLXTYpcWNv2dtzb32F-tHDlU6di', cache_dir=config.cache_dir) as f:
            perc_model = pickle.load(f)
    perceptual_model = PerceptualModel(args,
                                       perc_model=perc_model,
                                       batch_size=args.batch_size)
    perceptual_model.build_perceptual_model(generator, discriminator_network)

    ff_model = None

    # Optimize (only) dlatents by minimizing perceptual loss between reference and generated images in feature space
    for images_batch in tqdm(split_to_batches(ref_images, args.batch_size),
                             total=len(ref_images) // args.batch_size):
        names = [
            os.path.splitext(os.path.basename(x))[0] for x in images_batch
        ]
        if args.output_video:
            video_out = {}
            for name in names:
                video_out[name] = cv2.VideoWriter(
                    os.path.join(args.video_dir, '{}.avi'.format(name)),
                    cv2.VideoWriter_fourcc(*args.video_codec),
                    args.video_frame_rate, (args.video_size, args.video_size))

        perceptual_model.set_reference_images(images_batch)
        dlatents = None
        if (args.load_last != ''):  # load previous dlatents for initialization
            for name in names:
                dl = np.expand_dims(np.load(
                    os.path.join(args.load_last, '{}.npy'.format(name))),
                                    axis=0)
                if (dlatents is None):
                    dlatents = dl
                else:
                    dlatents = np.vstack((dlatents, dl))
        else:
            if (ff_model is None):
                if os.path.exists(args.load_resnet):
                    from keras.applications.resnet50 import preprocess_input
                    print("Loading ResNet Model:")
                    ff_model = load_model(args.load_resnet)
            if (ff_model is None):
                if os.path.exists(args.load_effnet):
                    import efficientnet
                    from efficientnet import preprocess_input
                    print("Loading EfficientNet Model:")
                    ff_model = load_model(args.load_effnet)
            if (ff_model
                    is not None):  # predict initial dlatents with ResNet model
                if (args.use_preprocess_input):
                    dlatents = ff_model.predict(
                        preprocess_input(
                            load_images(images_batch,
                                        image_size=args.resnet_image_size)))
                else:
                    dlatents = ff_model.predict(
                        load_images(images_batch,
                                    image_size=args.resnet_image_size))
        if dlatents is not None:
            generator.set_dlatents(dlatents)
        op = perceptual_model.optimize(generator.dlatent_variable,
                                       iterations=args.iterations,
                                       use_optimizer=args.optimizer)
        pbar = tqdm(op, leave=False, total=args.iterations)
        vid_count = 0
        best_loss = None
        best_dlatent = None
        avg_loss_count = 0
        if args.early_stopping:
            avg_loss = prev_loss = None
        for loss_dict in pbar:
            if args.early_stopping:  # early stopping feature
                if prev_loss is not None:
                    if avg_loss is not None:
                        avg_loss = 0.5 * avg_loss + (prev_loss -
                                                     loss_dict["loss"])
                        if avg_loss < args.early_stopping_threshold:  # count while under threshold; else reset
                            avg_loss_count += 1
                        else:
                            avg_loss_count = 0
                        if avg_loss_count > args.early_stopping_patience:  # stop once threshold is reached
                            print("")
                            break
                    else:
                        avg_loss = prev_loss - loss_dict["loss"]
            pbar.set_description(" ".join(names) + ": " + "; ".join(
                ["{} {:.4f}".format(k, v) for k, v in loss_dict.items()]))
            if best_loss is None or loss_dict["loss"] < best_loss:
                if best_dlatent is None or args.average_best_loss <= 0.00000001:
                    best_dlatent = generator.get_dlatents()
                else:
                    best_dlatent = 0.25 * best_dlatent + 0.75 * generator.get_dlatents(
                    )
                if args.use_best_loss:
                    generator.set_dlatents(best_dlatent)
                best_loss = loss_dict["loss"]
            if args.output_video and (vid_count % args.video_skip == 0):
                batch_frames = generator.generate_images()
                for i, name in enumerate(names):
                    video_frame = PIL.Image.fromarray(
                        batch_frames[i], 'RGB').resize(
                            (args.video_size, args.video_size),
                            PIL.Image.LANCZOS)
                    video_out[name].write(
                        cv2.cvtColor(
                            np.array(video_frame).astype('uint8'),
                            cv2.COLOR_RGB2BGR))
            generator.stochastic_clip_dlatents()
            prev_loss = loss_dict["loss"]
        if not args.use_best_loss:
            best_loss = prev_loss
        print(" ".join(names), " Loss {:.4f}".format(best_loss))

        if args.output_video:
            for name in names:
                video_out[name].release()

        # Generate images from found dlatents and save them
        if args.use_best_loss:
            generator.set_dlatents(best_dlatent)
        generated_images = generator.generate_images()
        generated_dlatents = generator.get_dlatents()
        for img_array, dlatent, img_path, img_name in zip(
                generated_images, generated_dlatents, images_batch, names):
            mask_img = None
            if args.composite_mask and (args.load_mask or args.face_mask):
                _, im_name = os.path.split(img_path)
                mask_img = os.path.join(args.mask_dir, '{}'.format(im_name))
            if args.composite_mask and mask_img is not None and os.path.isfile(
                    mask_img):
                orig_img = PIL.Image.open(img_path).convert('RGB')
                width, height = orig_img.size
                imask = PIL.Image.open(mask_img).convert('L').resize(
                    (width, height))
                imask = imask.filter(
                    ImageFilter.GaussianBlur(args.composite_blur))
                mask = np.array(imask) / 255
                mask = np.expand_dims(mask, axis=-1)
                img_array = mask * np.array(img_array) + (
                    1.0 - mask) * np.array(orig_img)
                img_array = img_array.astype(np.uint8)
                #img_array = np.where(mask, np.array(img_array), orig_img)
            img = PIL.Image.fromarray(img_array, 'RGB')
            img.save(
                os.path.join(args.generated_images_dir,
                             '{}.png'.format(img_name)), 'PNG')
            np.save(os.path.join(args.dlatent_dir, '{}.npy'.format(img_name)),
                    dlatent)

        generator.reset_dlatents()
from PIL import Image, ImageFilter

#resimleri açmamızı sağlıyorlar
image = Image.open("Kaplan.jpg")
image2 = Image.open("aslan.jpg")

#kaplan resmini farklı bir adla kaydetmemizi sağlayan komut satırı
image.save("kaplan2.jpg")

#resmimizin yönünü çevirmemizi sağlıyor..
image.rotate(155).save("kaplan3.jpg")

#aslan resmimizi siyah beyaz yapıyor...
image2.convert(mode="L").save("aslanSiyahBeyaz.jpg")

# kaplan resmine yeni boyut veriyoruz.....
degistir = (683, 360)
image.thumbnail(degistir)
image.save("kaplan4.jpg")

#kaplan resmini blurluyoruz...
image.filter(ImageFilter.GaussianBlur(10)).save("kaplan5.jpg")

#resmi kırpıyoruz...
kirpilacakAlan = (0, 0, 400, 300)
image.crop(kirpilacakAlan).save("kaplan6.jpg")
Esempio n. 28
0
def generate(PMS_uuid, url, authtoken, resolution, blurRadius, gradientTemplate, titleText, subtitleText, titleSize, subtitleSize, textColor, align, valign, offsetx, offsety, lineheight, blurStart, blurEnd, statusText):
    cachepath = sys.path[0]+"/assets/fanartcache"
    stylepath = sys.path[0]+"/assets/thumbnails"

    # Create cache filename
    id = re.search('/library/metadata/(?P<ratingKey>\S+)/art/(?P<fileId>\S+)', url)
    if id:
        # assumes URL in format "/library/metadata/<ratingKey>/art/fileId>"
        id = id.groupdict()
        cachefile = urllib.quote_plus(PMS_uuid +"_"+ id['ratingKey'] +"_"+ id['fileId'] +"_"+ resolution +"_"+ blurRadius) + titleText + subtitleText + gradientTemplate + ".jpg"
    else:
        fileid = posixpath.basename(urlparse.urlparse(url).path)
        cachefile = urllib.quote_plus(PMS_uuid +"_"+ fileid +"_"+ resolution +"_"+ blurRadius) + titleText + subtitleText + gradientTemplate + ".jpg"  # quote: just to make sure...
    
    # Already created?
    dprint(__name__, 1, 'Check for Cachefile.')  # Debug
    if os.path.isfile(cachepath+"/"+cachefile):
        dprint(__name__, 1, 'Cachefile  found.')  # Debug
        return "/fanartcache/"+cachefile
    
    # No! Request Background from PMS
    dprint(__name__, 1, 'No Cachefile found. Generating Background.')  # Debug
    try:
        dprint(__name__, 1, 'Getting Remote Image.')  # Debug
        xargs = {}
        if authtoken:
            xargs['X-Plex-Token'] = authtoken
        request = urllib2.Request(url, None, xargs)
        response = urllib2.urlopen(request).read()
        background = Image.open(io.BytesIO(response))
    except urllib2.URLError as e:
        dprint(__name__, 0, 'URLError: {0} // url: {1}', e.reason, url)
        return "/thumbnails/Background_blank_" + resolution + ".jpg"
    except urllib2.HTTPError as e:
        dprint(__name__, 0, 'HTTPError: {0} {1} // url: {2}', str(e.code), e.msg, url)
        return "/thumbnails/Background_blank_" + resolution + ".jpg"
    except IOError as e:
        dprint(__name__, 0, 'IOError: {0} // url: {1}', str(e), url)
        return "/thumbnails/Background_blank_" + resolution + ".jpg"
    
    blurRadius = int(blurRadius)
    
    # Get gradient template
    dprint(__name__, 1, 'Merging Layers.')  # Debug
    if resolution == '1080':
        width = 1920
        height = 1080
        blurStart = (1080/100) * int(blurStart)
        blurEnd = (1080/100) * int(blurEnd)
        blurRegion = (0, blurStart, 1920, blurEnd)
        # FT: get Background based on last Parameter
        layer = Image.open(stylepath + "/" + gradientTemplate + "_1080.png")
    else:
        width = 1280
        height = 720
        blurStart = (720/100) * int(blurStart)
        blurEnd = (720/100) * int(blurEnd)
        blurRegion = (0, blurStart, 1280, blurEnd)
        blurRadius = int(blurRadius / 1.5)
        layer = Image.open(stylepath + "/" + gradientTemplate + "_720.png")
    
    # Set background resolution and merge layers
    try:
        bgWidth, bgHeight = background.size
        dprint(__name__,1 ,"Background size: {0}, {1}", bgWidth, bgHeight)
        dprint(__name__,1 , "aTV Height: {0}, {1}", width, height)
        
        if bgHeight != height:
            background = background.resize((width, height), Image.ANTIALIAS)
            dprint(__name__,1 , "Resizing background")
        
        if blurRadius != 0:
            dprint(__name__,1 , "Blurring Lower Region")
            imgBlur = background.crop(blurRegion)
            imgBlur = imgBlur.filter(ImageFilter.GaussianBlur(blurRadius))
            background.paste(imgBlur, blurRegion)

        background.paste(layer, ( 0, 0), layer)

        background = textToImage(stylepath, background, resolution, titleText, titleSize, textColor, align, valign, offsetx, offsety)

        if subtitleText != "":
            offsety = int(offsety) + int(lineheight)
            background = textToImage(stylepath, background, resolution, subtitleText, subtitleSize, textColor, align, valign, offsetx, offsety)

        # Handle 1080 / atv3 Text
        statusSize = 20
        statusX = 80
        statusY = 25

        if resolution == '1080':
            statusSize = fullHDtext(statusSize)
            statusX = fullHDtext(statusX)
            statusY = fullHDtext(statusY)
    
        if statusText != "":
            background = textToImage(stylepath, background, resolution, statusText, statusSize, textColor, "right", "top", statusX, statusY)

        # Save to Cache
        background.save(cachepath+"/"+cachefile)
    except:
        dprint(__name__, 0, 'Error - Failed to generate background image.\n{0}', traceback.format_exc())
        return "/thumbnails/Background_blank_" + resolution + ".jpg"
    
    dprint(__name__, 1, 'Cachefile  generated.')  # Debug
    return "/fanartcache/"+cachefile
Esempio n. 29
0
def blur(event):
    img = Image.open(root.file)
    blurred = img.filter(ImageFilter.GaussianBlur(radius=15))
    blurred.save("file.png")
Esempio n. 30
0
def blur(image):
    many = 5
    return image.filter(ImageFilter.GaussianBlur(many)).convert('RGB')