Esempio n. 1
0
def getcolor(image, color):
    if image.getbands() == ('R', 'G', 'B', 'A'):
        return IC.getcolor(color, 'RGBA')
    elif image.getbands() == ('1',):
        return IC.getcolor(color, 'L')
    else:
        raise exceptions.NotImplementedError('Only RGBA or L format!')
Esempio n. 2
0
    def _setup_ui(self):
        """
        Sets up the UI
        """

        self.window = ui.Widget()
        self.window.dimensions = ui.normalize_dimension((
            0, 0,
            self.normalized_screen_resolution[0],
            self.normalized_screen_resolution[1]
        ))
        self.window.background_color = ImageColor.getcolor('#000000', 'RGB')

        interface_frame = ui.Widget(parent=self.window)
        interface_frame.dimensions = ui.normalize_dimension((
            self.preview_renderer.window[2],
            0,
            self.normalized_screen_resolution[0] - self.preview_renderer.window[2],
            self.normalized_screen_resolution[1]
        ))
        interface_frame.background_color = ImageColor.getcolor('#ffffff', 'RGB')

        number = ui.LabelWidget("",
                                name=NAME_GET_STARTED,
                                parent=interface_frame,
                                align="center",
                                font_color=(0, 0, 0, 255))
        number.dimensions = (
            5, 5,
            interface_frame.width - 10,
            interface_frame.height - 10
        )
Esempio n. 3
0
def to_colors(which):
    strs = config.get('settings', which).split()
    return {
        'norm': ImageColor.getcolor(strs[0], 'RGBA'),
        'hover': ImageColor.getcolor(strs[1], 'RGBA'),
        'barred': ImageColor.getcolor(strs[2], 'RGBA'),
    }
Esempio n. 4
0
def draw(layers):
    im = Image.new('1', (25, 6))
    layers = wrap(layers, 25)
    for element in layers:
        i = 0
        while i < len(element):
            if element[i] == '1':
                im.putpixel((i, layers.index(element)),
                            ImageColor.getcolor('white', '1'))
            else:
                im.putpixel((i, layers.index(element)),
                            ImageColor.getcolor('black', '1'))
            i = i + 1
    im.show()
Esempio n. 5
0
def createColors(inicial, final, n):
    ri, gi, bi = ImageColor.getcolor(inicial, 'RGB')
    rf, gf, bf = ImageColor.getcolor(final, 'RGB')
    reds = np.linspace(ri, rf, n)
    greens = np.linspace(gi, gf, n)
    blues = np.linspace(bi, bf, n)

    color = []

    for i, c in enumerate(reds):
        c = rgb2hex(int(round(reds[i].tolist(), 0)), int(round(greens[i].tolist(), 0)), int(round(blues[i].tolist(), 0)))
        color.append(c)

    return color
def draw_morton(n, mg, width, color='black'):
    sz = width + mg * ((1 << n) - 1)
    img = Image.new('RGB', (sz, sz), ImageColor.getcolor('white', 'RGB'))
    draw = ImageDraw.Draw(img)
    gen = morton(n)
    corner = (width >> 1, width >> 1)
    scaler = lambda x: scale_point(x, corner, mg)
    pos = next(gen)
    for npos in gen:
        draw.line(list(map(scaler, [pos, npos])),
                  fill=ImageColor.getcolor(color, img.mode),
                  width=width)
        pos = npos
    return img
Esempio n. 7
0
def main():
    parser = ap.ArgumentParser(
        description='Convert an image into 16 bit sprite font')
    parser.add_argument("input_path", help='Input file path')
    parser.add_argument("output_path", help='Output file path')
    parser.add_argument("name", help='buffer name')
    parser.add_argument(
        "bgcol",
        help='Background colour (will be replaced with transparent pixels)')
    parser.add_argument(
        "marker",
        help='Marker colour (marks top-left corner of each character)')
    parser.add_argument("first_char",
                        help='First character as ASCII ordinal',
                        type=int)
    parser.add_argument("last_char",
                        help='Last character as ASCII ordinal',
                        type=int)
    args = parser.parse_args()

    first_char = chr(args.first_char)
    last_char = chr(args.last_char)
    marker_colour = list(ImageColor.getcolor(args.marker, "RGB"))
    marker_colour.append(255)
    background_colour = list(ImageColor.getcolor(args.bgcol, "RGB"))
    background_colour.append(255)

    global output
    output = open(args.output_path, "w", encoding="utf-8", newline='\n')

    ## Get data as RGBA
    (image_data, width, height) = get_image(args.input_path)

    ## Find the marker pixels (return list of indices) and replace them all with BG colour
    markers = find_markers(image_data, marker_colour, background_colour)

    ## Replace all BG coloured pixels with transparent black
    image_data = replace_background(image_data, width, height,
                                    background_colour)

    ## Apply alpha threshold (either completely transparent or completely opaque)
    image_data = alpha_threshold(image_data, width, height, 0.5)

    ## Extract individual characters to their own arrays
    characters = extract_chars(image_data, width, height, markers)

    ## Write to output file
    format_c(characters, args.name, fileprint, args.first_char, args.last_char,
             height)
Esempio n. 8
0
def colors_degrade(c1, c2, nbcolors):
    col = []
    [r1, g1, b1] = ImageColor.getcolor(c1, "RGB")
    [r2, g2, b2] = ImageColor.getcolor(c2, "RGB")

    dr = (r2 - r1) / nbcolors
    dg = (g2 - g1) / nbcolors
    db = (b2 - b1) / nbcolors
    for i in range(nbcolors + 1):
        r = int(r1 + i * dr)
        g = int(g1 + i * dg)
        b = int(b1 + i * db)
        col.append(f"#{r:02x}{g:02x}{b:02x}")

    return col
Esempio n. 9
0
def changeColorImg(img:PILImage, color_old:str, color_new:str=None) -> PILImage:
    #Convert hex color and img to rgba
    color_new = ImageColor.getcolor(color_new, "RGBA")
    if color_old: color_old = ImageColor.getcolor(color_old, "RGBA")
    img = img.convert("RGBA")

    #Change rgb foreach pixel, keeping alpha
    pixel_data = img.load()
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r,g,b,_ = color_new
            a = pixel_data[x,y][-1]
            pixel_data[x,y] = (r,g,b,a)

    return img
