Ejemplo n.º 1
0
 def resizeImage(self):
     if self.image.size[0] <= self.size[0] and self.image.size[1] <= self.size[1]:
         method = Image.BICUBIC
     else:
         method = Image.LANCZOS
     if self.opt.stretch:
         self.image = self.image.resize(self.size, method)
     elif self.image.size[0] <= self.size[0] and self.image.size[1] <= self.size[1] and not self.opt.upscale:
         if self.opt.format == 'CBZ':
             borderw = int((self.size[0] - self.image.size[0]) / 2)
             borderh = int((self.size[1] - self.image.size[1]) / 2)
             self.image = ImageOps.expand(self.image, border=(borderw, borderh), fill=self.fill)
             if self.image.size[0] != self.size[0] or self.image.size[1] != self.size[1]:
                 self.image = ImageOps.fit(self.image, self.size, method=Image.BICUBIC, centering=(0.5, 0.5))
     else:
         if self.opt.format == 'CBZ':
             ratioDev = float(self.size[0]) / float(self.size[1])
             if (float(self.image.size[0]) / float(self.image.size[1])) < ratioDev:
                 diff = int(self.image.size[1] * ratioDev) - self.image.size[0]
                 self.image = ImageOps.expand(self.image, border=(int(diff / 2), 0), fill=self.fill)
             elif (float(self.image.size[0]) / float(self.image.size[1])) > ratioDev:
                 diff = int(self.image.size[0] / ratioDev) - self.image.size[1]
                 self.image = ImageOps.expand(self.image, border=(0, int(diff / 2)), fill=self.fill)
             self.image = ImageOps.fit(self.image, self.size, method=method, centering=(0.5, 0.5))
         else:
             hpercent = self.size[1] / float(self.image.size[1])
             wsize = int((float(self.image.size[0]) * float(hpercent)))
             self.image = self.image.resize((wsize, self.size[1]), method)
             if self.image.size[0] > self.size[0] or self.image.size[1] > self.size[1]:
                 self.image.thumbnail(self.size, Image.LANCZOS)
Ejemplo n.º 2
0
def put_contour(image, size=1, offset=0, contour_color=0, fill_color=0,
        opacity=100, include_image=True):
    if not has_transparency(image):
        return put_border(
                    image, size, offset, contour_color, fill_color,
                    opacity, include_image)
    image = image.convert('RGBA')
    mask = imtools.get_alpha(image)

    w, h = image.size
    outer_mask = mask.resize(
        (w + 2 * (size + offset), h + 2 * (size + offset)),
        Image.ANTIALIAS)

    inner_mask = mask.resize(
        (w + 2 * offset, h + 2 * offset),
        Image.ANTIALIAS)
    inner_mask = ImageOps.expand(inner_mask, border=size, fill=0)
    paste(outer_mask, (255 * opacity) / 100, mask=inner_mask)
    if include_image:
        image = ImageOps.expand(image, border=size + offset, fill=(0, 0, 0, 0))
        mask = ImageOps.expand(mask, border=size + offset, fill=0)
        paste(outer_mask, 255, mask=mask)

    contour = ImageOps.colorize(outer_mask, (255, 255, 255), contour_color)
    paste(contour, fill_color, mask=inner_mask)
    if include_image:
        paste(contour, image, mask=image)
    contour.putalpha(outer_mask)
    return contour
    def __call__(self, sample):
        img = sample['image']
        mask = sample['label']
        # 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 < self.crop_size:
            padh = self.crop_size - oh if oh < self.crop_size else 0
            padw = self.crop_size - ow if ow < self.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 - self.crop_size)
        y1 = random.randint(0, h - self.crop_size)
        img = img.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))
        mask = mask.crop((x1, y1, x1 + self.crop_size, y1 + self.crop_size))

        return {'image': img,
                'label': mask}
Ejemplo n.º 4
0
def border(name_image): #Funcio creada per fer un top5 del rànking creat que escollim
    mostra = open("../files/ranking_val/"+name_image+".txt",'r')
    print "Imatge mostra:"
    imagemostra = Image.open("../TerrassaBuildings900/val/images/168-2743-15592.jpg")
    y = ImageOps.expand(imagemostra,border=50,fill='blue')
    plt.figure(1),plt.imshow(y),plt.show()
    print "\n"
    print "Rànking mostra:"
    mostra_val = open("../TerrassaBuildings900/val/annotation.txt",'r')
    for line in mostra_val:
        id_im = line[0:line.index("\t")]
        if str(id_im) == name_image:
            clase_mostra = line[line.index("\t")+1:line.index("\n")]

    top = 0
    for line in mostra:
        if top<5:
            id_image = line[0:line.index("\n")]
            image_rank = Image.open("../TerrassaBuildings900/train/images/"+id_image+".jpg")
            mostra_train = open("../TerrassaBuildings900/train/annotation.txt",'r')
            for lin in mostra_train:
                id_train = lin[0:lin.index("\t")]
                if id_train == id_image:
                    clase = lin[lin.index("\t")+1:lin.index("\n")]
            if clase == clase_mostra:
                y2 = ImageOps.expand(image_rank,border=50,fill='green')
                plt.figure(top+2),plt.imshow(y2),plt.show()
            else:
                y3 = ImageOps.expand(image_rank,border=50,fill='red')
                plt.figure(top+2),plt.imshow(y3),plt.show()
            clase.strip()
        mostra_train.close()
        top += 1
Ejemplo n.º 5
0
 def resizeImage(self):
     if self.opt.bordersColor:
         fill = self.opt.bordersColor
     else:
         fill = self.fill
     # Set target size
     if self.opt.quality == 0:
         size = (self.size[0], self.size[1])
     elif self.opt.quality == 1 and not self.opt.stretch and not self.opt.upscale and self.image.size[0] <=\
             self.size[0] and self.image.size[1] <= self.size[1]:
         size = (self.size[0], self.size[1])
     elif self.opt.quality == 1:
         # Forcing upscale to make sure that margins will be not too big
         if not self.opt.stretch:
             self.opt.upscale = True
         size = (self.panelviewsize[0], self.panelviewsize[1])
     elif self.opt.quality == 2 and not self.opt.stretch and not self.opt.upscale and self.image.size[0] <=\
             self.size[0] and self.image.size[1] <= self.size[1]:
         # HQ version will not be needed
         self.noHQ = True
         return
     else:
         size = (self.panelviewsize[0], self.panelviewsize[1])
     # If stretching is on - Resize without other considerations
     if self.opt.stretch:
         if self.image.size[0] <= size[0] and self.image.size[1] <= size[1]:
             method = Image.BICUBIC
         else:
             method = Image.LANCZOS
         self.image = self.image.resize(size, method)
         return
     # If image is smaller than target resolution and upscale is off - Just expand it by adding margins
     if self.image.size[0] <= size[0] and self.image.size[1] <= size[1] and not self.opt.upscale:
         borderw = int((size[0] - self.image.size[0]) / 2)
         borderh = int((size[1] - self.image.size[1]) / 2)
         # PV is disabled when source image is smaller than device screen and upscale is off
         if self.image.size[0] <= self.size[0] and self.image.size[1] <= self.size[1]:
             self.noPV = True
         self.image = ImageOps.expand(self.image, border=(borderw, borderh), fill=fill)
         # Border can't be float so sometimes image might be 1px too small/large
         if self.image.size[0] != size[0] or self.image.size[1] != size[1]:
             self.image = ImageOps.fit(self.image, size, method=Image.BICUBIC, centering=(0.5, 0.5))
         return
     # Otherwise - Upscale/Downscale
     ratioDev = float(size[0]) / float(size[1])
     if (float(self.image.size[0]) / float(self.image.size[1])) < ratioDev:
         diff = int(self.image.size[1] * ratioDev) - self.image.size[0]
         self.image = ImageOps.expand(self.image, border=(int(diff / 2), 0), fill=fill)
     elif (float(self.image.size[0]) / float(self.image.size[1])) > ratioDev:
         diff = int(self.image.size[0] / ratioDev) - self.image.size[1]
         self.image = ImageOps.expand(self.image, border=(0, int(diff / 2)), fill=fill)
     if self.image.size[0] <= size[0] and self.image.size[1] <= size[1]:
         method = Image.BICUBIC
     else:
         method = Image.LANCZOS
     self.image = ImageOps.fit(self.image, size, method=method, centering=(0.5, 0.5))
     return
Ejemplo n.º 6
0
def apply_frame(pixbuf):
    '''
    adds a border at all four edges
    '''
    width,height = pixbuf.get_width(),pixbuf.get_height() 
    y = ImageOps.expand(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ) ,border=22,fill='black')
    y = ImageOps.expand(y ,border=42,fill='silver')
    y = ImageOps.expand(y ,border=4,fill='black')
    return I.fromImageToPixbuf(y)
Ejemplo n.º 7
0
def draw_histogram(pixbuf, height=170, fill=170, text=True):
    """Draw a histogram from <pixbuf> and return it as another pixbuf.

    The returned prixbuf will be 262x<height> px.

    The value of <fill> determines the colour intensity of the filled graphs,
    valid values are between 0 and 255.

    If <text> is True a label with the maximum pixel value will be added to
    one corner.
    """
    im = Image.new('RGB', (258, height - 4), (30, 30, 30))
    hist_data = image.pixbuf_to_pil(pixbuf).histogram()
    maximum = max(hist_data[:768] + [1])
    y_scale = float(height - 6) / maximum
    r = [int(hist_data[n] * y_scale) for n in xrange(256)]
    g = [int(hist_data[n] * y_scale) for n in xrange(256, 512)]
    b = [int(hist_data[n] * y_scale) for n in xrange(512, 768)]
    im_data = im.getdata()
    # Draw the filling colours
    for x in xrange(256):
        for y in xrange(1, max(r[x], g[x], b[x]) + 1):
            r_px = y <= r[x] and fill or 0
            g_px = y <= g[x] and fill or 0
            b_px = y <= b[x] and fill or 0
            im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, b_px))
    # Draw the outlines
    for x in xrange(1, 256):
        for y in range(r[x-1] + 1, r[x] + 1) + [r[x]] * (r[x] != 0):
            r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y))
            im_data.putpixel((x + 1, height - 5 - y), (255, g_px, b_px))
        for y in range(r[x] + 1, r[x-1] + 1):
            r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y))
            im_data.putpixel((x, height - 5 - y), (255, g_px, b_px))
        for y in range(g[x-1] + 1, g[x] + 1) + [g[x]] * (g[x] != 0):
            r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y))
            im_data.putpixel((x + 1, height - 5 - y), (r_px, 255, b_px))
        for y in range(g[x] + 1, g[x-1] + 1):
            r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y))
            im_data.putpixel((x, height - 5 - y), (r_px, 255, b_px))
        for y in range(b[x-1] + 1, b[x] + 1) + [b[x]] * (b[x] != 0):
            r_px, g_px, b_px = im_data.getpixel((x + 1, height - 5 - y))
            im_data.putpixel((x + 1, height - 5 - y), (r_px, g_px, 255))
        for y in range(b[x] + 1, b[x-1] + 1):
            r_px, g_px, b_px = im_data.getpixel((x, height - 5 - y))
            im_data.putpixel((x, height - 5 - y), (r_px, g_px, 255))
    if text:
        maxstr = 'max: ' + str(maximum)
        draw = ImageDraw.Draw(im)
        draw.rectangle((0, 0, len(maxstr) * 6 + 2, 10), fill=(30, 30, 30))
        draw.text((2, 0), maxstr, fill=(255, 255, 255))
    im = ImageOps.expand(im, 1, (80, 80, 80))
    im = ImageOps.expand(im, 1, (0, 0, 0))
    return image.pil_to_pixbuf(im)
Ejemplo n.º 8
0
def put_border(image, size, offset, contour_color, fill_color, opacity,
        include_image):
    if opacity < 100:
        fill_color = HTMLColorToRGBA(fill_color, (255 * opacity) / 100)

    if not include_image:
        w, h = image.size
        image = Image.new('RGBA', (w + 2 * offset, h + 2 * offset), fill_color)
    else:
        image = image.convert('RGBA')
        image = ImageOps.expand(image, border=offset, fill=fill_color)
    image = ImageOps.expand(image, border=size, fill=contour_color)
    return image
Ejemplo n.º 9
0
    def run(self):
        self.output().makedirs()

        image_urls = []
        country = self.measure.split('.')[0]
        for center, zoom, boundary in self.CENTER_ZOOM_BOUNDS[country]:
            lon, lat = center

            if country == 'uk':
                image_size = (300, 700, )
            else:
                image_size = (500, 500, )

            config = self._generate_config(zoom, lon, lat, boundary)

            named_map = self.get_named_map(config['layers'])
            image_urls.append('{cartodb_url}/api/v1/map/static/center/' \
                              '{layergroupid}/{zoom}/{center_lon}/{center_lat}/{x}/{y}.png'.format(
                                  cartodb_url=os.environ['CARTODB_URL'],
                                  layergroupid=named_map['layergroupid'],
                                  zoom=zoom,
                                  center_lon=lon,
                                  center_lat=lat,
                                  x=image_size[0],
                                  y=image_size[1],
                              ))

        url1 = image_urls.pop(0)
        print url1
        file1 = StringIO(requests.get(url1, stream=True).content)
        image1 = ImageOps.expand(Image.open(file1), border=10, fill='white')

        for url2 in image_urls:
            print url2
            file2 = StringIO(requests.get(url2, stream=True).content)

            image2 = ImageOps.expand(Image.open(file2), border=10, fill='white')

            (width1, height1) = image1.size
            (width2, height2) = image2.size

            result_width = width1 + width2
            result_height = max(height1, height2)

            result = Image.new('RGB', (result_width, result_height))
            result.paste(im=image1, box=(0, 0))
            result.paste(im=image2, box=(width1, 0))

            image1 = result
        image1.save(self.output().path)