def decorate_perf_edges(image, edges):
    """
    Draw the edge points onto an image.  N&S are red, E&W are blue.
    """
    red = ImageColor.getcolor("red", "RGB")
    blue = ImageColor.getcolor("blue", "RGB")
    draw = ImageDraw.Draw(image, "RGB")
    for x in range(len(edges['N'])):
        for c in ('N', 'S'):
            if edges[c][x] is not None:
                draw.point((x, edges[c][x]), red)
    for y in range(len(edges['E'])):
        for c in ('E', 'W'):
            if edges[c][y] is not None:
                draw.point((edges[c][y], y), blue)
 def check_color_existance(arg):
     if isinstance(arg, str):
         try:
             ImageColor.getcolor(arg, "RGB")
         except:
             raise ValueError(f"color '{arg}' is not exist")
     elif isinstance(arg, tuple):
         if len(arg) != 3:
             msg = f'''color tuple must have lenght 3'.
                       len({arg}) = {len(arg)} were given'''
             raise ValueError(str_to_error_message(msg))
     else:
         msg = f'''color argument must be 'str' or 'tuple'.
                   type({arg}) = {type(arg)} were given'''
         raise ValueError(str_to_error_message(msg))
Esempio n. 12
0
    def execute(self):
        base_img_path = self.filepath / self.filename
        if not base_img_path.exists():
            return None

        masks_path = self.filepath / "masks"

        if not masks_path.exists():
            os.makedirs(masks_path)

        black = ImageColor.getcolor("black", "L")
        white = ImageColor.getcolor("white", "L")

        base_img: Image.Image = Image.open(base_img_path).convert("L")
        already_processed = set()

        mask_count = 0
        mask_centers = {}

        for y1 in range(base_img.height):
            for x1 in range(base_img.width):
                if (x1, y1) in already_processed:
                    continue
                if base_img.getpixel((x1, y1)) == self.region_color:
                    filled = floodfill(base_img, (x1, y1), black,
                                       self.wall_color)
                    if filled:  # Pixels were updated, make them into a mask
                        mask = Image.new("L", base_img.size, 255)
                        for x2, y2 in filled:
                            mask.putpixel((x2, y2), 0)

                        mask_count += 1
                        mask = mask.convert("L")
                        mask.save(masks_path / f"{mask_count}.png", "PNG")

                        mask_centers[mask_count] = get_center(filled)

                        already_processed.update(filled)

        number_img = Image.new("L", base_img.size, 255)
        fnt = ImageFont.load_default()
        d = ImageDraw.Draw(number_img)
        for mask_num, center in mask_centers.items():
            d.text(center, str(mask_num), font=fnt, fill=0)

        number_img.save(self.filepath / f"numbers.png", "PNG")

        return mask_centers
Esempio n. 13
0
    def __init__(self, palette):

        self.n_gears = random.choice([2, 3, 4, 5, 6])

        self.speeds = 1. * np.random.choice(
            [-1, 1], self.n_gears) * np.random.choice([0, 0, 1, 2, 4, 8, 16],
                                                      self.n_gears)

        radii = np.random.uniform(0.05, 1, self.n_gears)
        # this will lead to a strong bias towards smaller gears, while keeping the largest ones:
        #radii = radii**4
        radii = radii / np.sum(radii)
        self.radii = radii * 0.9  #make it take up *most* of the image

        self.cur_loc = np.array([sum(self.radii), 0])
        self.current_speed = 0

        self.colour_options = [[
            ImageColor.getcolor(v, "RGB") for v in colour_pair
        ] for colour_pair in palette.line_options]

        self.cur_color_range = self.colour_options[0]
        self.current_colour = None
        self.performed_regime_switch = False

        self.cur_angles = np.zeros(len(self.speeds))
Esempio n. 14
0
def brightness(image, amount=50):
    """Adjust brightness from black to white
    - amount: -1(black) 0 (unchanged) 1(white)
    - repeat: how many times it should be repeated"""
    if amount == 0:
        return image

    image = imtools.convert_safe_mode(image)

    if amount < 0:
        #fade to black
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size, 0),
                -amount / 100.0)
    else:
        #fade to white
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size,
                    ImageColor.getcolor('white', image.mode)),
                amount / 100.0)
    #fix image transparency mask
    if imtools.has_alpha(image):
        im.putalpha(imtools.get_alpha(image))
    return im
Esempio n. 15
0
    def prep(self, colors=None, **kwargs):
        """
        parameters for spatial color quantization

        :param colors: colors to use. can be a list of str
        or pixel array likes
        """

        if colors is None:
            colors = np.asarray([[]])
        elif type(colors) is list:
            rgb_colors = []
            for color in colors:
                if type(color) is str:
                    if color[0] != '#':
                        color = '#' + color
                    rgb_colors.append(ImageColor.getcolor(color, "RGB"))

            colors = np.asarray(rgb_colors)

        else:
            colors = np.array(colors)

        self.palette = colors.astype(np.dtype('uint8'))
        """palette to use"""
Esempio n. 16
0
 def color_templ(out_name, slice_no):
     out_name = str(out_name)
     slice_no = str(slice_no)
     dirpath = os.getcwd()
     out_dir = os.fsencode(dirpath)
     for file in os.listdir(out_dir):
         filename = os.fsdecode(file)
         if filename.startswith(slice_no):
             templ = Image.open(dirpath + '/' + filename)
             for i in range(len(labels_list)):
                 label_name = labels_list[i][0]
                 if (label_name[8:]) == slice_no + '.png':
                     area = int(label_name[5:7])
                     if colors[area] == None:
                         pass
                     else:
                         for j in range(len(labels_list[i])):
                             pixel = labels_list[i][j]
                             if type(pixel) == tuple:
                                 pixel_w = int(pixel[0])
                                 pixel_h = int(pixel[1])
                                 templ.putpixel((pixel_w, pixel_h),
                                                ImageColor.getcolor(
                                                    colors[area], 'RGBA'))
             templ = templ.filter(ImageFilter.BLUR)
             templ.save(
                 str(dirpath + '/output/' + out_name + '_' + slice_no),
                 'PNG')
Esempio n. 17
0
    def makeGradient(self, picture, start, end):
        if type(start) == str:
            start = ImageColor.getcolor(start, "RGB")
        if type(end) == str:
            end = ImageColor.getcolor(end, "RGB")
        gradient = Image.new('RGBA', picture.size, color=0)
        drawer = ImageDraw.Draw(gradient)
        for i, color in enumerate(self.interpolate(start, end, picture.width * 2)):
            drawer.line([(i, 0), (0, i)], tuple(color), width=1)

        drawer.line(((0,0), (0, 1000)), width=25, fill=(37,37,37))
        drawer.line(((0, 1000), (1000, 1000)), width=25, fill=(37,37,37))
        drawer.line(((1000, 1000), (1000,0)), width=25, fill=(37,37,37))
        drawer.line(((1000, 0), (0,0)), width=25, fill=(37,37,37))

        return Image.alpha_composite(gradient, picture)