Ejemplo n.º 10
0
 def createPNG(self, filename=None):
     self.format = 'png'
     self.backend = 'eps'
     self.writeTemp(fp=filename) # do not need extension here
     lilyFile = self.runThroughLily()
     if noPIL is False:
         try:
             lilyImage = Image.open(lilyFile)
             lilyImage2 = ImageOps.expand(lilyImage, 10, 'white')
             if os.name == 'nt':
                 format = 'png'
             # why are we changing format for darwin? -- did not work before
             elif sys.platform == 'darwin':
                 format = 'jpeg'
             else: # default for all other platforms
                 format = 'png'
             
             if lilyImage2.mode == "I;16":
             # @PIL88 @PIL101
             # "I;16" isn't an 'official' mode, but we still want to
             # provide a simple way to show 16-bit images.
                 base = "L"
             else:
                 base = Image.getmodebase(lilyImage2.mode)
             if base != lilyImage2.mode and lilyImage2.mode != "1":
                 file = lilyImage2.convert(base)._dump(format=format)
             else:
                 file = lilyImage2._dump(format=format)
             return file
         except:
             raise
             
     return lilyFile
Ejemplo n.º 11
0
    def _CompositePackedImages(self, outputPath, size, padding, packedImageDict):
        # Keep track of the result.
        result = True

        # Create the output image.
        outImage = Image.new("RGBA", size)

        # Composite all packed images into the output image.
        for packedImagePath, packedImageData in packedImageDict.iteritems():
            try:
                # Open the image
                image = Image.open(packedImageData[0].path)

                # Make sure it's an RGBA image.
                if image.mode != "RGBA":
                    image = image.convert("RGBA")

                # Crop the image to its bounding box.
                image = image.crop(packedImageData[0].boundingBox)

                # Pad the image.
                image = ImageOps.expand(image, padding, 0)

                # Paste the image into the output image.
                outImage.paste(image, packedImageData[1].packPosition)

            except IOError:
                result = False

        # Save the output image
        outImage.save(outputPath)

        return result