Esempio n. 18
0
def image_tint(image, tint=None):
    if tint is None:
        return image
    if image.mode not in ['RGB', 'RGBA']:
        image = image.convert('RGBA')

    tr, tg, tb = ImageColor.getrgb(tint)
    tl = ImageColor.getcolor(tint, "L")  # tint color's overall luminosity
    if not tl:
        tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv / tl,
                     (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
            tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
            tuple(map(lambda lb: int(lb * sb + 0.5), range(256))))
    l = ImageOps.grayscale(image)  # 8-bit luminosity version of whole image
    if Image.getmodebands(image.mode) < 4:
        merge_args = (image.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of image's alpha layer
        a = Image.new("L", image.size)
        a.putdata(image.getdata(3))
        merge_args = (image.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)
Esempio n. 19
0
def hex_to_rgb(hex_code: str) -> tuple:
    """
    Converts HTML color code to RGB Color

    :hex_code -> html color code
    """
    return ImageColor.getcolor(hex_code, "RGBA")
Esempio n. 20
0
    def process_dual_image(self, photo_bundle):
        im = Image.open(photo_bundle.raw[0])
        im.thumbnail(map(lambda x: int(x * 0.5), im.size), Image.ANTIALIAS)
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1] + self.banner.size[1]) * 1.15) * 2
        new_width = int(new_height / 1.45)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        draw = ImageDraw.Draw(new_im)
        line_y = top_border + im.size[1] + self.banner.size[1]
        draw.line((0, line_y, new_width, line_y), fill=128, width=0)
        banner_x_start = int(new_width / 2 - self.banner.size[0] / 2)
        new_im.paste(self.banner, (banner_x_start, top_border + im.size[1]))
        new_im.paste(self.banner, (banner_x_start, int(top_border * 1.5) + im.size[1] * 2 + self.banner.size[1]))
        im_x_start = int(new_width / 2 - im.size[0] / 2)
        new_im.paste(im, (im_x_start, top_border))
        new_im.paste(im, (im_x_start, int(top_border * 1.5) + im.size[1] + self.banner.size[1]))
        esif_logo_x_start = int(new_width - im_x_start - self.esif_logo.size[0])
        esif_logo_y_start = int(top_border + im.size[1])
        new_im.paste(self.esif_logo, (esif_logo_x_start, esif_logo_y_start), mask=self.esif_logo)
        new_im.paste(self.esif_logo, (esif_logo_x_start, int(top_border * 1.5) + (im.size[1]*2) + self.banner.size[1]), mask=self.esif_logo)
        return new_im
Esempio n. 21
0
def thumbnail( image, size ):

    """ Create a thumbnail of the given image that fits into a box
        having the dimentions given in size (a tuple: width, height).

    """

    # Trim whitespace around image
    image = trim(image)

    # Calculate scaling ratio to get image to fit into the given size
    width, height         = [float(v) for v in image.size]
    new_width, new_height = [float(v) for v in size]
    ratio                 = min( new_width / width, new_height / height )

    # Scale the image to the new size
    image = image.resize(
        ( int(width * ratio), int(height * ratio) ),
        resample = Image.ANTIALIAS)

    
    # Apply light sharpening to bring out the details
    image = image.filter(ImageFilter.DETAIL)

    white = Image.new(image.mode, size, ImageColor.getcolor('white', image.mode))
    white.paste(image, ((size[0]-image.size[0])/2, (size[1]-image.size[1])/2))
    
    return white
Esempio n. 22
0
    def process_four_images(self, photo_bundle):
        images = map(lambda image: Image.open(image), photo_bundle.raw)
        new_size = map(lambda x: int(x * 0.5), images[0].size)
        map(lambda x: x.thumbnail(new_size, Image.ANTIALIAS), images)
        im = images[0]
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1]*2 + self.banner.size[1]) * 1.10)
        new_width = int((new_height / 1.45) * 2)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        banner_x_start = int(new_width / 2 - self.banner.size[0] / 2)
        new_im.paste(self.banner, (banner_x_start, top_border + im.size[1]))
        left_x_start = int(new_width / 4 - im.size[0] / 2)
        right_x_start = int(new_width / 2 + left_x_start)
        new_im.paste(images[0], (left_x_start, top_border))
        new_im.paste(images[1], (right_x_start, top_border))
        new_im.paste(images[2], (left_x_start, top_border + im.size[1] + self.banner.size[1]))
        new_im.paste(images[3], (right_x_start, top_border + im.size[1] + self.banner.size[1]))
        esif_logo_x_start = int(new_width - left_x_start - self.esif_logo.size[0])
        esif_logo_y_start = int((new_height - self.esif_logo.size[1])/2)
        new_im.paste(self.esif_logo, (esif_logo_x_start, esif_logo_y_start), mask=self.esif_logo)
        return new_im
Esempio n. 23
0
def image_tint(src, tint=None):
    r = lambda: random.randint(0,255)
    tint = tint or '#{:02X}{:02X}{:02X}'.format(r(), r(), r())
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = ImageColor.getrgb(tint)
    tl = ImageColor.getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (map(lambda lr: int(lr*sr + 0.5), range(256)) +
            map(lambda lg: int(lg*sg + 0.5), range(256)) +
            map(lambda lb: int(lb*sb + 0.5), range(256)))
    l = ImageOps.grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += range(256)  # for 1:1 mapping of copied alpha values

    return (Image.merge(*merge_args).point(luts), tint)
Esempio n. 24
0
def drawBoundingBoxes():
    global objects_information, to_be_annotated_input_dir, bounding_boxes_dir
    objects = objects_information['boundingboxes']
    labels = objects_information['labels_info']
    seg_stop = int(objects_information['segment_stop'])

    for obj in objects:
        if type(obj) == int and obj in objects:
            individual_obj = objects[obj]
            for frame in individual_obj:
                if (type(frame) != str):
                    if (int(frame.attrib['frame']) <= seg_stop):
                        if frame.attrib['outside'] == '0':
                            image = frame.attrib['frame']
                            top_left = (int(float(frame.attrib['xtl'])),
                                        int(float(frame.attrib['ytl'])))
                            bottom_right = (int(float(frame.attrib['xbr'])),
                                            int(float(frame.attrib['ybr'])))
                            box_label = objects[obj][len(objects[obj]) -
                                                     1] + str(obj)
                            RGBcolor = ImageColor.getcolor(
                                labels[objects[obj][len(objects[obj]) - 1]],
                                "RGB")
                            BGRcolor = (RGBcolor[2], RGBcolor[1], RGBcolor[0])
                            impath = os.path.join(to_be_annotated_input_dir,
                                                  image + ".png")
                            im = cv2.imread(impath)
                            img = cv2.rectangle(img=im,
                                                pt1=top_left,
                                                pt2=bottom_right,
                                                color=BGRcolor,
                                                thickness=1)
                            img = cv2.putText(
                                img,
                                text=box_label,
                                org=top_left,
                                fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                                fontScale=0.5,
                                color=BGRcolor,
                                thickness=1)
                            file = os.path.join(to_be_annotated_input_dir,
                                                image + ".png")
                            file = file.replace("\\", '/')
                            cv2.imwrite(file, img)

    names = os.listdir(to_be_annotated_input_dir)
    global current_video_processed
    videodir = os.path.join(set.LIST_OF_VIDEOS_DIR, current_video_processed)
    results_dir = os.path.join(videodir, "results")
    if (os.path.isdir(results_dir) != True):
        os.mkdir(results_dir)
    bounding_boxes_results = os.path.join(results_dir, "Bounding Boxes")
    if (os.path.isdir(bounding_boxes_results) != True):
        os.mkdir(bounding_boxes_results)

    for name in names:
        srcname = os.path.join(to_be_annotated_input_dir, name)
        dstname = os.path.join(bounding_boxes_dir, name)
        copy2(srcname, dstname)
        copy2(srcname, os.path.join(bounding_boxes_results, name))
Esempio n. 25
0
    def color(self, string):
        try:
            rgb, brightness = ImageColor.getrgb(string), ImageColor.getcolor(
                string, 'L')
        except:
            return None

        _hex = '%02x%02x%02x' % rgb
        main = Image.new(mode='RGB', size=(500, 500), color=rgb)
        try:
            color_name = get('https://api.alexflipnote.dev/color/' + _hex,
                             headers={
                                 "Authorization": getenv("ALEXFLIPNOTE_TOKEN")
                             }).json()['name']
        except:
            color_name = 'Unknown'
        big_font = self.get_font("Aller", 50)
        medium_font = self.get_font("Aller", 30)
        small_font = self.get_font("Aller", 20)
        draw = ImageDraw.Draw(main)
        draw.text((10, 10),
                  "#" + _hex.upper(),
                  fill=self.invert(rgb),
                  font=big_font)
        draw.text((10, 75),
                  color_name,
                  fill=self.invert(rgb),
                  font=medium_font)
        draw.text(
            (10, 115),
            f'RGB: {rgb[0]}, {rgb[1]}, {rgb[2]}\nInteger: {rgb[0]*rgb[1]*rgb[2]}\nBrightness: {brightness}',
            fill=self.invert(rgb),
            font=small_font)
        return self.buffer(main)
Esempio n. 26
0
    def generate(self, image_format='PNG', text=None, color_string=None):
        height = self.cleaned_data['height']
        width = self.cleaned_data['width']
        try:
            color = ImageColor.getcolor(color_string, 'RGB')
        except Exception as e:
            print e.message
            color = 'black'
        image = Image.new('RGB', (width, height), color=color)

        draw = ImageDraw.Draw(image)

        text = '{} x {}'.format(width, height) if text==None else text

        textwidth, textheight = draw.textsize(text)

        if textwidth < width and textheight < height:
            texttop = (height - textheight) // 2
            textleft = (width - textwidth) // 2
            draw.text((textleft, texttop), text, fill=(255, 255, 255))

        content = BytesIO()
        image.save(content, image_format)
        content.seek(0)
        return content