Ejemplo n.º 12
0
def pad(img, padding, fill=0):
    """Pad the given PIL Image on all sides with the given "pad" value.

    Args:
        img (PIL Image): Image to be padded.
        padding (int or tuple): Padding on each border. If a single int is provided this
            is used to pad all borders. If tuple of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a tuple of length 4 is provided
            this is the padding for the left, top, right and bottom borders
            respectively.
        fill: Pixel fill value. Default is 0. If a tuple of
            length 3, it is used to fill R, G, B channels respectively.

    Returns:
        PIL Image: Padded image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    if not isinstance(padding, (numbers.Number, tuple)):
        raise TypeError('Got inappropriate padding arg')
    if not isinstance(fill, (numbers.Number, str, tuple)):
        raise TypeError('Got inappropriate fill arg')

    if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:
        raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
                         "{} element tuple".format(len(padding)))

    return ImageOps.expand(img, border=padding, fill=fill)
Ejemplo n.º 13
0
def pad_to_size(input_img, size, fill_label=0):
    """Pads image to the size with fill_label if the input image is smaller"""

    input_size = np.asarray(input_img.size)
    padded_size = np.asarray(size)

    difference = padded_size - input_size

    parts_to_expand = difference > 0

    expand_difference = difference * parts_to_expand

    expand_difference_top_and_left = expand_difference // 2

    expand_difference_bottom_and_right = expand_difference - expand_difference_top_and_left
    
    # Form the PIL config vector
    pil_expand_array = np.concatenate( (expand_difference_top_and_left,
                                        expand_difference_bottom_and_right) )
    
    processed_img = input_img
    
    # Check if we actually need to expand our image.
    if pil_expand_array.any():
        
        pil_expand_tuple = tuple(pil_expand_array)
        
        processed_img = ImageOps.expand(input_img, border=pil_expand_tuple, fill=fill_label)
    
    return processed_img
Ejemplo n.º 14
0
	def update_preview(self, widget):
		if self.item:
			#get a crop for the preview
			#box = tuple((int(round(v)) for v in widget.coords(self.item)))
			box = self.getRealBox()
			pbox = self.getPreviewBox()
			if fast_preview:
				preview = self.image.crop(pbox) # region of interest
			else:
				preview = self.imageOrig.crop(box) # region of interest

			#add black borders for correct aspect ratio
			#if preview.size[0] > 512:
			preview.thumbnail(self.image.size, Image.ANTIALIAS) #downscale to preview rez
			paspect = preview.size[0]/float(preview.size[1])
			aspect = self.image.size[0]/float(self.image.size[1])
			if paspect < aspect:
				bbox = (0, 0, int(preview.size[1] * aspect), preview.size[1])
			else:
				bbox = (0, 0, preview.size[0], int(preview.size[0] / aspect))
			preview = ImageOps.expand(preview, border=(bbox[2]-preview.size[0], bbox[3]-preview.size[1]))
			#preview = ImageOps.fit(preview, size=self.image.size, method=Image.ANTIALIAS, bleed=-10.0)

			#resize to preview rez (if too small)
			self.preview = preview.resize(self.image.size, Image.ANTIALIAS)
			self.previewPhoto = ImageTk.PhotoImage(self.preview)
			self.previewLabel.configure(image=self.previewPhoto)

			print str(box[2]-box[0])+"x"+str(box[3]-box[1])+"+"+str(box[0])+"+"+str(box[1])
Ejemplo n.º 15
0
    def resize(self, img, width, height, kwargs=None):
        if kwargs is None:
            img = img.resize((width, height), Image.ANTIALIAS)
        else:
            background = kwargs['background'] if 'background' in kwargs else None
            mode = kwargs['mode'] if 'mode' in kwargs else None

            if mode == self.helper.io.image.mode.center:
                width_new, height_new = (width, height)
                width_origin, height_origin = img.size

                width_calc = width_new
                height_calc = height_origin * width_calc / width_origin

                if height_calc > height_new:
                    height_calc = height_new
                    width_calc = width_origin * height_calc / height_origin

                img = img.resize((int(width_calc), int(height_calc)), Image.ANTIALIAS)
                img = self.helper.io.image.radius(img, **kwargs)

                img = ImageOps.expand(
                    img, border=(int((width - width_calc) / 2), int((height_new - height_calc) / 2)), fill=background)

                radius = int(kwargs['radius'] or 0) if 'radius' in kwargs else None

                if radius:
                    img_empty = Image.new('RGB', (width, height_new), background)
                    img_empty.paste(img, (0, 0), img)
                    img = img_empty

                img.__dict__['__radius_processed__'] = True

        return img
Ejemplo n.º 16
0
    def create_img(self):
        random.seed()

        self.img = Image.new("RGB", (self.imgWidth, self.imgHeight), "#FFFFFF")

        draw = ImageDraw.Draw(self.img)

        for i in range(0, self.numChars):
            fontSize = random.randint(11,16)
            font = ImageFont.truetype("imgVerification/resources/DroidSans.ttf", fontSize)

            if (font > 13):
                char = random.randint(0,9)
            else:
                char = random.randint(1,9)

            char = str(char)

            fontWidth, fontHeight = font.getsize(char)

            self.numString += char

            xOffset = self.minX + random.randint(3,10)
            self.minX = xOffset + fontWidth

            maxY = self.imgHeight - self.borderThick - fontHeight
            yOffset = random.randint(self.minY, maxY)

            draw.text((xOffset, yOffset), char, "#000000", font=font)

        self.img = ImageOps.expand(self.img, border=self.borderThick,fill='#000000')
Ejemplo n.º 17
0
    def border(self, img, border, border_color):
        if img.mode == 'P':
            img = img.convert('RGBA')

        img = ImageOps.expand(img, border=(border, border), fill=border_color)

        return img
Ejemplo n.º 18
0
    def create(self, output):

        # scale image
        self._scale_source_image()

        # get texts
        l1, l1_font, w1, h1 = self._get_line(self.line1)
        l2, l2_font, w2, h2 = self._get_line(self.line2, type="description")

        # calculate final image size
        width, height = self.image.size

        width += self.margin * 2 + 5
        height += self.margin * 2 + h1 + h2 + 30 + 5

        # add image border
        self.image = ImageOps.expand(self.image, border=1, fill="white")

        # create black background
        self.final_image = Image.new("RGBA", (width, height), "black")
        self.final_image.paste(self.image, (self.margin, self.margin), self.image)

        # draw texts
        self._draw_line(l1, l1_font, self.image.size[1] + self.margin + 10)
        self._draw_line(l2, l2_font, self.image.size[1] + self.margin + 10 + h1 + 10)

        # draw footer
        self._draw_footer()

        # self generated image
        self.final_image.save(output)

        return self.final_image
Ejemplo n.º 19
0
    def process(self):
        draw = ImageDraw.Draw(self._image)
        if(self._block_size == 2):
            draw.rectangle([(0,0),(163,83)],fill=(0,0,0))
        else:
            draw.rectangle([(0,0),(83,83)],fill=(0,0,0))

        font = ImageFont.truetype('./08SeoulNamsanB.ttf',size=45)

        text = self.getLocation()

        if(self._block_size == 2):
            if(len(text) == 4):
                draw.text((38,21),text,font=font)
            else:
                draw.text((26,21),text,font=font)
        else:
            if(len(text) == 2):
                draw.text((19,21),text,font=font)
            else:
                draw.text((9,21),text,font=font)

        del draw

        self._image = ImageOps.expand(self._image,border=1,fill=(0,0,0))

        return self
Ejemplo n.º 20
0
Archivo: im.py Proyecto: Josca/im
def _border(src: str, width: int, color: str):
    image, exf = imread(src)
    image = ImageOps.expand(image, border=width, fill=color)
    path_base, ext = os.path.splitext(src)
    new_file_path = '%s_border%s' % (path_base, ext)
    print('%s --> %s' % (src, new_file_path))
    imwrite(image, new_file_path, exf)
    def _tf_pil(self, img):
        """ Letterbox an image to fit in the network """
        if self.dataset is not None:
            net_w, net_h = self.dataset.input_dim
        else:
            net_w, net_h = self.dimension
        im_w, im_h = img.size

        if im_w == net_w and im_h == net_h:
            self.scale = None
            self.pad = None
            return img

        # Rescaling
        if im_w / net_w >= im_h / net_h:
            self.scale = net_w / im_w
        else:
            self.scale = net_h / im_h
        if self.scale != 1:
            resample_mode = Image.NEAREST #Image.BILINEAR if self.scale > 1 else Image.ANTIALIAS
            img = img.resize((int(self.scale*im_w), int(self.scale*im_h)), resample_mode)
            im_w, im_h = img.size

        if im_w == net_w and im_h == net_h:
            self.pad = None
            return img

        # Padding
        img_np = np.array(img)
        channels = img_np.shape[2] if len(img_np.shape) > 2 else 1
        pad_w = (net_w - im_w) / 2
        pad_h = (net_h - im_h) / 2
        self.pad = (int(pad_w), int(pad_h), int(pad_w+.5), int(pad_h+.5))
        img = ImageOps.expand(img, border=self.pad, fill=(self.fill_color,)*channels)
        return img
Ejemplo n.º 22
0
	def convertImage(self, inputPath, outputPath):
		r = inputPath
		path = outputPath

		for root, dirs, files in os.walk(r):
			for f in files:
				if f.endswith('.gif'):
					if not os.path.exists(path): #Tworzony jest folder wyjsciowy
						os.makedirs(path)

					newroot = root.split(r)[1] #Te dwie linijki moga powodowac problemy, dlatego wazne jest, by obrazy do konwersji znajdowaly sie w podfolderach
					newroot = newroot.split('/')[1] #Podfolder

					f2 = f.split('.')[0]

					orgImg = Image.open(root + "/" + f)
					orgImg = orgImg.convert('L')
					orgSize = orgImg.size
					# niech beda tylko kwadratowe obrazy
					assert orgSize[0] == orgSize[1]
					assert self.newSize[0] == self.newSize[1]
					borderSize = int((self.newSize[0] - orgSize[0]) / 2)
					# dodanie bialej ramki
					newImg = ImageOps.expand(orgImg, borderSize, 0)
					# zapisanie wersji bez inwersji
					newImg.save(path + newroot + f2 + ".pgm")
					# dodanie wersji z inwersja
					newImg = ImageOps.invert(newImg)
					newImg.save(path + newroot + "n" + f2 + ".pgm")
Ejemplo n.º 23
0
def create_card(card_data, settings):
	margin = cm_to_pixels(settings['margin'])
	spacing = cm_to_pixels(settings['spacing'])
	
	(card_width_cm, card_height_cm) = settings['card_size']
	(card_width_px, card_height_px) = (cm_to_pixels(card_width_cm), cm_to_pixels(card_height_cm))

	border_width_px = cm_to_pixels(settings['border_width']) # around each card
	border_color = settings['border_color']

	outline_width = settings['outline_width']
	outline_color = settings['outline_color']

	size_minus_border = (card_width_px - (border_width_px * 2), card_height_px - (border_width_px * 2))

	(width_minus_border, height_minus_border) = size_minus_border
	card = Image.new("RGB", size_minus_border, "white")
	#draw_bg(card, width_minus_border, height_minus_border)
	draw_illustration(card, card_data['pic'], 100, 500, width_minus_border, outline_width, outline_color)
	draw_title(card, card_data['name'], (20, 15))
	draw_body(card, card_data['body'], 730, width_minus_border, card_data['body_width'])
	draw_footer(card, 100, width_minus_border, height_minus_border)
	draw_corner_nr(card, card_data['speed'], (width_minus_border - 65, height_minus_border - 90))
	card_with_border = ImageOps.expand(card, border=border_width_px, fill=border_color)
	return card_with_border
Ejemplo n.º 24
0
def loader(queue, settings):
    from pyglet.image import ImageData
    from PIL import Image, ImageOps
    import random, glob, time

    displayed = set()

    last_scan = time.time()
    files = glob.glob("{}/*jpg".format(settings['originals']))
    new = sorted(list(set(files) - displayed))

    while 1:
        if last_scan + 15 < time.time():
            last_scan = time.time()
            files = glob.glob("{}/*jpg".format(settings['originals']))
            new = sorted(list(set(files) - displayed))[15:]

        if new:
            filename = random.choice(new)
            displayed.add(filename)
        else:
            filename = random.choice(files)

        image = Image.open(filename)
        image = image.transpose(Image.FLIP_TOP_BOTTOM)
        image.thumbnail(settings['large_size'], Image.ANTIALIAS)
        image = ImageOps.expand(image, border=32, fill=(255, 255, 255))

        w, h = image.size
        image = image.convert()
        image = ImageData(w, h, image.mode, image.tostring())
        queue.put(image)
Ejemplo n.º 25
0
 def to_file(self, f, scale=1, border=0):
     i = self.to_transparent_image()
     if scale != 1:
         i = i.resize((i.size[0] * scale, i.size[1] * scale))
     if border:
         i = ImageOps.expand(i, border)
     i.save(f)
Ejemplo n.º 26
0
def apply_border(pixbuf,borderSize,borderColor):
    '''
    adds a border at all four edges
    '''
    width,height = pixbuf.get_width(),pixbuf.get_height() 
    y = ImageOps.expand(Image.frombytes(K.ImageConstants.RGB_SHORT_NAME,(width,height),pixbuf.get_pixels() ) ,border=borderSize,fill=borderColor)
    return I.fromImageToPixbuf(y)
Ejemplo n.º 27
0
def draw_illustration(card, illustration_name, y, vertical_space, width_minus_border, outline_width, outline_color):
	image_spacing = 20
	image_spacing_x2 = image_spacing * 2
	illustration = Image.open("illustrations/" + illustration_name + ".png")
	cropped = ImageOps.fit(illustration, (width_minus_border - (outline_width * 2) - image_spacing_x2, vertical_space - (outline_width * 2)), Image.ANTIALIAS, 0.01, (0.5, 0.5)) 
	cropped_with_border = ImageOps.expand(cropped, border=outline_width, fill=outline_color)
	card.paste(cropped_with_border, (0 + image_spacing, y))
Ejemplo n.º 28
0
    def render_line(self, text):
        """
        Draws a line onto a Cairo surface which will be converted to an pillow
        Image.

        Args:
            text (unicode): A string which will be rendered as a single line.

        Returns:
            PIL.Image of mode 'L'.

        Raises:
            KrakenCairoSurfaceException if the Cairo surface couldn't be created
            (usually caused by invalid dimensions.
        """
        temp_surface = cairo.cairo_image_surface_create(0, 0, 0)
        width, height = _draw_on_surface(temp_surface, self.font, self.language, text)
        cairo.cairo_surface_destroy(temp_surface)
        if width == 0 or height == 0:
            raise KrakenCairoSurfaceException('Surface zero pixels in at least one dimension', width, height)
        real_surface = cairo.cairo_image_surface_create(0, width, height)
        _draw_on_surface(real_surface, self.font, self.language, text)
        data = cairo.cairo_image_surface_get_data(real_surface)
        size = int(4 * width * height)
        buffer = ctypes.create_string_buffer(size)
        ctypes.memmove(buffer, data, size)
        im = Image.frombuffer("RGBA", (width, height), buffer, "raw", "BGRA", 0, 1)
        cairo.cairo_surface_destroy(real_surface)
        im = im.convert('L')
        im = ImageOps.expand(im, 5, 255)
        return im
Ejemplo n.º 29
0
def draw_text_on_logo(line1, line2, output_filename):
    '''
    >>> line1 = u'TOIDUKOGUMISPÄEVAD'
    >>> line2 = u'9.12 – 10.12'
    >>> output_filename = '../htdocs/static/generated/test.png'
    >>> draw_text_on_logo(line1, line2, output_filename)
    '''
    font = ImageFont.truetype(FONT_FILE, 10)
    logo = Image.open(LOGO_FILE)
    logo.thumbnail((120, 120))

    logo_height = logo.size[1]
    text_height = font.getsize(line1)[1]
    left_border = 3
    first_line_offset = 2
    line_gap = 3
    expand = text_height * 2 + line_gap * 2 + first_line_offset

    canvas = Image.new('RGBA', (logo.size[0], logo.size[1] + expand), 'white')
    canvas.paste(logo, (0, 0))

    draw = ImageDraw.Draw(canvas)

    first_line_offset = logo_height + first_line_offset
    draw.text((left_border, first_line_offset), line1, 'black', font=font)

    second_line_offset = first_line_offset + line_gap + text_height
    draw.text((left_border, second_line_offset), line2, 'black', font=font)

    canvas = ImageOps.expand(canvas, border=2, fill='white')

    _save_file(canvas, output_filename)
Ejemplo n.º 30
0
 def splitImage(self, img):
   # Get best subsize between 200 and 350
   w, h = img.size
   orig_size = (w, h)
   if (-w%200)*(-h%200) < (-w%350)*(-h%350):
     subsize = 200
   else:
     subsize = 350
   # Set sizes multiples of subsize
   n_w = int(numpy.ceil(w/subsize) * subsize)
   n_h = int(numpy.ceil(h/subsize) * subsize)
   new_img = Image.new('RGB', (n_w, n_h), 'black')
   new_img.paste(img, (0,0))
   # Add border size
   new_img = ImageOps.expand(new_img, border=BORDER_SIZE, fill='black')
   # Split
   # We want images of size (subsize+2*BORDER_SIZE)x(subsize+2*BORDER_SIZE)
   imgs = []
   images_on_width = int(n_w/subsize)
   images_on_height = int(n_h/subsize)
   rdata = (orig_size, subsize, images_on_width, images_on_height)
   for i in range(images_on_width):
     for j in range(images_on_height):
       left = i*subsize
       right = (i+1)*subsize + 2*BORDER_SIZE
       top = j*subsize
       bottom = (j+1)*subsize + 2*BORDER_SIZE
       simg = new_img.crop((left, top, right, bottom))
       imgs.append((simg, (i,j)))
   return imgs, rdata
Ejemplo n.º 31
0
 def __call__(self, img):
     return ImageOps.expand(img, border=self.pad, fill=0)
Ejemplo n.º 32
0
def load_data():
    img_array = []
    path1 = 'C:\\Flowers Data\\flowers'
    mypaths = []
    x = []
    class_num = []
    #    d = {}
    #    train_data = []
    #    test_data = []
    #    re_img = []
    #    app_n = []
    #    d1 = {}
    full_inp_data = []
    desired_size = 506
    dict_flower = {
        "daisy": 0,
        "dandelion": 1,
        "rose": 2,
        "sunflower": 3,
        "tulip": 4
    }
    for f in os.listdir(path1):
        dirs = os.listdir(path1)
        s = os.path.join(path1, f)
        mypaths.append(s)
        print(mypaths)
        #       print(mypaths)
        class_num = dirs.index(f)
        print(class_num)

        #       c = count()
        #       numbers = [d.setdefault(i, next(c)) for i in mypaths]
        ##       print(numbers)
        #       print(" i will execute my loop")
        #       print(c)

        print(f)
        assing_val = dict_flower[f]
        print("assignment val: " + str(assing_val))
        for fp in os.listdir(s):
            #           print("second loop")
            #           if os.path.isdir(s):
            try:
                #            print(fp, 'i got fp')
                img_data = Image.open((os.path.join(s, fp)))
            except IOError:
                pass

            old_size = img_data.size
            ratio = float(desired_size) / max(old_size)
            #           print(ratio)
            new_size = tuple([int(x * ratio) for x in old_size])
            """ resizing the image by using image module"""
            img_data = img_data.resize(new_size, Image.ANTIALIAS)

            #           new_im = Image.new("RGB", (desired_size, desired_size))
            #           new_im.paste(img_data, ((desired_size-new_size[0])//2,
            #                    (desired_size-new_size[1])//2))
            """resizing the images by using imageOps module"""
            delta_w = desired_size - new_size[0]
            delta_h = desired_size - new_size[1]
            padding = (delta_w // 2, delta_h // 2, delta_w - (delta_w // 2),
                       delta_h - (delta_h // 2))
            new_im = ImageOps.expand(img_data, padding)
            #           print((new_im))
            #           print(new_im)
            gs_data = new_im.convert(mode='L')
            #           print(np.shape(gs_data))
            data = np.asarray(gs_data)
            img_array = Image.fromarray(data)

            #           images.append(img_array)
            #           print(np.shape(images))
            #           images = np.asarray(img_array)
            #           x.append(img_array)
            inpt = np.array(img_array)
            #           print('Min: %.3f, Max: %.3f' % (inpt.min(), inpt.max()))
            pixels = asarray(inpt)
            #           print('Data Type: %s' % pixels.dtype)
            """confirm image range in between 0 to 255"""
            #           print('Min: %.3f, Max: %.3f' % (pixels.min(), pixels.max()))
            """convert intergers to float"""
            inpt = pixels.astype('float32')
            """ normalize to the range 0 to 1"""
            inpt /= 255.0
            """ confirm the normalization"""
            #           print('Min: %.3f, Max: %.3f' % (inpt.min(), inpt.max()))
            #           print(inpt[100])
            #           break
            #           print(np.shape())
            #           print(np.shape(inpt))
            inpt = np.array([np.reshape(inpt, np.prod(inpt.shape))])
            #           print("inp: "+str(np.shape(inpt)))
            outp = vectorized_result(assing_val)
            #           print("out: "+str(np.shape(outp)))
            x = [inpt, outp]
            #           print(x)
            #           print(np.shape(x))

            full_inp_data.append(x)


#
    print("final training data")
    #    full_inp_data = np.array(full_inp_data)
    print(np.shape(full_inp_data))
    training_data, test_data = full_inp_data[:3000], full_inp_data[3000:]
    print(np.shape(training_data))
    print(np.shape(test_data))
    #    print(np.shape(train_data))
    return training_data, test_data

    #def load_data_wrapper():
    #    tr_d, te_d= load_data()
    ##    print((tr_d[0]))
    ##    s = len(tr_d)
    ##    print(len(tr_d))S
    #    training_data = [tr_d]
    #    test_data = [te_d]

    return training_data, test_data
Ejemplo n.º 33
0
    xray = Image.open(dir_xray_png + '/' + file)
    heatmap = Image.open(dir_heatmap_png + '/' + file)
    '''Get node_1 from landmark fcsv'''
    landmarks = get_landmarks(file_name, dir_fcsv)

    x = -1 * int(float(landmarks['Node_1'][0]))
    y = -1 * int(float(landmarks['Node_1'][1]))

    cols, rows = xray.size

    if x - 512 < 0 or x + 512 > cols or y - 762 < 0 or y + 256 > rows:
        '''Add border to image'''
        padding = 768  # give size for margin

        xray_extended = ImageOps.expand(xray, border=padding,
                                        fill=38)  # 38 xray black
        heatmap_extended = ImageOps.expand(
            heatmap, border=padding, fill='#0C0786')  # 0C0786 = plasma blue

        x += padding
        y += padding

        xray_croped = xray_extended.crop((x - 512, y - 768, x + 512, y + 256))
        heatmap_croped = heatmap_extended.crop(
            (x - 512, y - 768, x + 512, y + 256))

    else:

        xray_croped = xray.crop((x - 512, y - 768, x + 512, y + 256))
        heatmap_croped = heatmap.crop((x - 512, y - 768, x + 512, y + 256))
Ejemplo n.º 34
0
def CreateLangLabelImg_fx(lang_rank, lang_name, vote_percent, vote_count,
                          q_name, tmp_imageObj_dict):
    '''finding Color and finding Logo image'''
    # addition to lang_rank
    lang_rank += 1
    # finding lang color using Ref table
    lang_color = colors_ref.at[lang_name, 'color']

    # reading Logo
    os.chdir('.\LanguageInfo')
    if lang_name == 'C++':
        lang_logo = Image.open('Cpp.png')
    elif lang_name == 'C#':
        lang_logo = Image.open('Csharp.png')
    else:
        lang_logo = Image.open(lang_name + '.png')

    os.chdir('..')
    '''Logo resizing'''
    # resizing LangLogo
    # if WIDE, then scale the height according to width
    if lang_logo.size[0] > lang_logo.size[1]:
        # since WIDE, we find the nu_height
        nuheight_float = (160 / lang_logo.size[0]) * lang_logo.size[1]
        nuheight_int = round(nuheight_float / 2.0) * 2
        # resiziing LangLogo
        lang_logo = lang_logo.resize((160, nuheight_int))
    # if TALL, then scale the width according to the height
    elif lang_logo.size[1] > lang_logo.size[0]:
        # since TALL, we find NuWidth
        nuwidth_float = (160 / lang_logo.size[1]) * lang_logo.size[0]
        nuwidth_int = round(nuwidth_float / 2.0) * 2
        # resizing LangLogo
        lang_logo = lang_logo.resize((nuwidth_int, 160))
    # if neither tall nor wide, then EVEN, and just resize to 280,280
    else:
        lang_logo = lang_logo.resize((160, 160))
    '''Title sizing'''
    # defining Lang Title Str for the #2 current tie
    if q_name == 'Q2Current' and lang_name in ['Java', 'JavaScript']:
        lang_title_str = '2 (tie): ' + lang_name
    # defining the normal Lang Title Str
    else:
        lang_title_str = str(lang_rank) + ': ' + lang_name

    # determing which font number is closest to 80 height for the Title
    for fsize in np.arange(100, 0, -1):
        # creating langFont
        lang_title_fnt = ImageFont.truetype('ARLRDBD.TTF', fsize)
        # testing if at or below 80, breaking if so
        if lang_title_fnt.getsize(lang_title_str)[1] <= 110:
            break

    # finding the size of the title
    lang_title_size = lang_title_fnt.getsize(lang_title_str)
    '''Vote Perc sizing'''
    # defining Lang VotePerc Str
    lang_voteperc_str = '{:.1%}'.format(vote_percent)

    # determing which font number is closest to 50 height for the Percent
    for fsize in np.arange(100, 0, -1):
        # creating langFont
        lang_voteperc_fnt = ImageFont.truetype('ARLRDBD.TTF', fsize)
        # testing if below 50, breaking if so
        if lang_voteperc_fnt.getsize(lang_voteperc_str)[1] <= 70:
            break

    # defining Lang VotePerc Size
    lang_voteperc_size = lang_voteperc_fnt.getsize(lang_voteperc_str)
    '''Vote Count sizing'''
    # defining Lang VoteCount Str
    lang_votecount_str = '(' + str(int(vote_count)) + ' votes)'

    # determing which font number is closest to 30 height for the Count
    for fsize in np.arange(100, 0, -1):
        # creating langFont
        lang_votecount_fnt = ImageFont.truetype('ARLRDBD.TTF', fsize)
        # testing if below 30, breaking if so
        if lang_votecount_fnt.getsize(lang_votecount_str)[1] <= 60:
            break

    # defining Lang VoteCount Size
    lang_votecount_size = lang_votecount_fnt.getsize(lang_votecount_str)
    '''White Background creation'''
    # determining the width
    # first, find the longer length between the Title, Perc, and Count
    farthest_x = max([
        lang_title_size[0], lang_voteperc_size[0] + lang_votecount_size[0] + 35
    ])

    # creating Background Size, picking between Farthest Title or Count for the X width
    background_size = (farthest_x + 215, 190)

    # creating white background
    background_img = Image.new('RGBA', background_size, 'white')
    # adding border
    if 'JavaScript' in lang_name or 'SQL' in lang_name:
        background_img = ImageOps.expand(background_img,
                                         border=3,
                                         fill=lang_color)
        background_img = ImageOps.expand(background_img,
                                         border=2,
                                         fill='#3f3f3f')
    else:
        background_img = ImageOps.expand(background_img,
                                         border=5,
                                         fill=lang_color)
    '''Pasting Logo'''
    # pasting LangLogo onto background, creating full image
    full_img = background_img.copy()
    # calculating the position of the logo
    logo_position = (int(20 + (160 - lang_logo.size[0]) / 2),
                     int(20 + (160 - lang_logo.size[1]) / 2))
    # try as mask
    try:
        full_img.paste(lang_logo, logo_position, mask=lang_logo)
    # if logo is no mask, paste as normal
    except ValueError:
        full_img.paste(lang_logo, logo_position)
    '''Drawing on Title, Vote Perc, and Vote Count'''
    # determining Title position
    lang_title_position = (200, 5)
    # creating draw object
    full_draw = ImageDraw.Draw(full_img)

    # drawing black outlines for JavaScript and SQL
    if 'JavaScript' in lang_name or 'SQL' in lang_name:
        for tmp_text_pos, tmp_text_str, tmp_fnt in zip(
            [(200, 5), (220, 105), (240 + lang_voteperc_size[0], 125)],
            [lang_title_str, lang_voteperc_str, lang_votecount_str],
            [lang_title_fnt, lang_voteperc_fnt, lang_votecount_fnt]):
            for position_tup in (
                    list(
                        it.product(
                            np.arange(tmp_text_pos[0] - 3,
                                      tmp_text_pos[0] + 4),
                            [tmp_text_pos[1] + 1])) +  #bottom border
                    list(
                        it.product(
                            np.arange(tmp_text_pos[0] - 1,
                                      tmp_text_pos[0] + 2),
                            [tmp_text_pos[1] + 2])) +  #bottom border extra
                    list(
                        it.product(
                            np.arange(tmp_text_pos[0] - 3,
                                      tmp_text_pos[0] + 4),
                            [tmp_text_pos[1] - 1])) +  #top border
                    list(
                        it.product(
                            np.arange(tmp_text_pos[0] - 1,
                                      tmp_text_pos[0] + 2),
                            [tmp_text_pos[1] - 2])) +  #top border extra
                    list(
                        it.product(
                            [tmp_text_pos[0] - 1],
                            np.arange(tmp_text_pos[1] - 3,
                                      tmp_text_pos[1] + 4))) +  #left border
                    list(
                        it.product([tmp_text_pos[0] - 2],
                                   np.arange(tmp_text_pos[1] - 1,
                                             tmp_text_pos[1] + 2)))
                    +  #left border extra
                    list(
                        it.product(
                            [tmp_text_pos[0] + 1],
                            np.arange(tmp_text_pos[1] - 3,
                                      tmp_text_pos[1] + 4))) +  #right border
                    list(
                        it.product(
                            [tmp_text_pos[0] + 2],
                            np.arange(tmp_text_pos[1] - 1, tmp_text_pos[1] +
                                      2)))):  #right border extra
                # drawing black shift
                full_draw.text(position_tup,
                               tmp_text_str,
                               fill='#3f3f3f',
                               font=tmp_fnt)
    # drawing colored center for title
    full_draw.text(lang_title_position,
                   lang_title_str,
                   fill=lang_color,
                   font=lang_title_fnt)

    # drawing Lang VotePerc
    full_draw.text((220, 5 + 100),
                   lang_voteperc_str,
                   fill=lang_color,
                   font=lang_voteperc_fnt)

    # drawing Lang VoteCount
    full_draw.text((240 + lang_voteperc_size[0], 5 + 120),
                   lang_votecount_str,
                   fill=lang_color,
                   font=lang_votecount_fnt)

    # adding the image obj to the Dict
    tmp_imageObj_dict[q_name + '_' + lang_name] = full_img

    # returning the Image Obj dict
    return tmp_imageObj_dict
Ejemplo n.º 35
0
def resize(target_size,
           img_filepath,
           save_dir,
           quality=95,
           keep_aspect_ratio=True):
    try:
        img = Image.open(img_filepath)
    except Exception as ex:
        # print(ex)
        return

    img_basename = os.path.basename(img_filepath)
    print(img_basename)

    img_name, img_ext = os.path.splitext(img_basename)
    resized_img_name = '{}_resize_{}x{}'.format(img_name, size[0], size[1])
    resized_img_basename = resized_img_name + img_ext
    resized_img_filepath = os.path.join(save_dir, resized_img_basename)

    original_size = img.size

    # resize and keep aspect ratio
    ratio = min(target_size[0] / original_size[0],
                target_size[1] / original_size[1])
    new_size = tuple([int(s * ratio) for s in original_size])
    img = img.resize(new_size, Image.BICUBIC)

    # padding to desired size and save imge
    delta_w = target_size[0] - new_size[0]
    delta_h = target_size[1] - new_size[1]
    padding_left = delta_w // 2
    padding_top = delta_h // 2
    padding_right = delta_w - padding_left
    padding_bottom = delta_h - padding_top
    padding = (padding_left, padding_top, padding_right, padding_bottom)
    img = ImageOps.expand(img, padding)
    img.save(resized_img_filepath, quality=quality)

    # modify annotation and save in json format (change shape to bounding box in rectangle)
    jsn_filepath = img_filepath.replace(img_ext, '.json')
    with open(jsn_filepath, 'r') as fp:
        jsn = json.load(fp)

    jsn['imageWidth'] = img.size[0]
    jsn['imageHeight'] = img.size[1]
    jsn['imagePath'] = resized_img_basename

    bndboxes = list()
    labels = list()
    for shape in jsn['shapes']:
        labels.append(shape['label'])
        points = shape['points']
        for idx, point in enumerate(points):
            x, y = point
            x = int(x * ratio + padding_left)
            y = int(y * ratio + padding_top)
            points[idx] = [x, y]
        '''
        # change all shapes to bounding box in rectangle
        # for example, [xmin, ymin], [xmax, ymax]
        xmin, ymin, xmax, ymax = bndbox(shape['points'])
        shape['points'] = [
            [xmin, ymin],
            [xmax, ymax]
        ]
        shape['shape_type'] = 'rectangle'
        '''

    resized_jsn_basename = resized_img_name + '.json'
    resized_jsn_filepath = os.path.join(save_dir, resized_jsn_basename)
    with open(resized_jsn_filepath, 'w') as fp:
        json.dump(jsn, fp, indent=4)

    ## generate xml in pascal voc annotation and save
    ## collect labels and bounding boxes
    #labels, bndboxes = list(), list()
    #for shape in jsn['shapes']:
    #    labels.append(shape['label'])
    #    bndboxes.append(bndbox(shape['points']))
    ## generate xml file
    #resized_xml_basename = resized_img_name + '.xml'
    #resized_xml_filepath = os.path.join(save_dir, resized_xml_basename)
    #with open(resized_xml_filepath, 'w') as fp:
    #    fp.write(etree.tostring(xmlgen(resized_img_basename, img.size, labels, bndboxes), encoding='utf-8', pretty_print=True).decode('utf-8'))

    return labels
Ejemplo n.º 36
0
def pad(img, padding, fill=0, padding_mode="constant"):
    r"""Pad the given PIL.Image on all sides with the given "pad" value.

    Args:
        img (PIL Image): Image to be padded.
        padding (int or tuple or list): Padding on each border. If a single int is provided this
            is used to pad all borders. If a tuple or list of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a tuple or list of length 4 is provided
            this is the padding for the left, top, right and bottom borders respectively. For compatibility reasons
            with ``functional_tensor.pad``, if a tuple or list of length 1 is provided, it is interpreted as
            a single int.
        fill (int or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
            length 3, it is used to fill R, G, B channels respectively.
            This value is only used when the padding_mode is constant.
        padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.

            - constant: pads with a constant value, this value is specified with fill

            - edge: pads with the last value on the edge of the image

            - reflect: pads with reflection of image (without repeating the last value on the edge)

                       padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
                       will result in [3, 2, 1, 2, 3, 4, 3, 2]

            - symmetric: pads with reflection of image (repeating the last value on the edge)

                         padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
                         will result in [2, 1, 1, 2, 3, 4, 4, 3]

    Returns:
        PIL Image: Padded image.
    """

    if not _is_pil_image(img):
        raise TypeError("img should be PIL Image. Got {}".format(type(img)))

    if not isinstance(padding, (numbers.Number, tuple, list)):
        raise TypeError("Got inappropriate padding arg")
    if not isinstance(fill, (numbers.Number, str, tuple)):
        raise TypeError("Got inappropriate fill arg")
    if not isinstance(padding_mode, str):
        raise TypeError("Got inappropriate padding_mode arg")

    if isinstance(padding, list):
        padding = tuple(padding)

    if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]:
        raise ValueError("Padding must be an int or a 1, 2, or 4 element tuple, not a " +
                         "{} element tuple".format(len(padding)))

    if isinstance(padding, tuple) and len(padding) == 1:
        # Compatibility with `functional_tensor.pad`
        padding = padding[0]

    if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
        raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")

    if padding_mode == "constant":
        if isinstance(fill, numbers.Number):
            fill = (fill,) * len(img.getbands())
        if len(fill) != len(img.getbands()):
            raise ValueError("fill should have the same number of elements "
                             "as the number of channels in the image "
                             "({}), got {} instead".format(len(img.getbands()), len(fill)))
        if img.mode == "P":
            palette = img.getpalette()
            image = ImageOps.expand(img, border=padding, fill=fill)
            image.putpalette(palette)
            return image

        return ImageOps.expand(img, border=padding, fill=fill)
    else:
        if isinstance(padding, int):
            pad_left = pad_right = pad_top = pad_bottom = padding
        if isinstance(padding, tuple) and len(padding) == 2:
            pad_left = pad_right = padding[0]
            pad_top = pad_bottom = padding[1]
        if isinstance(padding, tuple) and len(padding) == 4:
            pad_left = padding[0]
            pad_top = padding[1]
            pad_right = padding[2]
            pad_bottom = padding[3]

        if img.mode == 'P':
            palette = img.getpalette()
            img = np.asarray(img)
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)
            img = Image.fromarray(img)
            img.putpalette(palette)
            return img

        img = np.asarray(img)
        # RGB image
        if len(img.shape) == 3:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)
        # Grayscale image
        if len(img.shape) == 2:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)

        return Image.fromarray(img)
Ejemplo n.º 37
0
    output = image.crop(area)
    return output


image_name = "egg"
image = Image.open(f"{image_name}.png")
width, height = image.size
size = 128

x_loss = ceil_to_number(width, size) - width
y_loss = ceil_to_number(height, size) - height
loss = x_loss
if y_loss > x_loss:
    loss = y_loss

image = ImageOps.expand(image, border=loss, fill=(255, 255, 255))

x_index = 0
y_index = 0
for x in range(0, ceil_to_number(width, size), size):
    y_index = 0
    for y in range(0, ceil_to_number(height, size), size):
        slice(
            image, (x + loss, y + loss),
            (size, size)).save(f"./tiles/{image_name}_{x_index}_{y_index}.png")
        y_index = y_index + 1
    x_index = x_index + 1

print(int(ceil_to_number(width, size) / size - 1),
      int(ceil_to_number(height, size) / size - 1))
Ejemplo n.º 38
0
def images_to_tfrecords(image_names,
                        output_filename,
                        num_images_per_tfrecord,
                        image_class=None,
                        target_size=299):
    """ This function converts images listed in the image_names to tfrecords files

    :param image_names: a list of strings like ['xxx.jpg', 'xxx.jpg', 'xxx.jpg', ...]
    :param output_filename: 'train'
    :param num_images_per_tfrecord: integer
    :param image_class: class label for each image, a list like [1, 34, 228, ...]
    :param target_size: the size of images after padding and resizing
    :return:
    """

    num_images = len(image_names)
    # iteratively handle each image
    writer = None
    start_time = time.time()
    for image_index in range(num_images):
        # retrieve a single image
        im_loc = os.path.join(FLAGS.DEFAULT_DOWNLOAD, image_names[image_index])
        im_cla = image_class[image_index] if isinstance(image_class,
                                                        list) else None
        im = Image.open(im_loc)

        # resize the image
        old_size = im.size
        ratio = float(target_size) / max(old_size)
        if not ratio == 1.0:
            new_size = tuple([int(x * ratio) for x in old_size])
            im = im.resize(new_size, Image.LANCZOS)

        # zero-pad the images
        new_size = im.size
        delta_w = target_size - new_size[0]
        delta_h = target_size - new_size[1]
        if delta_w < 0 or delta_h < 0:
            raise AttributeError(
                'The target size is smaller than the image size {}.'.format(
                    new_size))
        elif delta_w > 0 or delta_h > 0:
            padding = (delta_w // 2, delta_h // 2, delta_w - (delta_w // 2),
                       delta_h - (delta_h // 2))
            im = ImageOps.expand(im, padding)

        # if image not RGB format, convert to RGB
        # This is done in case the image is greyscale
        if im.mode != 'RGB':
            im = im.convert('RGB')

        # convert the full image data to the jpeg compressed string to reduce tfrecord size
        with BytesIO() as fp:
            im.save(fp, format="JPEG")
            im_string = fp.getvalue()

        # save to tfrecords
        if image_index % num_images_per_tfrecord == 0:
            file_out = "{}_{:03d}.tfrecords".format(
                output_filename, image_index // num_images_per_tfrecord)
            # if file_out exist, raise an error, as that means this job has been done before
            if os.path.isfile(file_out):
                print('Job abortion: {} already exists.'.format(file_out))
                break
            writer = tf.python_io.TFRecordWriter(file_out)
        if image_class is None:
            # for test set, the labels are unknown and not provided
            instance = tf.train.Example(features=tf.train.Features(
                feature={'x': _bytes_feature(im_string)}))
        else:
            instance = tf.train.Example(features=tf.train.Features(
                feature={
                    'x': _bytes_feature(im_string),
                    'y': _int64_feature(im_cla)
                }))
        writer.write(instance.SerializeToString())
        if image_index % 2000 == 0:
            sys.stdout.write('\r {}/{} instances finished.'.format(
                image_index + 1, num_images))
        if image_index % num_images_per_tfrecord == (num_images_per_tfrecord -
                                                     1):
            writer.close()

    writer.close()
    duration = time.time() - start_time
    sys.stdout.write('\n All {} instances finished in {:.1f} seconds'.format(
        num_images, duration))
Ejemplo n.º 39
0
def data_achieve(hostid, host_user, database, host_passwd, pdf_set):

    '''
    '''

    const_width = 64
    const_height = 64
    redis_pool=redis.ConnectionPool(host='127.0.0.1', port=6379,db=0, password='******', encoding='utf-8')
    red = redis.Redis(connection_pool=redis_pool)
    elem_list = []
    polygon_elem = {}
    with open("./data/elem_list.txt", "r") as f:
        for line in f:
            line = line.strip('\n')
            elem_info = json.loads(line)
            elem_id = elem_info["id"]
            elem_list.append(elem_id)
    connection = pymysql.connect(host=hostid, user=host_user, password=host_passwd, charset="utf8", use_unicode=True)
    db_cursor = connection.cursor()
    connection.select_db(database)

    for elem_id in elem_list:
        sql_polygon_id = 'select polygon_id from ocr_polygonelem where elem_id = (%s)'
        db_cursor.execute(sql_polygon_id, elem_id)
        polygon_id_set = db_cursor.fetchall()
        for polygon_id in polygon_id_set:
            polygonid = polygon_id[0]
            if polygonid in polygon_elem:
                polygon_elem[polygonid].append(elem_id)
            else:
                polygon_elem[polygonid] = [elem_id]

    data_label = []
    elem_set = set()
    widgets = ['data_achieving: ', Percentage(), ' ', Bar('#'), ' ', Timer(), ' ']
    bar_achieve_label = progressbar.ProgressBar(widgets=widgets, maxval=len(polygon_elem))
    bar_achieve_label.start()
    process_step = 0
    for key in polygon_elem:
        # 获取polygon信息
        sql_polygon = 'select labeling_content, pdfImage_id, polygon from ocr_ocrlabelingpolygon where id = %s'
        db_cursor.execute(sql_polygon, key)
        labeling_content, pdfImage_id, polygon = db_cursor.fetchone()

        sql_pdf = 'select ocrPDF_id from ocr_pdfimage where id = %s'
        db_cursor.execute(sql_pdf, pdfImage_id)
        pdf = db_cursor.fetchone()[0]
        in_PDF_set = pdf in pdf_set
        if in_PDF_set == False:
            continue

        if labeling_content == 0:
            process_step = process_step+1
            continue

        points = json.loads(str(polygon, encoding = "utf8"))
        degree_to_rotate = cal_rotate_angle(points[0]['x'], points[0]['y'], points[3]['x'], points[3]['y'])
        degree_to_rotate = round(degree_to_rotate, 1)
        key_image_rotated = "%s_%s" % (pdfImage_id, degree_to_rotate)
        image_rotated = red.get(key_image_rotated)
        
        if image_rotated is None:
            # 获取原始图片image
            sql_pdfimage = 'select width, height, data_byte from ocr_pdfimage where id = %s'
            db_cursor.execute(sql_pdfimage, pdfImage_id)
            width, height, data_byte = db_cursor.fetchone()
            data_stream=io.BytesIO(data_byte)
            pil_image = Image.open(data_stream)
            gray = pil_image.convert('L')
            if abs(degree_to_rotate)<0.01:
                image_rotated = gray
            else:
                image_rotated = gray.rotate(degree_to_rotate)
            image_rotated = pickle.dumps(image_rotated)
            red.set(key_image_rotated, image_rotated)
        image_rotated = pickle.loads(image_rotated)
        pdf_width, pdf_height = image_rotated.size
        rotate_points(points, degree_to_rotate, pdf_width, pdf_height)
        bounding_points(points)
        rect_info = get_rect_info(points[0], points[2])
        rect = (rect_info['x'], rect_info['y'], rect_info['x_'], rect_info['y_'])
        image_corp = image_rotated.crop(rect)
        width ,height = image_corp.size
        ratio_w =width*1.0/const_width
        ratio_h =height*1.0/const_height
        ratio = max(ratio_w, ratio_h)
        tar_width = min(int(width/ratio),const_width)
        tar_height = min(int(height/ratio),const_height)
        image_resized = image_corp.resize((tar_width, tar_height), Image.ANTIALIAS)
        tar_width, tar_height = image_resized.size
        w_extend = const_width - tar_width
        h_extend = const_height - tar_height
        w_l_extend = w_extend // 2
        w_r_extend = w_extend -w_l_extend
        h_t_extend = h_extend // 2
        h_b_extend = h_extend -h_t_extend


        image_padding = ImageOps.expand(image_resized, border=(w_l_extend, h_t_extend, w_r_extend, h_b_extend) ,fill=0)
        image_file = "./data/image/%s.png" % key
        image_padding.save(image_file)
        label= {'file': image_file, 'label': polygon_elem[key]}
        data_label.append(label)
        for elem in polygon_elem[key]:
            elem_set.add(elem)
        process_step = process_step+1
        bar_achieve_label.update(process_step)
    bar_achieve_label.finish()
    elem_list = list(elem_set)
    elem_list.sort()
    
    with open('./data/elem_list.json', 'w') as f:
        json.dump(elem_list, f)

    with open('./data/label.json', 'w') as f:
        json.dump(data_label, f)

            
    db_cursor.close()
    connection.close()
Ejemplo n.º 40
0
 def __call__(self, input):
     input['img'] = ImageOps.expand(input['img'], border=self.padding, fill=self.fill)
     return input
Ejemplo n.º 41
0
    return images, labels


#read train data(images and labels)
trainImages, trainLabels = readTrafficSigns('GTSRB-2/Final_Training/Images')

#Image padding
for i, elem in enumerate(trainImages):
    h, w, d = elem.shape
    new_size = max(h, w)
    img = Image.fromarray(elem, 'RGB')
    delta_h = new_size - h
    delta_w = new_size - w
    padding = (delta_w // 2, delta_h // 2, delta_w - (delta_w // 2),
               delta_h - (delta_h // 2))
    new_im = ImageOps.expand(img, padding)
    trainImages[i] = numpy.array(new_im)

#Image resize
for i, elem in enumerate(trainImages):
    size = image_size
    img = Image.fromarray(elem, 'RGB')
    trainImages[i] = numpy.array(ImageOps.fit(img, size, Image.ANTIALIAS))

# Split a dataset into a train and test set
train_images = []
test_images = trainImages
train_labels = []
test_labels = trainLabels

train_size = 0.8 * len(trainImages)
Ejemplo n.º 42
0
i = 0
for i in range(len(a)):
    line()
    print('image %d size' % i)
    im = Image.open(a[i])
    print(im.size)
    inimg = im.size
    if inimg[0] < inimg[1]:
        greater = inimg[1]
    else:
        greater = inimg[0]

    print(greater)
    img = Image.open(a[i])
    img_with_border = ImageOps.expand(img,
                                      border=int(9 * greater / 40),
                                      fill='white')
    os.chdir(os.path.dirname(os.path.realpath(__file__)))
    os.chdir("result")
    print("dir changed to result")
    img_with_border.save('%d border.jpg' % i)
    print('%d border.jpg' % i + ' rough save done')

    line()
    print('%d border.jpg' % i + ' cropping')
    imc = Image.open('%d border.jpg' % i)
    print(imc.size)
    inimg = imc.size

    if inimg[0] < inimg[1]:
        print('This is vertical img')
Ejemplo n.º 43
0
        else:
            print('%i NO possible candidate grid (%i:%i,%i:%i)' %
                  (i, startgridx, startgridy, endgridx, endgridy))
    else:
        matgrid[gridx[i], gridy[i]] = True
        gridcoord[i, 0] = gridx[i]
        gridcoord[i, 1] = gridy[i]
        valid[i] = True
        #print('%i free space'%i)

# convert the grid coordinate to real img_res coordinates
realcoordx = gridcoord[:, 0] * thumnail_res[0]
realcoordy = gridcoord[:, 1] * thumnail_res[1]

# create image buffer
im = Image.new('RGB', img_res, 'white')

# read the image provided in xy_id
xy_path = [os.path.join(img_dir, x) for x in xy_id]

# pasting image accordingly to buffer
for i in range(n):
    im2 = Image.open(xy_path[i])
    im2 = im2.resize(read_thumb_size)
    im2 = ImageOps.expand(im2, border=border_size, fill=0)
    im.paste(im2, (realcoordx[i], realcoordy[i]))

# save the results
im.save('%s_scatter.jpg' % current_time())
print 'done! Time elapsed: {} seconds'.format(time.time() - time_start)
Ejemplo n.º 44
0
def test(file_list, model_path):

    net = CrowdCounter()
    net.load_state_dict(torch.load(model_path))
    # net = tr_net.CNN()
    # net.load_state_dict(torch.load(model_path))
    net.cuda()
    net.eval()

    maes = []
    mses = []

    for filename in file_list:
        print filename
        imgname = dataRoot + '/img/' + filename
        filename_no_ext = filename.split('.')[0]

        denname = dataRoot + '/den/' + filename_no_ext + '.csv'


        den = pd.read_csv(denname, sep=',',header=None).values
        den = den.astype(np.float32, copy=False)

        img = Image.open(imgname)

        if img.mode == 'L':
            img = img.convert('RGB')

        # prepare
        wd_1, ht_1 = img.size
        # pdb.set_trace()

        if wd_1 < cfg.DATA.STD_SIZE[1]:
            dif = cfg.DATA.STD_SIZE[1] - wd_1
            img = ImageOps.expand(img, border=(0,0,dif,0), fill=0)
            pad = np.zeros([ht_1,dif])
            den = np.array(den)
            den = np.hstack((den,pad))
            
        if ht_1 < cfg.DATA.STD_SIZE[0]:
            dif = cfg.DATA.STD_SIZE[0] - ht_1
            img = ImageOps.expand(img, border=(0,0,0,dif), fill=0)
            pad = np.zeros([dif,wd_1])
            den = np.array(den)
            den = np.vstack((den,pad))

        img = img_transform(img)

        gt = np.sum(den)

        img = Variable(img[None,:,:,:],volatile=True).cuda()

        #forward
        pred_map = net.test_forward(img)

        pred_map = pred_map.cpu().data.numpy()[0,0,:,:]
        pred = np.sum(pred_map)/100.0

        maes.append(abs(pred-gt))
        mses.append((pred-gt)*(pred-gt))

        
        # vis
        pred_map = pred_map/np.max(pred_map+1e-20)
        pred_map = pred_map[0:ht_1,0:wd_1]
        
        
        den = den/np.max(den+1e-20)
        den = den[0:ht_1,0:wd_1]

        den_frame = plt.gca()
        plt.imshow(den, 'jet')
        den_frame.axes.get_yaxis().set_visible(False)
        den_frame.axes.get_xaxis().set_visible(False)
        den_frame.spines['top'].set_visible(False) 
        den_frame.spines['bottom'].set_visible(False) 
        den_frame.spines['left'].set_visible(False) 
        den_frame.spines['right'].set_visible(False) 
        plt.savefig(exp_name+'/'+filename_no_ext+'_gt_'+str(int(gt))+'.png',\
            bbox_inches='tight',pad_inches=0,dpi=150)

        plt.close()
        
        # sio.savemat(exp_name+'/'+filename_no_ext+'_gt_'+str(int(gt))+'.mat',{'data':den})

        pred_frame = plt.gca()
        plt.imshow(pred_map, 'jet')
        pred_frame.axes.get_yaxis().set_visible(False)
        pred_frame.axes.get_xaxis().set_visible(False)
        pred_frame.spines['top'].set_visible(False) 
        pred_frame.spines['bottom'].set_visible(False) 
        pred_frame.spines['left'].set_visible(False) 
        pred_frame.spines['right'].set_visible(False) 
        plt.savefig(exp_name+'/'+filename_no_ext+'_pred_'+str(float(pred))+'.png',\
            bbox_inches='tight',pad_inches=0,dpi=150)

        plt.close()

        # sio.savemat(exp_name+'/'+filename_no_ext+'_pred_'+str(float(pred))+'.mat',{'data':pred_map})

        diff = den-pred_map

        diff_frame = plt.gca()
        plt.imshow(diff, 'jet')
        plt.colorbar()
        diff_frame.axes.get_yaxis().set_visible(False)
        diff_frame.axes.get_xaxis().set_visible(False)
        diff_frame.spines['top'].set_visible(False) 
        diff_frame.spines['bottom'].set_visible(False) 
        diff_frame.spines['left'].set_visible(False) 
        diff_frame.spines['right'].set_visible(False) 
        plt.savefig(exp_name+'/'+filename_no_ext+'_diff.png',\
            bbox_inches='tight',pad_inches=0,dpi=150)

        plt.close()

        # sio.savemat(exp_name+'/'+filename_no_ext+'_diff.mat',{'data':diff})
        
        print '[file %s]: [pred %.2f], [gt %.2f]' % (filename, pred, gt)
    print np.average(np.array(maes))
    print np.sqrt(np.average(np.array(mses)))
Ejemplo n.º 45
0
def pad(img, padding, fill=0, padding_mode='constant'):
    r"""Pad the given PIL Image on all sides with specified padding mode and fill value.

    Args:
        img (PIL Image): Image to be padded.
        padding (int or tuple): Padding on each border. If a single int is provided this
            is used to pad all borders. If tuple of length 2 is provided this is the padding
            on left/right and top/bottom respectively. If a tuple of length 4 is provided
            this is the padding for the left, top, right and bottom borders
            respectively.
        fill: Pixel fill value for constant fill. Default is 0. If a tuple of
            length 3, it is used to fill R, G, B channels respectively.
            This value is only used when the padding_mode is constant
        padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.

            - constant: pads with a constant value, this value is specified with fill

            - edge: pads with the last value on the edge of the image

            - reflect: pads with reflection of image (without repeating the last value on the edge)

                       padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
                       will result in [3, 2, 1, 2, 3, 4, 3, 2]

            - symmetric: pads with reflection of image (repeating the last value on the edge)

                         padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
                         will result in [2, 1, 1, 2, 3, 4, 4, 3]

    Returns:
        PIL Image: Padded image.
    """
    if not _is_pil_image(img):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))

    if not isinstance(padding, (numbers.Number, tuple)):
        raise TypeError('Got inappropriate padding arg')
    if not isinstance(fill, (numbers.Number, str, tuple)):
        raise TypeError('Got inappropriate fill arg')
    if not isinstance(padding_mode, str):
        raise TypeError('Got inappropriate padding_mode arg')

    if isinstance(padding, Sequence) and len(padding) not in [2, 4]:
        raise ValueError(
            "Padding must be an int or a 2, or 4 element tuple, not a " +
            "{} element tuple".format(len(padding)))

    assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
        'Padding mode should be either constant, edge, reflect or symmetric'

    if padding_mode == 'constant':
        return ImageOps.expand(img, border=padding, fill=fill)
    else:
        if isinstance(padding, int):
            pad_left = pad_right = pad_top = pad_bottom = padding
        if isinstance(padding, Sequence) and len(padding) == 2:
            pad_left = pad_right = padding[0]
            pad_top = pad_bottom = padding[1]
        if isinstance(padding, Sequence) and len(padding) == 4:
            pad_left = padding[0]
            pad_top = padding[1]
            pad_right = padding[2]
            pad_bottom = padding[3]

        img = np.asarray(img)
        # RGB image
        if len(img.shape) == 3:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right),
                               (0, 0)), padding_mode)
        # Grayscale image
        if len(img.shape) == 2:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)),
                         padding_mode)

        return Image.fromarray(img)
Ejemplo n.º 46
0
from PIL import Image, ImageOps

img = Image.open('beijo_menor.jpg')

new_img = ImageOps.expand(img, border=30, fill='white')

new_img.show()
Ejemplo n.º 47
0
def apply_effect(layer, backdrop, base_image):
    """Apply effect to the image.

    ..note: Correct effect order is the following. All the effects are first
        applied to the original image then blended together.

        * dropshadow
        * outerglow
        * (original)
        * patternoverlay
        * gradientoverlay
        * coloroverlay
        * innershadow
        * innerglow
        * bevelemboss
        * satin
        * stroke
    """
    from PIL import ImageChops
    for effect in layer.effects:
        if effect.__class__.__name__ == 'PatternOverlay':
            image = draw_pattern_fill(base_image.size, layer._psd,
                                      effect.value)
            if base_image.mode.endswith('A'):
                alpha = base_image.getchannel('A')
                if image.mode.endswith('A'):
                    alpha = ImageChops.darker(alpha, image.getchannel('A'))
                image.putalpha(alpha)
            backdrop = blend(backdrop, image, (0, 0), effect.blend_mode)

    for effect in layer.effects:
        if effect.__class__.__name__ == 'GradientOverlay':
            image = draw_gradient_fill(base_image.size, effect.value)
            if base_image.mode.endswith('A'):
                alpha = base_image.getchannel('A')
                if image.mode.endswith('A'):
                    alpha = ImageChops.darker(alpha, image.getchannel('A'))
                image.putalpha(alpha)
            backdrop = blend(backdrop, image, (0, 0), effect.blend_mode)

    for effect in layer.effects:
        if effect.__class__.__name__ == 'ColorOverlay':
            image = draw_solid_color_fill(base_image.size, effect.value)
            if base_image.mode.endswith('A'):
                alpha = base_image.getchannel('A')
                if image.mode.endswith('A'):
                    alpha = ImageChops.darker(alpha, image.getchannel('A'))
                image.putalpha(alpha)
            backdrop = blend(backdrop, image, (0, 0), effect.blend_mode)

    for effect in layer.effects:
        if effect.__class__.__name__ == 'Stroke':
            from PIL import ImageOps

            if layer.has_vector_mask():
                alpha = draw_vector_mask(layer)
            elif base_image.mode.endswith('A'):
                alpha = base_image.getchannel('A')
            else:
                alpha = base_image.convert('L')
            alpha.info['offset'] = base_image.info['offset']
            flat = alpha.getextrema()[0] < 255

            # Expand the image size
            setting = effect.value
            size = int(setting.get(Key.SizeKey))
            offset = backdrop.info['offset']
            backdrop = ImageOps.expand(backdrop, size)
            backdrop.info['offset'] = tuple(x - size for x in offset)
            offset = alpha.info['offset']
            alpha = ImageOps.expand(alpha, size)
            alpha.info['offset'] = tuple(x - size for x in offset)

            if not layer.has_vector_mask() and setting.get(
                    Key.Style).enum == Enum.InsetFrame and flat:
                image = create_stroke_effect(alpha, setting, layer._psd, True)
                backdrop.paste(image)
            else:
                image = create_stroke_effect(alpha, setting, layer._psd)
                backdrop = blend(backdrop, image, (0, 0), effect.blend_mode)

    return backdrop
Ejemplo n.º 48
0
    def _train_sync_transform(self, img, mask):
        '''
        :param image:  PIL input image
        :param gt_image: PIL input gt_image
        :return:
        '''
        if self.random_mirror:
            # random mirror
            if random.random() < 0.5:
                img = img.transpose(Image.FLIP_LEFT_RIGHT)
                if mask:
                    mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
            crop_w, crop_h = self.crop_size

        if self.random_crop:
            # random scale
            base_w, base_h = self.base_size
            w, h = img.size
            assert w >= h
            if (base_w / w) > (base_h / h):
                base_size = base_w
                short_size = random.randint(int(base_size * 0.5),
                                            int(base_size * 2.0))
                ow = short_size
                oh = int(1.0 * h * ow / w)
            else:
                base_size = base_h
                short_size = random.randint(int(base_size * 0.5),
                                            int(base_size * 2.0))
                oh = short_size
                ow = int(1.0 * w * oh / h)

            img = img.resize((ow, oh), Image.BICUBIC)
            if mask:
                mask = mask.resize((ow, oh), Image.NEAREST)
            # pad crop
            if ow < crop_w or oh < crop_h:
                padh = crop_h - oh if oh < crop_h else 0
                padw = crop_w - ow if ow < crop_w else 0
                img = ImageOps.expand(img, border=(0, 0, padw, padh), fill=0)
                if mask:
                    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_w)
            y1 = random.randint(0, h - crop_h)
            img = img.crop((x1, y1, x1 + crop_w, y1 + crop_h))
            if mask:
                mask = mask.crop((x1, y1, x1 + crop_w, y1 + crop_h))
        elif self.resize:
            img = img.resize(self.crop_size, Image.BICUBIC)
            if mask:
                mask = mask.resize(self.crop_size, Image.NEAREST)

        if self.gaussian_blur:
            # gaussian blur as in PSP
            if random.random() < 0.5:
                img = img.filter(
                    ImageFilter.GaussianBlur(radius=random.random()))
        # final transform
        if mask:
            img, mask = self._img_transform(img), self._mask_transform(mask)
            return img, mask
        else:
            img = self._img_transform(img)
            return img
Ejemplo n.º 49
0
 def add_border(self, image):
     return ImageOps.expand(image, border=41, fill='black')
Ejemplo n.º 50
0
 def resizeImage(self, qualityMode=None):
     upscale = self.opt.upscale
     stretch = self.opt.stretch
     bordersColor = self.opt.bordersColor
     if qualityMode is None:
         qualityMode = self.opt.quality
     if bordersColor:
         fill = bordersColor
     else:
         fill = self.fill
     # Set target size
     if qualityMode == 0:
         size = (self.size[0], self.size[1])
     elif qualityMode == 1 and not stretch and not upscale and self.image.size[0] <=\
             self.size[0] and self.image.size[1] <= self.size[1]:
         size = (self.size[0], self.size[1])
     elif qualityMode == 1:
         # Forcing upscale to make sure that margins will be not too big
         if not stretch:
             upscale = True
         size = (self.panelviewsize[0], self.panelviewsize[1])
     elif qualityMode == 2 and not stretch and not upscale and self.image.size[0] <=\
             self.size[0] and self.image.size[1] <= self.size[1]:
         self.purge = True
         return self.image
     else:
         self.hq = True
         size = (self.panelviewsize[0], self.panelviewsize[1])
     # If stretching is on - Resize without other considerations
     if stretch:
         if self.image.size[0] <= size[0] and self.image.size[1] <= size[1]:
             method = Image.BICUBIC
         else:
             method = Image.LANCZOS
         self.image = self.image.resize(size, method)
         return self.image
     # If image is smaller than target resolution and upscale is off - Just expand it by adding margins
     if self.image.size[0] <= size[0] and self.image.size[1] <= size[
             1] and not upscale:
         borderw = int((size[0] - self.image.size[0]) / 2)
         borderh = int((size[1] - self.image.size[1]) / 2)
         # PV is disabled when source image is smaller than device screen and upscale is off
         if self.image.size[0] <= self.size[0] and self.image.size[
                 1] <= self.size[1]:
             self.noPV = True
         self.image = ImageOps.expand(self.image,
                                      border=(borderw, borderh),
                                      fill=fill)
         # Border can't be float so sometimes image might be 1px too small/large
         if self.image.size[0] != size[0] or self.image.size[1] != size[1]:
             self.image = ImageOps.fit(self.image,
                                       size,
                                       method=Image.BICUBIC,
                                       centering=(0.5, 0.5))
         return self.image
     # Otherwise - Upscale/Downscale
     ratioDev = float(size[0]) / float(size[1])
     if (float(self.image.size[0]) / float(self.image.size[1])) < ratioDev:
         diff = int(self.image.size[1] * ratioDev) - self.image.size[0]
         self.image = ImageOps.expand(self.image,
                                      border=(int(diff / 2), 0),
                                      fill=fill)
     elif (float(self.image.size[0]) /
           float(self.image.size[1])) > ratioDev:
         diff = int(self.image.size[0] / ratioDev) - self.image.size[1]
         self.image = ImageOps.expand(self.image,
                                      border=(0, int(diff / 2)),
                                      fill=fill)
     if self.image.size[0] <= size[0] and self.image.size[1] <= size[1]:
         method = Image.BICUBIC
     else:
         method = Image.LANCZOS
     self.image = ImageOps.fit(self.image,
                               size,
                               method=method,
                               centering=(0.5, 0.5))
     return self.image
Ejemplo n.º 51
0
def add_border(x, color='', size=2):
    
    from PIL import ImageOps
    if color is not '': 
        x = ImageOps.expand(x, border=size, fill=color)
    return x
Ejemplo n.º 52
0
                os.rename(filename,
                          (str(int(filename[4:5]) + MATSIZE * j) + '.png'))
            elif filename.startswith("0" + str(j + 1) + "_") and j + 1 > 10:
                os.rename(filename,
                          (str(int(filename[4:6]) + MATSIZE * j) + '.png'))
x = (300 / (2 * MATSIZE))
x = x - 1
for i in range(d):
    imgx = Image.open(str(i + 1) + '.png')
    halfwidth = imgx.size[0] / 2
    halfheight = imgx.size[1] / 2
    imgcrop = imgx.crop(
        (halfwidth - x, halfheight - x, halfwidth + x, halfheight + x))
    imgcrop.save(str(i + 1) + '.png')
    imgx = Image.open(str(i + 1) + '.png')
    imgborder = ImageOps.expand(imgx, border=5, fill='white')
    imgborder.save(str(i + 1) + '.png')

pygame.init()

INDS = 300 / MATSIZE
MP = 1
RANDOMIZEUPTO = 1
FPS = 30  # frames per second setting
fpsClock = pygame.time.Clock()
NumberOfMoves = 0
BLACK = (0, 0, 0)

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 400), 0, 32)
pygame.display.set_caption('Tile Game')
Ejemplo n.º 53
0
from PIL import Image, ImageOps
from sys import argv
try:
    image = argv[2]
    number = int(argv[1])
    output = argv[3]
    im = Image.open(image)
    (width, height) = im.size
    if (width + number) > 11000:
        print('Too many pixels')
        raise SystemExit()
    if (height + number) > 11000:
        print('Too many pixels')
        raise SystemExit()
    if number < 0:
        print('Bad pixel number')
        raise SystemExit()
    ImageOps.expand(im, border=number, fill='black').save(output)
except IndexError:
    print('No arguments')
except FileNotFoundError:
    print('File not found')
except MemoryError:
    print('Not enough memory')
Ejemplo n.º 54
0
def pad(
    img: Image.Image,
    padding: Union[int, List[int], Tuple[int, ...]],
    fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
    padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
) -> Image.Image:

    if not _is_pil_image(img):
        raise TypeError(f"img should be PIL Image. Got {type(img)}")

    if not isinstance(padding, (numbers.Number, tuple, list)):
        raise TypeError("Got inappropriate padding arg")
    if not isinstance(fill, (numbers.Number, str, tuple)):
        raise TypeError("Got inappropriate fill arg")
    if not isinstance(padding_mode, str):
        raise TypeError("Got inappropriate padding_mode arg")

    if isinstance(padding, list):
        padding = tuple(padding)

    if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]:
        raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple")

    if isinstance(padding, tuple) and len(padding) == 1:
        # Compatibility with `functional_tensor.pad`
        padding = padding[0]

    if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
        raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")

    if padding_mode == "constant":
        opts = _parse_fill(fill, img, name="fill")
        if img.mode == "P":
            palette = img.getpalette()
            image = ImageOps.expand(img, border=padding, **opts)
            image.putpalette(palette)
            return image

        return ImageOps.expand(img, border=padding, **opts)
    else:
        if isinstance(padding, int):
            pad_left = pad_right = pad_top = pad_bottom = padding
        if isinstance(padding, tuple) and len(padding) == 2:
            pad_left = pad_right = padding[0]
            pad_top = pad_bottom = padding[1]
        if isinstance(padding, tuple) and len(padding) == 4:
            pad_left = padding[0]
            pad_top = padding[1]
            pad_right = padding[2]
            pad_bottom = padding[3]

        p = [pad_left, pad_top, pad_right, pad_bottom]
        cropping = -np.minimum(p, 0)

        if cropping.any():
            crop_left, crop_top, crop_right, crop_bottom = cropping
            img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom))

        pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0)

        if img.mode == "P":
            palette = img.getpalette()
            img = np.asarray(img)
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode)
            img = Image.fromarray(img)
            img.putpalette(palette)
            return img

        img = np.asarray(img)
        # RGB image
        if len(img.shape) == 3:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)
        # Grayscale image
        if len(img.shape) == 2:
            img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)

        return Image.fromarray(img)
Ejemplo n.º 55
0
def expand(v=30):
    v = int(v)
    image = Image.open(name)
    image = ImageOps.expand(image, border=v)
    image.save(name)
Ejemplo n.º 56
0
def writeBezelConfig(bezel, retroarchConfig, systemName, rom, gameResolution,
                     bezel_stretch):
    # disable the overlay
    # if all steps are passed, enable them
    retroarchConfig['input_overlay_hide_in_menu'] = "false"
    overlay_cfg_file = batoceraFiles.overlayConfigFile

    # bezel are disabled
    # default values in case something wrong append
    retroarchConfig['input_overlay_enable'] = "false"
    retroarchConfig['video_message_pos_x'] = 0.05
    retroarchConfig['video_message_pos_y'] = 0.05

    if bezel is None:
        return

    bz_infos = bezelsUtil.getBezelInfos(rom, bezel, systemName)
    if bz_infos is None:
        return

    overlay_info_file = bz_infos["info"]
    overlay_png_file = bz_infos["png"]
    bezel_game = bz_infos["specific_to_game"]

    # only the png file is mandatory
    if os.path.exists(overlay_info_file):
        try:
            infos = json.load(open(overlay_info_file))
        except:
            infos = {}
    else:
        infos = {}

    # if image is not at the correct size, find the correct size
    bezelNeedAdaptation = False
    viewPortUsed = True
    if "width" not in infos or "height" not in infos or "top" not in infos or "left" not in infos or "bottom" not in infos or "right" not in infos:
        viewPortUsed = False

    gameRatio = float(gameResolution["width"]) / float(
        gameResolution["height"])

    if viewPortUsed:
        if gameResolution["width"] != infos["width"] or gameResolution[
                "height"] != infos["height"]:
            if gameRatio < 1.6:  # let's use bezels only for 16:10, 5:3, 16:9 and wider aspect ratios
                return
            else:
                bezelNeedAdaptation = True
        retroarchConfig['aspect_ratio_index'] = str(
            ratioIndexes.index(
                "custom"))  # overwritten from the beginning of this file
    else:
        # when there is no information about width and height in the .info, assume that the tv is HD 16/9 and infos are core provided
        if gameRatio < 1.6:  # let's use bezels only for 16:10, 5:3, 16:9 and wider aspect ratios
            return
        else:
            # No info on the bezel, let's get the bezel image width and height and apply the
            # ratios from usual 16:9 1920x1080 bezels (example: theBezelProject)
            try:
                infos["width"], infos["height"] = bezelsUtil.fast_image_size(
                    overlay_png_file)
                infos["top"] = int(infos["height"] * 2 / 1080)
                infos["left"] = int(
                    infos["width"] * 241 / 1920
                )  # 241 = (1920 - (1920 / (4:3))) / 2 + 1 pixel = where viewport start
                infos["bottom"] = int(infos["height"] * 2 / 1080)
                infos["right"] = int(infos["width"] * 241 / 1920)
                bezelNeedAdaptation = True
            except:
                pass  # outch, no ratio will be applied.
        if gameResolution["width"] == infos["width"] and gameResolution[
                "height"] == infos["height"]:
            bezelNeedAdaptation = False
        retroarchConfig['aspect_ratio_index'] = str(ratioIndexes.index("core"))

    retroarchConfig['input_overlay_enable'] = "true"
    retroarchConfig['input_overlay_scale'] = "1.0"
    retroarchConfig['input_overlay'] = overlay_cfg_file
    retroarchConfig['input_overlay_hide_in_menu'] = "true"

    if "opacity" not in infos:
        infos["opacity"] = 1.0
    if "messagex" not in infos:
        infos["messagex"] = 0.0
    if "messagey" not in infos:
        infos["messagey"] = 0.0

    retroarchConfig['input_overlay_opacity'] = infos["opacity"]

    if bezelNeedAdaptation:
        wratio = gameResolution["width"] / float(infos["width"])
        hratio = gameResolution["height"] / float(infos["height"])

        # If width or height < original, can't add black borders, need to stretch
        if gameResolution["width"] < infos["width"] or gameResolution[
                "height"] < infos["height"]:
            bezel_stretch = True

        if bezel_stretch:
            retroarchConfig['custom_viewport_x'] = infos["left"] * wratio
            retroarchConfig['custom_viewport_y'] = infos["top"] * hratio
            retroarchConfig['custom_viewport_width'] = (
                infos["width"] - infos["left"] - infos["right"]) * wratio
            retroarchConfig['custom_viewport_height'] = (
                infos["height"] - infos["top"] - infos["bottom"]) * hratio
            retroarchConfig['video_message_pos_x'] = infos["messagex"] * wratio
            retroarchConfig['video_message_pos_y'] = infos["messagey"] * hratio
        else:
            if bezel_game is True:
                output_png_file = "/tmp/bezel_game_adapted.png"
                create_new_bezel_file = True
            else:
                create_new_bezel_file = False
                output_png_file = "/tmp/" + os.path.splitext(
                    os.path.basename(overlay_png_file))[0] + "_adapted.png"
                if os.path.exists(output_png_file) is False:
                    create_new_bezel_file = True
                else:
                    if os.path.getmtime(output_png_file) < os.path.getmtime(
                            overlay_png_file):
                        create_new_bezel_file = True
            # fast way of checking the size of a png
            oldwidth, oldheight = bezelsUtil.fast_image_size(output_png_file)
            if (oldwidth != gameResolution["width"]
                    or oldheight != gameResolution["height"]):
                create_new_bezel_file = True

            xoffset = gameResolution["width"] - infos["width"]
            yoffset = gameResolution["height"] - infos["height"]
            retroarchConfig['custom_viewport_x'] = infos["left"] + xoffset / 2
            retroarchConfig['custom_viewport_y'] = infos["top"] + yoffset / 2
            retroarchConfig['custom_viewport_width'] = infos["width"] - infos[
                "left"] - infos["right"]
            retroarchConfig['custom_viewport_height'] = infos[
                "height"] - infos["top"] - infos["bottom"]
            retroarchConfig[
                'video_message_pos_x'] = infos["messagex"] + xoffset / 2
            retroarchConfig[
                'video_message_pos_y'] = infos["messagey"] + yoffset / 2

            if create_new_bezel_file is True:
                # Padding left and right borders for ultrawide screens (larger than 16:9 aspect ratio)
                # or up/down for 4K
                eslog.log("Generating a new adapted bezel file {}".format(
                    output_png_file))
                fillcolor = 'black'

                borderw = 0
                borderh = 0
                if wratio > 1:
                    borderw = xoffset / 2
                if hratio > 1:
                    borderh = yoffset / 2
                imgin = Image.open(overlay_png_file)
                if imgin.mode != "RGBA":
                    # TheBezelProject have Palette + alpha, not RGBA. PIL can't convert from P+A to RGBA.
                    # Even if it can load P+A, it can't save P+A as PNG. So we have to recreate a new image to adapt it.
                    if not 'transparency' in imgin.info:
                        return  # no transparent layer for the viewport, abort
                    alpha = imgin.split()[
                        -1]  # alpha from original palette + alpha
                    ix, iy = imgin.size
                    imgnew = Image.new("RGBA", (ix, iy), (0, 0, 0, 255))
                    imgnew.paste(alpha, (0, 0, ix, iy))
                    imgout = ImageOps.expand(imgnew,
                                             border=(borderw, borderh,
                                                     xoffset - borderw,
                                                     yoffset - borderh),
                                             fill=fillcolor)
                    imgout.save(output_png_file, mode="RGBA", format="PNG")
                else:
                    imgout = ImageOps.expand(imgin,
                                             border=(borderw, borderh,
                                                     xoffset - borderw,
                                                     yoffset - borderh),
                                             fill=fillcolor)
                    imgout.save(output_png_file, mode="RGBA", format="PNG")
            overlay_png_file = output_png_file  # replace by the new file (recreated or cached in /tmp)
    else:
        if viewPortUsed:
            retroarchConfig['custom_viewport_x'] = infos["left"]
            retroarchConfig['custom_viewport_y'] = infos["top"]
            retroarchConfig['custom_viewport_width'] = infos["width"] - infos[
                "left"] - infos["right"]
            retroarchConfig['custom_viewport_height'] = infos[
                "height"] - infos["top"] - infos["bottom"]
        retroarchConfig['video_message_pos_x'] = infos["messagex"]
        retroarchConfig['video_message_pos_y'] = infos["messagey"]

    eslog.log("Bezel file set to {}".format(overlay_png_file))
    writeBezelCfgConfig(overlay_cfg_file, overlay_png_file)
if student.AdjectivesIGet.exists():
    createWordCloud(student)

##########################################
# prepare directory

ROOT_DIR = "media/collage_and_yearbook_personal"
student_dir_path = os.path.join(ROOT_DIR, student.user.username)
folder_path = os.path.join(student_dir_path, 'collages')
if os.path.exists(folder_path) and os.path.isdir(folder_path):
    shutil.rmtree(folder_path)
os.makedirs(folder_path)

if student.closeFriendsPic:
    rgb_img = Image.open(student.closeFriendsPic.path).convert('RGB')
    ImageOps.expand(rgb_img, border=200, fill='white').save(
        os.path.join(student_dir_path, "closeFriendsPic.jpg"))

for friendUserName in friendsGroup:
    i = User.objects.get(username=(friendUserName).lower()).student
    if i.closeFriendsPic:
        shutil.copyfile(
            i.closeFriendsPic.path,
            os.path.join(folder_path,
                         os.path.basename(i.closeFriendsPic.name)))

##########################################
# generate collage

ROOT_DIR = "media/collage_and_yearbook_personal"
BATCH_SIZE = 8
Ejemplo n.º 58
0
def start():
    startbutton.config(state='disabled')
    browsebutton.config(state='disabled')
    mvar = 'Creating wallpaper. Please wait...'
    messvar.set(mvar)

    ### CODE ###
    print('>> Opening image...')
    img = i.open(filename)
    wid, hei = math.ceil(
        img.size[1] *
        (16 / 9)), img.size[1]  # Working out 16:9 width for original height

    # print(f'>> Orig size:   {img.size}')
    # print(f'>> New size:   {wid, hei}')

    mode = 'RGBA'
    global bkg
    bkg = i.new(mode, (wid, hei))  # Background

    def split(
        pos
    ):  # Splits image in 2 and puts top half on the left and bottom on the right
        imgcent = math.ceil(hei / 2)  # Image center
        blur = hei / 200
        global fopt

        if pos == 't':
            print('>> Creating left background...')
            s = img.crop(box=(
                0, 0, img.size[0],
                imgcent))  # Cropping image - 4 tuple: left,top,right,bottom
        elif pos == 'b':
            print('>> Creating right background...')
            s = img.crop(box=(0, imgcent, img.size[0], img.size[1]))

        sr = s.resize(tuple(
            z * 2
            for z in s.size))  # Scaling up by 2 because img was split in two

        if cmvar.get() == 1:  # Colour map
            if invvar.get() == 1:
                cmblack = cmwvar.get()
                cmwhite = cmbvar.get()
            else:
                cmblack = cmbvar.get()
                cmwhite = cmwvar.get()
            sr = sr.convert('L')  # Convert to greyscale
            sr = ImageOps.colorize(sr, black=cmblack,
                                   white=cmwhite)  # colour map

        if fopt.get() == 0:  # Filter options
            pass
        else:
            if fopt.get() != 2:  # If radio button 3 not chosen
                sr = sr.filter(
                    ImageFilter.GaussianBlur(radius=blur))  # Gaussian blur

            if fopt.get() != 1:  # If radio button 2 not chosen
                # https://stackoverflow.com/questions/43618910/pil-drawing-a-semi-transparent-square-overlay-on-image
                sr = i.eval(sr, lambda x: x / 2)

        if plbvar.get() == 0:  # Matplotlib colour map
            pass
        else:
            pltcm = matplotlib.cm.get_cmap(pltvar.get())  # color map
            sr = sr.convert('L')
            sr = np.array(sr)
            sr = pltcm(sr)
            sr = np.uint8(sr * 255)
            sr = i.fromarray(sr)

        if icvar.get() == 1:  # Invert colours
            sr = ImageOps.invert(sr)

        return sr

    ## Working out where top and bottom splits are to be pasted
    print('>> Calculating dimensions...')
    sw = math.ceil((wid - img.size[0]) / 2)  # split width

    tspos = (math.ceil((sw / 2) - img.size[0]), 0)  # Top split position
    bspos = (math.ceil((wid - sw / 2) - img.size[0]), 0
             )  # Bottom split position

    print('>> Creating background...')
    bkg.paste(split('t'), box=tspos)
    bkg.paste(split('b'), box=bspos)

    bkg.paste(img, box=(math.ceil((wid / 2) - (img.size[0] / 2)),
                        0))  # Paste original image in the center of new image

    # Add border
    if bordvar.get() == 1:
        bkg = ImageOps.expand(bkg, border=wid // 100, fill='black')
    elif bordvar.get() == 0:
        pass

    print('>> Exporting image...')
    dt = time.strftime('%Y-%m-%d_%H-%M-%S')
    path = f'./walls/wallpaper-{dt}.png'

    previmg = ImageTk.PhotoImage(
        image=bkg)  # Creating a PhotoImage of image object to load on canvas
    setprev = preview.create_image(
        0, 0, image=previmg)  # Loading photoimage on canvas
    preview.itemconfig(setprev)
    tkinter.Tk()

    # bkg.save(path)
    # bkg.show()

    # ~ Resetting GUI ~
    startbutton.config(state='normal')
    browsebutton.config(state='normal')
    bordbutton.config(state='normal')

    mvar = f'Done. File saved as ./walls/{dt}.png\n'
    print(f'>> {mvar}')
    messvar.set(mvar)
Ejemplo n.º 59
0
for i, j in zip(activationLabel, map(str, chartLegendPercent)):
    legendLabels.append(i + ' (' + j + ' %)')

colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

fig1 = plt.figure()
plt.pie(activationValue, labels=None, colors=colors, explode=explodeValues, autopct=None, shadow=False, startangle=90)
plt.axis('equal')
plt.title('User status', pad=20, fontsize=15)
plt.legend(legendLabels, loc='best', fontsize=10)

fig1.savefig(workDirectory+'myplot1.png', dpi=70)
plt.clf()

im = Image.open(workDirectory+'myplot1.png')
bordered = ImageOps.expand(im, border=1, fill=(0, 0, 0))
bordered.save(workDirectory+'myplot1.png')

# INSERT CHART IN EXCEL
img = openpyxl.drawing.image.Image(workDirectory+'myplot1.png')
img.anchor = 'A8'

workbook['Registrations'].add_image(img)
workbook.save(outputExcelFile)


# CHART CATEGORIES
chartLabel = df_Categories_count['Categories'].tolist()
chartLegendLabel = df_Categories_count['Categories'].tolist()
chartValue = df_Categories_count['Total'].tolist()
chartLegendPercent = df_Categories_count['Percent'].tolist()
Ejemplo n.º 60
0
def start():
    startbutton.config(state='disabled')
    previewbutton.config(state='disabled')
    browsebutton.config(state='disabled')
    mvar = 'Creating wallpaper. Please wait...'
    messvar.set(mvar)

    ### CODE ###
    print('>> Opening image...')
    img = i.open(filename)
    origimg = img  # Original image to be used later
    wid, hei = math.ceil(
        img.size[1] *
        (16 / 9)), img.size[1]  # Working out 16:9 width for original height

    # print(f'>> Orig size:   {img.size}')
    # print(f'>> New size:   {wid, hei}')

    mode = 'RGBA'
    global bkg
    bkg = i.new(mode, (wid, hei))  # Background

    if cmvar.get() == 1:  # Colour map
        if invvar.get() == 1:
            cmblack = cmwvar.get()
            cmwhite = cmbvar.get()
        else:
            cmblack = cmbvar.get()
            cmwhite = cmwvar.get()
        img = img.convert('L')  # Convert to greyscale
        img = ImageOps.colorize(img, black=cmblack,
                                white=cmwhite)  # colour map

    ## Matplotlib colour map

    if plbvar.get() == 0:
        pass
    else:
        print(f'>> Applying {pltvar.get()} colour map...')
        pltcm = matplotlib.cm.get_cmap(pltvar.get())  # color map
        img = img.convert('L')
        img = np.array(img)
        img = pltcm(img)
        img = np.uint8(img * 255)
        img = i.fromarray(img)

    ## Invert colours

    if icvar.get() == 1:
        print('>> Inverting image...')
        img = img.convert('RGB')
        # print(img.mode)
        img = ImageOps.invert(img)

    ## Gaussian Blur

    blurval = int(blurslider.get())  # Slider value

    if blurval == 0:  # Filter options
        pass
    else:
        print('>> Applying Gaussian Blur...')
        # blur = hei/()*8
        img = img.filter(
            ImageFilter.GaussianBlur(radius=(blurval * 0.1)))  # Gaussian blur

    ## Darken

    if fopt.get() == 2 or fopt.get() == 3:  # If radio button 2 not chosen
        # https://stackoverflow.com/questions/43618910/pil-drawing-a-semi-transparent-square-overlay-on-image
        ndimg = img  # Non darkened image to paste on top
        img = i.eval(img, lambda x: x / 1.5)

    ## Split image

    def split(
        pos
    ):  # Splits image in 2 and puts top half on the left and bottom on the right
        imgcent = math.ceil(hei / 2)  # Image center

        global fopt

        if pos == 't':
            print('>> Creating left background...')
            s = img.crop(box=(
                0, 0, img.size[0],
                imgcent))  # Cropping image - 4 tuple: left,top,right,bottom
        elif pos == 'b':
            print('>> Creating right background...')
            s = img.crop(box=(0, imgcent, img.size[0], img.size[1]))

        sr = s.resize(tuple(
            z * 2
            for z in s.size))  # Scaling up by 2 because img was split in two

        return sr

    ## Working out where top and bottom splits are to be pasted
    print('>> Calculating dimensions...')
    sw = math.ceil((wid - img.size[0]) / 2)  # split width

    tspos = (math.ceil((sw / 2) - img.size[0]), 0)  # Top split position
    bspos = (math.ceil((wid - sw / 2) - img.size[0]), 0
             )  # Bottom split position

    print('>> Creating background...')
    bkg.paste(split('t'), box=tspos)
    bkg.paste(split('b'), box=bspos)

    if fopt.get() == 1 or fopt.get() == 3:  # If radiobutton 2 or 4 are chosen
        bkg.paste(ndimg,
                  box=(math.ceil((wid / 2) - (img.size[0] / 2)),
                       0))  # Paste edited image in the center of new image
    else:
        bkg.paste(origimg,
                  box=(math.ceil((wid / 2) - (img.size[0] / 2)),
                       0))  # Paste original image in the center of new image

    # Add border
    if bordvar.get() == 1:
        bkg = ImageOps.expand(bkg, border=wid // 100, fill='black')
    elif bordvar.get() == 0:
        pass

    prevbkg = bkg.resize((800, 450))  # Resizing preview image to fit on canvas
    previmg = ImageTk.PhotoImage(
        image=prevbkg
    )  # Creating a PhotoImage of image object to load on canvas
    preview.create_image(0, 0, image=previmg,
                         anchor='nw')  # Loading photoimage on canvas
    preview.image = previmg  # https://web.archive.org/web/20201111190625id_/http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
    # preview.itemconfig(setprev)
    # tkinter.Tk()
    # master.mainloop()

    # ~ Resetting GUI ~
    startbutton.config(state='normal')
    previewbutton.config(state='normal')
    browsebutton.config(state='normal')
    bordbutton.config(state='normal')