Esempio n. 27
0
def scaled_crop_and_pad(bbox, raw_img, scale=1.0):

    im_width, im_height = raw_img.size

    # Need to use integer only
    x_left, x_right, y_lower, y_upper = bbox.x_left, \
                                        bbox.x_right, \
                                        bbox.y_lower, \
                                        bbox.y_upper

    x_left = int((2.0 - scale) * x_left )
    x_right = int(min(scale * x_right, im_width))

    y_lower = int((2.0 - scale) * y_lower)
    y_upper = int(min(scale * y_upper, im_height))


    # Create crop with tuple defining by left, upper, right, lower (Beware -> y descending!)
    crop = raw_img.crop(box=(x_left, im_height-y_upper, x_right,im_height-y_lower))
    crop_w, crop_h = crop.size

    # rescaling the crop
    max_side = max(crop_w, crop_h)

    black_color = ImageColor.getcolor("black", crop.mode)
    background = Image.new(crop.mode, (max_side, max_side), black_color)
    background.paste(im=crop, box=(((max_side - crop_w) // 2), (max_side - crop_h) // 2))

    return background
Esempio n. 28
0
def select_ocr_image(infiles, output_file, log, context):
    """Select the image we send for OCR. May not be the same as the display
    image depending on preprocessing. This image will never be shown to the
    user."""

    image = infiles[0]
    options = context.get_options()
    pageinfo = get_pageinfo(image, context)

    with Image.open(image) as im:
        from PIL import ImageColor
        from PIL import ImageDraw

        white = ImageColor.getcolor('#ffffff', im.mode)
        # pink = ImageColor.getcolor('#ff0080', im.mode)
        draw = ImageDraw.ImageDraw(im)

        xres, yres = im.info['dpi']
        log.debug('resolution %r %r', xres, yres)

        if not options.force_ocr:
            # Do not mask text areas when forcing OCR, because we need to OCR
            # all text areas
            mask = None  # Exclude both visible and invisible text from OCR
            if options.redo_ocr:
                mask = True  # Mask visible text, but not invisible text

            for textarea in pageinfo.get_textareas(visible=mask, corrupt=None):
                # Calculate resolution based on the image size and page dimensions
                # without regard whatever resolution is in pageinfo (may differ or
                # be None)
                bbox = [float(v) for v in textarea]
                xscale, yscale = float(xres) / 72.0, float(yres) / 72.0
                pixcoords = [
                    bbox[0] * xscale,
                    im.height - bbox[3] * yscale,
                    bbox[2] * xscale,
                    im.height - bbox[1] * yscale,
                ]
                pixcoords = [int(round(c)) for c in pixcoords]
                log.debug('blanking %r', pixcoords)
                draw.rectangle(pixcoords, fill=white)
                # draw.rectangle(pixcoords, outline=pink)

        if options.mask_barcodes or options.threshold:
            pix = leptonica.Pix.frompil(im)
            if options.threshold:
                pix = pix.masked_threshold_on_background_norm()
            if options.mask_barcodes:
                barcodes = pix.locate_barcodes()
                for barcode in barcodes:
                    decoded, rect = barcode
                    log.info('masking barcode %s %r', decoded, rect)
                    draw.rectangle(rect, fill=white)
            im = pix.topil()

        del draw
        # Pillow requires integer DPI
        dpi = round(xres), round(yres)
        im.save(output_file, dpi=dpi)
Esempio n. 29
0
 def color_right(identifier, slice_no):
     identifier = str(identifier)
     slice_no = str(slice_no)
     dirpath = os.getcwd()
     out_dir = os.fsencode(dirpath + '/output/left_part')
     for file in os.listdir(out_dir):
         filename = os.fsdecode(file)
         if filename.endswith(slice_no) and filename.startswith(identifier):
             templ = Image.open(dirpath + '/output/left_part/' + filename)
             for i in range(len(labels_list)):
                 label_name = labels_list[i][0]
                 if (label_name[8:]) == slice_no + '.png':
                     area = int(label_name[5:7])
                     if colors[area] == None:
                         pass
                     else:
                         for j in range(len(labels_list[i])):
                             pixel = labels_list[i][j]
                             if type(pixel) == tuple:
                                 pixel_w = int(pixel[0])
                                 pixel_h = int(pixel[1])
                                 if pixel_w > 394:
                                     templ.putpixel((pixel_w, pixel_h),
                                                    ImageColor.getcolor(
                                                        colors[area],
                                                        'RGBA'))
             templ = templ.filter(ImageFilter.BLUR)
             templ.save(str(dirpath + '/output/' + identifier + slice_no),
                        'PNG')
             os.remove(dirpath + '/output/left_part/' + filename)
Esempio n. 30
0
def image_tint(image, tint=None):
	if tint is None:
		return image
	if image.mode not in ['RGB', 'RGBA']:
		image = image.convert('RGBA')

	tr, tg, tb = ImageColor.getrgb(tint)
	tl = ImageColor.getcolor(tint, "L")  # tint color's overall luminosity
	if not tl:
		tl = 1  # avoid division by zero
	tl = float(tl)  # compute luminosity preserving tint factors
	sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb)
						)  # per component adjustments

	# create look-up tables to map luminosity to adjusted tint
	# (using floating-point math only to compute table)
	luts = (tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
			tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
			tuple(map(lambda lb: int(lb * sb + 0.5), range(256))))
	l = ImageOps.grayscale(image)  # 8-bit luminosity version of whole image
	if Image.getmodebands(image.mode) < 4:
		merge_args = (image.mode, (l, l, l))  # for RGB verion of grayscale
	else:  # include copy of image's alpha layer
		a = Image.new("L", image.size)
		a.putdata(image.getdata(3))
		merge_args = (image.mode, (l, l, l, a))  # for RGBA verion of grayscale
		luts += tuple(range(256))  # for 1:1 mapping of copied alpha values

	return Image.merge(*merge_args).point(luts)
Esempio n. 31
0
def generate_basic(filepath, color, size, image_format=image_format):
    if filepath.endswith(".gif"):
        return generate_basic_GIF(filepath, color, size)

    color = ImageColor.getcolor(color, 'RGBA')

    with Image.open(filepath) as image_avatar:
        image_ring = Image.new('RGBA', (2048, 2048), color=color)

        midp = image_ring.width / 2
        r = midp * (1 - size)

        draw = ImageDraw.Draw(image_ring)

        draw.ellipse((midp - r, midp - r, midp + r, midp + r),
                     fill=(0, 0, 0, 0))
        image_ring.thumbnail(image_avatar.size, Image.LANCZOS)
        image_avatar.paste(image_ring, (0, 0), image_ring)

        mask = Image.new('L', (2048, 2048), 0)
        draw = ImageDraw.Draw(mask)
        draw.ellipse((0, 0) + mask.size, fill=255)
        image_avatar.putalpha(mask.resize(image_avatar.size, Image.LANCZOS))

        image_avatar.thumbnail(config.max_size, Image.LANCZOS)

        return get_image_bytes(image_avatar, image_format)
Esempio n. 32
0
def generate_image(static_dir, image_type, width, height, color):
    print(static_dir, image_type, width, height, color)

    mode = 'RGB'
    width = int(width)
    height = int(height)
    color_tuple = ImageColor.getcolor(color, mode)

    image = Image.new(mode, (width, height), color_tuple)

    image_dir = os.path.join(static_dir, 'image')
    image_name = '%sx%s_%s.%s' % (width, height, int(time.time()), image_type)
    image_path = os.path.join(image_dir, image_name)

    font = ImageFont.truetype('./font/consola.ttf', 96)
    draw = ImageDraw.Draw(image)
    # mark_content = "nicojwzhang"
    mark_content = '{width}x{height}'.format(width=width, height=height)
    for i, ch in enumerate(mark_content):
        draw.text((60*i + 10, 10), ch, font=font, fill=rndColor())

    image.save(image_path)

    print('image_path:%s' % (image_path))
    return image_path
def watermark_image(image_obj, watermark_text):
    # load a standard gray color
    gray_color = ImageColor.getcolor('gray', 'RGB')

    # load a font object
    font_path = (pathlib.Path('..') / 'fonts' / 'Arvo-Bold.ttf').resolve()
    font = ImageFont.truetype(str(font_path), 100)

    # the  watermark is a new image with the same size of the source image
    # and added alpha channel.
    watermark = Image.new("RGBA", image_obj.size)

    # Then we draw on that new image via an ImageDraw instance: we
    # add text wiht a specific font and a surrounding rectangle, both gray
    drawing = ImageDraw.ImageDraw(watermark, "RGBA")
    drawing.text((150, 350), watermark_text, fill=gray_color, font=font)
    drawing.rectangle([(100, 320), (1150, 500)], outline=gray_color)

    # Turn the watermark image to grayscale. Then we use an alpha filter
    # to make drawings a little bit transparent
    grayscale_watermark = watermark.convert("L")
    watermark.putalpha(grayscale_watermark)

    # We then paste the watermark on the source image
    image_obj.paste(watermark, None, watermark)

    return image_obj
def hex_to_color(poll_party):
    '''
    Extract hex color from polling data and convert to RGB to determine
    candidate's political affiliation.
        - Rep. has highest red value
        - Dem. has highest blue value
        - Ind. has highest green value

    '''

    # filter to colormap data
    filt = poll_party[0].find_all('div', {'class': 'heat-map'})

    r, g, b = [], [], []
    for c in range(len(filt)):

        # extract hex color
        hex_color = filt[c].attrs['style'].split(':')[1][:-1]

        # convert to rgb
        rgb = ImageColor.getcolor(hex_color, 'RGB')

        r.append(rgb[0])
        g.append(rgb[1])
        b.append(rgb[2])

    color = pd.DataFrame(zip(r, g, b), columns=['red', 'green', 'blue'])
    color['party'] = predict_party.predict_party(color)

    return list(color['party'])
Esempio n. 35
0
def color_the_mask(mask_image, color, intensity):
    assert 0 <= intensity <= 1, "intensity should be between 0 and 1"
    RGB_color = ImageColor.getcolor(color, "RGB")
    delta_color = (random.randint(5, 15), random.randint(5, 15),
                   random.randint(5, 15))
    RGB_color = (RGB_color[2], RGB_color[1], RGB_color[0])
    RGB_color_2 = tuple(RGB + delta
                        for RGB, delta in zip(RGB_color, delta_color))
    orig_shape = mask_image.shape
    bit_mask = mask_image[:, :, 3]
    # with np.printoptions(threshold=np.inf):
    #     print(bit_mask)
    mask_image = mask_image[:, :, 0:3]
    color_image = np.random.randint(low=RGB_color,
                                    high=RGB_color_2,
                                    size=(mask_image.shape))
    color_image = color_image.astype('uint8')

    mask_color = cv2.addWeighted(mask_image, 1 - intensity, color_image,
                                 intensity, 0)
    mask_color = cv2.bitwise_and(mask_color, mask_color, mask=bit_mask)
    colored_mask = np.zeros(orig_shape, dtype=np.uint8)
    colored_mask[:, :, 0:3] = mask_color
    colored_mask[:, :, 3] = bit_mask

    # cv2.namedWindow('colored_mask', cv2.WINDOW_NORMAL)
    # cv2.imshow('colored_mask', colored_mask)
    # key = cv2.waitKey()
    # if key == ord("q"):
    #     break

    return colored_mask
Esempio n. 36
0
def image_compare(path_origin,path_current,perc=100):
    '''image_compare function
    args - path_to origin screenshot,path_to screenshot for compare, type "str"
    compare percent (default = 100%, no difference between screenshot), type "int")
    '''
    original_image = Image.open(path_origin)
    width,height = origin_size = original_image.size
    device_image = Image.open(path_current)
    im_diff=original_image.copy()
    pixel_count = 0

    assert (origin_size==device_image.size),"Fatal Error!!! Images has different height or weight!!!"

    for x in xrange(width):
        for y in xrange(0,height):
            cur_pixel = original_image.getpixel((x,y))
            if cur_pixel!=device_image.getpixel((x,y)):
                pixel_count+=1
                if pixel_count==1:
                    im_diff=original_image.copy()
                im_diff.putpixel((x, y), ImageColor.getcolor('darkred', 'RGBA'))
                
    diff_percent = round(float(pixel_count)*100/(width*height),2)
    print "Image compare: {0}% difference from original screenshot".format(diff_percent)
    im_diff.save("C:/{0}_diff.png".format(test_name))
    if perc>100-diff_percent:
        return False
    else:
        return True
Esempio n. 37
0
def temp_hex_to_rgb(hex):
    print(hex)
    if hex == None:
        return (0, 0, 0)
    val = str(hex)
    val = val.replace('#', '')
    return ImageColor.getcolor(hex, "RGB")
Esempio n. 38
0
def HEX(color: str) -> str:
    """
    Convert hex code to the closest ansi escape code.

    Parameters
    ----------
    color : str
        Hex color to convert to ansi.

    Returns
    -------
    str
        color parameter as ansi escape code.
    """
    for ansicolor, hexcolor in colors.items():
        if hexcolor == color:
            return ansicolor

    r, g, b = ImageColor.getcolor(color, "RGB")

    cube = lambda x: x * x
    f = lambda hex_val, ref: cube(int(hex_val, 16) - ref)

    min_cube_d = cube(0xFFFFFF)
    nearest = '15'

    for k, h in colors.items():
        cube_d = f(h[1:3], r) + f(h[3:5], g) + f(h[5:7], b)
        if cube_d < min_cube_d:
            min_cube_d = cube_d
            nearest = k

    return nearest
Esempio n. 39
0
def select_ocr_image(infiles, output_file, log, context):
    """Select the image we send for OCR. May not be the same as the display
    image depending on preprocessing. This image will never be shown to the
    user."""

    image = infiles[0]
    options = context.get_options()
    pageinfo = get_pageinfo(image, context)

    with Image.open(image) as im:
        from PIL import ImageColor
        from PIL import ImageDraw

        white = ImageColor.getcolor('#ffffff', im.mode)
        # pink = ImageColor.getcolor('#ff0080', im.mode)
        draw = ImageDraw.ImageDraw(im)

        xres, yres = im.info['dpi']
        log.debug('resolution %r %r', xres, yres)

        if not options.force_ocr:
            # Do not mask text areas when forcing OCR, because we need to OCR
            # all text areas
            mask = None  # Exclude both visible and invisible text from OCR
            if options.redo_ocr:
                mask = True  # Mask visible text, but not invisible text

            for textarea in pageinfo.get_textareas(visible=mask, corrupt=None):
                # Calculate resolution based on the image size and page dimensions
                # without regard whatever resolution is in pageinfo (may differ or
                # be None)
                bbox = [float(v) for v in textarea]
                xscale, yscale = float(xres) / 72.0, float(yres) / 72.0
                pixcoords = [
                    bbox[0] * xscale,
                    im.height - bbox[3] * yscale,
                    bbox[2] * xscale,
                    im.height - bbox[1] * yscale,
                ]
                pixcoords = [int(round(c)) for c in pixcoords]
                log.debug('blanking %r', pixcoords)
                draw.rectangle(pixcoords, fill=white)
                # draw.rectangle(pixcoords, outline=pink)

        if options.mask_barcodes or options.threshold:
            pix = leptonica.Pix.frompil(im)
            if options.threshold:
                pix = pix.masked_threshold_on_background_norm()
            if options.mask_barcodes:
                barcodes = pix.locate_barcodes()
                for barcode in barcodes:
                    decoded, rect = barcode
                    log.info('masking barcode %s %r', decoded, rect)
                    draw.rectangle(rect, fill=white)
            im = pix.topil()

        del draw
        # Pillow requires integer DPI
        dpi = round(xres), round(yres)
        im.save(output_file, dpi=dpi)
Esempio n. 40
0
def _get_grid_colors(grid_proba, grid_pred, class_values, colors):
    """
    For the grid locations, return a list of colors, one per location
    indicating the class color.  To compute the probability color,
    we want to simulate overlaying regions from multiple trees onto
    the two-dimensional feature space using alpha to shade the colors.
    Instead, compute the color for each tile by combining the class colors
    according to their probabilities. If class 1 has probability .3 and class 2
    has probability .7, multiply the color ((R,G,B) color vector) associated
    with class 1 by .3 and the color vector associated with class 2 by .7 then
    add together. This gives a weighted color vector for each tile associated with
    the class probabilities. This gives the exact same effect as alpha channels,
    but transparent colors screwed up plotting the instance circles on top; they
    got washed out. This gives us more control and we can use alpha=1.
    """
    nclasses = len(class_values)
    class_colors = np.array(colors['classes'][nclasses])

    grid_pred_colors = class_colors[
        grid_pred]  # color for each prediction in grid

    color_map = {v: class_colors[i] for i, v in enumerate(class_values)}
    # multiply each probability vector times rgb color for each class then add
    # together to get weighted color
    rgb = np.array([ImageColor.getcolor(c, mode="RGB") for c in class_colors])
    grid_proba_colors = grid_proba @ rgb
    grid_proba_colors /= 255  # get in [0..1]
    grid_proba_colors = [Color(rgb=c).hex for c in grid_proba_colors]
    return color_map, grid_pred_colors, grid_proba_colors
Esempio n. 41
0
def HEX_to_RGB(hexcode_color):
    try:
        r, g, b = ImageColor.getcolor(hexcode_color, 'RGB')
        rgb_string = str(r) + ',' + str(g) + ',' + str(b)
        return rgb_string
    except ValueError:
        return None
Esempio n. 42
0
    def __init__(self):
        self.image = Image.new("RGBA", (500, 500))
        self.transforms = []
        self.draw = ImageDraw.Draw(self.image)
        self.color = ImageColor.getcolor("rgb(0, 0, 0)", mode="RGB")

        self.last_point = 0, 0
        self.cursor = 0, 0
Esempio n. 43
0
def gen_mem_usage_image(chunk_iter, start, end, step, height=512):
    width = (end - start - 1) / step / height+ 1
    im = Image.new('RGB', (width, height), 'WHITE')
    red = ImageColor.getcolor('RED', 'RGB')
    green = ImageColor.getcolor('GREEN', 'RGB')

    for chunk in chunk_iter:
        chunk_start = chunk.as_address()
        chunk_end = chunk_start + chunk.chunksize()
        for p in xrange(chunk_start, chunk_end, step):
            x, y = p / step / height, p / step % height
            if chunk.is_in_use():
                im.putpixel((x, y), red)
            else:
                im.putpixel((x, y), green)

    return im
Esempio n. 44
0
 def setink(self, ink):
     # compatibility
     if warnings:
         warnings.warn("'setink' is deprecated; use keyword arguments instead", DeprecationWarning, stacklevel=2)
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not isinstance(ink, numbers.Number):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
Esempio n. 45
0
 def create(self, image, geometry, options):
     thumb = super(VortaroEngine, self).create(image, geometry, options)
     if options.get('background'):
         try:
             background = Image.new('RGB', thumb.size, ImageColor.getcolor(options.get('background'), 'RGB'))
             background.paste(thumb, mask=thumb.split()[3])  # 3 is the alpha of an RGBA image.
             return background
         except Exception, e:
             return thumb
	def draw_hatch_3(img, X1, Y1, X2, Y2):
		"draws a vertical hatch pattern"
		n = 0
		for x in range(X1, X2):
			for y in range(Y1, Y2):
				if n % 4 == 0:
					img.putpixel((x, y), ImageColor.getcolor('black', 'RGB'))
			n = n + 1
		return None
	def draw_hatch_2(img, X1, Y1, X2, Y2):
		"draws a diagonal hatch pattern"
		m = 0
		for y in range(Y1, Y2):
			for x in range(X1, X2):
				if m % 7 == 0:
					img.putpixel((x, y), ImageColor.getcolor('black', 'RGB'))
				m = m + 1
		return None
	def draw_hatch_1(img, X1, Y1, X2, Y2):
		"draws a horizontal hatch pattern"
		k = 0
		for y in range(Y1, Y2):
			for x in range(X1, X2):
				if k % 5 == 0:
					img.putpixel((x, y), ImageColor.getcolor('black', 'RGB'))
			k = k + 1
		return None
Esempio n. 49
0
 def _getink(self, ink, fill=None):
     if ink is None and fill is None:
         if self.fill:
             fill = self.ink
         else:
             ink = self.ink
     else:
         if ink is not None:
             if isStringType(ink):
                 ink = ImageColor.getcolor(ink, self.mode)
             if self.palette and not isinstance(ink, numbers.Number):
                 ink = self.palette.getcolor(ink)
             ink = self.draw.draw_ink(ink, self.mode)
         if fill is not None:
             if isStringType(fill):
                 fill = ImageColor.getcolor(fill, self.mode)
             if self.palette and not isinstance(fill, numbers.Number):
                 fill = self.palette.getcolor(fill)
             fill = self.draw.draw_ink(fill, self.mode)
     return ink, fill
def returnColor():

	from PIL import ImageColor
	try:
		while True:
			print('What color would you like RGBA values for?')
			colorDesired = input("Color: ")
			print(str(ImageColor.getcolor(colorDesired, 'RGBA')))

	except ValueError:
		print('Color does not exist! Try again!')
		returnColor()
Esempio n. 51
0
 def create(self, image, geometry, options):
     ALPHA = 3  # 3 is the alpha of an RGBA image.
     thumb = super(Engine, self).create(image, geometry, options)
     background = options.get('background')
     if background:
         try:
             bgthumb = Image.new('RGB', thumb.size, ImageColor.getcolor(background, 'RGB'))
             bgthumb.paste(thumb, mask=thumb.split()[ALPHA])
             return bgthumb
         except Exception:
             logger.exception('error while creating %r thumbnail with parameter: %r, %r', image, geometry, options)
             return thumb
     return thumb
Esempio n. 52
0
def validate_color(color,default,color_type):
	"""Validate a color against known PIL values. Return the validated color if valid; otherwise return a default.

	Keyword arguments:
		color: color to test.
		default: default color string value if color is invalid.
		color_type: string name for color type, used for alerting users of defaults.
	"""
	# Use exception handling. If a given color throws an error, we may return false.
	try:
		c = ImageColor.getcolor(color,'RGB')
		return color
	except ValueError as e:
		logging.warning('"%s" is not a valid color specifier. Defaulting to "%s" for %s color.',color,default,color_type)
		return default
Esempio n. 53
0
    def create_strip(self, resolution_ratio=None):
        """
        Combines the images in taken_photos into one
        :return: the combined image
        """

        if not resolution_ratio:
            resolution_ratio = self.strip_resolution_ratio

        padding = 40
        photo_width = int(self.photo_resolution[0] * resolution_ratio)
        photo_height = int(self.photo_resolution[1] * resolution_ratio)
        width = (photo_width * 2) + (padding * 4)
        height = (photo_height * self.picture_count) + (padding * (self.picture_count + 1))

        strip = Image.new('RGB', (width, height))
        canvas = ImageDraw.Draw(strip)
        canvas.rectangle((0, 0, width, height), fill=ImageColor.getcolor('#ffffff', 'RGB'))

        for i in range(0, self.picture_count):
            image = Image.open(self.pictures_taken[i])
            image = image.convert(mode='RGB')
            image = image.resize((photo_width, photo_height), resample=Image.LANCZOS)
            strip.paste(image, box=(
                padding,
                padding + (padding * i) + (photo_height * i)
            ))
            strip.paste(image, box=(
                padding + photo_width + padding + padding,
                padding + (padding * i) + (photo_height * i)
            ))
            del image

        strip = strip.transpose(Image.FLIP_LEFT_RIGHT)
        strip = strip.filter(ImageFilter.DETAIL)
        strip = strip.filter(ImageFilter.SHARPEN)

        (handle, file_name) = mkstemp(suffix='.jpg', prefix='photoberry-strip')
        os.close(handle)
        handle = open(file_name, 'wb')
        strip.save(handle, format='jpeg', quality=95, optimize=True)
        handle.close()
        handle.close()
        del strip
        return file_name
Esempio n. 54
0
    def process_four_album_images(self, photo_bundle):
        images = map(lambda image: Image.open(image), photo_bundle.raw)
        new_size = map(lambda x: int(x * 0.5), images[0].size)
        map(lambda x: x.thumbnail(new_size, Image.ANTIALIAS), images)
        im = images[0]
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1] + self.banner.size[1]) * 1.20) * 2
        new_width = int(new_height * 1.5)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        left_x_center = int(new_width / 4)
        right_x_center = int(new_width / 2 + left_x_center)
        row_rop_start = top_border
        row_bottom_start = int(new_height / 2)

        image_width = im.size[0]
        image_height = im.size[1]
        banner_width = self.banner.size[0]
        banner_height = self.banner.size[1]

        esif_logo_left_x = left_x_center + (image_width / 2) - self.esif_logo.size[0]
        esif_logo_right_x = right_x_center + (image_width / 2) - self.esif_logo.size[0]

        new_im.paste(images[0], (left_x_center - (image_width / 2), row_rop_start))
        new_im.paste(self.banner, (left_x_center - (banner_width / 2), row_rop_start + image_height))
        new_im.paste(self.esif_logo, (esif_logo_left_x, row_rop_start + image_height), mask=self.esif_logo)

        new_im.paste(images[1], (right_x_center - (image_width / 2), row_rop_start))
        new_im.paste(self.banner, (right_x_center - (banner_width / 2), row_rop_start + image_height))
        new_im.paste(self.esif_logo, (esif_logo_right_x, row_rop_start + image_height), mask=self.esif_logo)

        new_im.paste(images[2], (left_x_center - (image_width / 2), row_bottom_start))
        new_im.paste(self.banner, (left_x_center - (banner_width / 2), row_bottom_start + image_height))
        new_im.paste(self.esif_logo, (esif_logo_left_x, row_bottom_start + image_height), mask=self.esif_logo)

        new_im.paste(images[3], (right_x_center - (image_width / 2), row_bottom_start))
        new_im.paste(self.banner, (right_x_center - (banner_width / 2), row_bottom_start + image_height))
        new_im.paste(self.esif_logo, (esif_logo_right_x, row_bottom_start + image_height), mask=self.esif_logo)

        return new_im
Esempio n. 55
0
    def process_single_image(self, photo_bundle):
        im = Image.open(photo_bundle.raw[0])
        im.thumbnail(map(lambda x: int(x * 0.5), im.size), Image.ANTIALIAS)
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1] + self.banner.size[1]) * 1.05)
        new_width = int(new_height * 1.5)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        banner_x_start = int(new_width / 2 - self.banner.size[0] / 2)
        new_im.paste(self.banner, (banner_x_start, top_border + im.size[1]))
        im_x_start = int(new_width / 2 - im.size[0] / 2)
        new_im.paste(im, (im_x_start, top_border))
        esif_logo_x_start = int(new_width - im_x_start - self.esif_logo.size[0])
        esif_logo_y_start = int(top_border + im.size[1])
        new_im.paste(self.esif_logo, (esif_logo_x_start, esif_logo_y_start), mask=self.esif_logo)
        return new_im
def generate(words):
  """
  Words are supposed to be a list of tuples [(word, weight)]
  """

  words_dict = dict(words)
  words = " ".join(words_dict.keys())

  wordcloud = WordCloud(stopwords=STOPWORDS,
                        background_color=ImageColor.getcolor('#36394c', 'RGB'),
                        width=400,
                        height=400,
                        scale=3,
                        mask=tedmask,
                        color_func=partial(color_func, dictionary=words_dict)).generate(words)

  img = wordcloud.to_image()
  pixdata = img.load()

  return img
Esempio n. 57
0
    def process_two_images(self, photo_bundle):
        im1 = Image.open(photo_bundle.raw[0])
        resize = (im1.size[0] * 0.6, im1.size[1] * 0.6)
        im1.thumbnail(resize, Image.ANTIALIAS)

        new_width = int(im1.size[0] * 10 / 9)
        new_height = int(new_width * 1.5)

        print("image", im1.format, im1.size, im1.mode)
        im2 = Image.open(photo_bundle.raw[1])
        im2.thumbnail(resize, Image.ANTIALIAS)
        print("image", im2.format, im2.size, im2.mode)

        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        new_im.paste(im1, (int(new_width / 2 - im1.size[0] / 2), top_border))
        new_im.paste(im2, (int(new_width / 2 - im2.size[0] / 2), new_height - im2.size[1] - self.banner.size[1]))
        new_im.paste(self.banner, (int(new_width / 2 - self.banner.size[0] / 2), new_height - self.banner.size[1]))
        return new_im
Esempio n. 58
0
def text_icon(request, color, text, width, height):
    """
    获取文本组合的头像
    :param request:
    :param color:
    :param text:
    :param width:
    :param height:
    :return:
    获取文本组合的头像
    by:范俊伟 at:2016-04-21
    """

    etag = request.META.get('HTTP_IF_NONE_MATCH')
    if etag:
        return http.HttpResponseNotModified()
    image_size = 150
    base = Image.new("RGBA", (image_size, image_size), color=(255, 255, 255, 0))
    color = Image.new("RGBA", (image_size, image_size), color=ImageColor.getcolor(color, "RGBA"))
    mask = Image.open(os.path.join(settings.BASE_DIR, 'util', 'circle.png'))
    base.paste(color, mask=mask)
    fnt = ImageFont.truetype(os.path.join(settings.BASE_DIR, 'util', 'SimHei.ttf'), 73)
    text_size = fnt.getsize(text)
    d = ImageDraw.Draw(base)
    x = (image_size - text_size[0]) / 2
    y = (image_size - text_size[1]) / 2
    d.text((x, y), text, font=fnt, fill=(255, 255, 255, 255))
    if width and height:
        width = int(width)
        height = int(height)
        base = base.resize((width, height), Image.ANTIALIAS)
    out = cStringIO.StringIO()
    base.save(out, format='png')
    s = out.getvalue()
    response = http.HttpResponse(s, content_type=u'image/png')
    response['Cache-Control'] = "max-age=604800, must-revalidate"
    return response
Esempio n. 59
0
import sys, os
from PIL import ImageColor, Image, ImageDraw, ImageFont

red = ImageColor.getcolor('red', 'RGBA')
black = ImageColor.getcolor('black', 'RGBA')
cornFlowerBlue = ImageColor.getcolor('CornflowerBlue', 'RGBA')


os.chdir('/Users/jmartin/code/codingChallenges/Misc/AutomateTheBoringStuffWithPython')

def processCatImage():
    catImage = Image.open('zophie.png')

    attributes = {
        'size': catImage.size,
        'mode': catImage.mode,
        'filename': catImage.filename
    }

    width, height = attributes['size']

    print(attributes)
    print(f"Width:{width} Height:{height}")

    print("Saving JPG version...")
    catImage.save("zophie.jpg")

def createNewImage():
    image = Image.new('RGBA', (100, 200), 'purple')
    image.save('purpleImage.png')
    print("Saving purple image")