Example #1
0
    def filter(self, im):
        falloff = self.falloff
        extent = self.extent

        def length(start, end):
            start_x, start_y = start
            end_x, end_y = end
            dist_x = end_x - start_x
            dist_y = end_y - start_y
            return math.sqrt((dist_x ** 2) + (dist_y ** 2))

        def light_falloff(radius, outside):
            return ((radius / outside) ** falloff) * extent

        im = im.convert('RGBA')

        w, h = im.size
        center = w / 2, h / 2
        outside = length(center, (0, 0))

        data = []
        for y in xrange(h):
            for x in xrange(w):
                radius = length(center, (x, y))
                factor = light_falloff(radius, outside)
                data.append(factor)

        alpha_im = Image.new('L', im.size)
        alpha_im.putdata(data)
        overlay_im = Image.new('L', im.size, 'black')
        return Image.composite(overlay_im, im, alpha_im)
Example #2
0
    def draw_articulations(self, count, length, radius, line_thickness, ring_thickness):
        canvas_size = radius * 2 + length
        canvas_c = (canvas_size / 2.0, canvas_size / 2.0)
        half_len = length / 2.0
        theta = 360.0 / count
        
        canvas = Image.new("RGB", [canvas_size, canvas_size], tuple(LIGHTGREY[:3]))
        mask = Image.new('L', [canvas_size, canvas_size], 0)
        mask_surf = aggdraw.Draw(mask)

        line_pen = aggdraw.Pen(255, line_thickness)
        ring_pen = aggdraw.Pen(0, ring_thickness)
        transparent_brush = aggdraw.Brush((255, 0, 0), 0)
        
        # Draw articulations
        for i in range(0, count):
            start = util.point_pos(canvas_c, radius-half_len, angle=theta*i)
            end = util.point_pos(canvas_c, radius+half_len, angle=theta*i)
            mask_surf.line((start[0], start[1], end[0], end[1]), line_pen)
        
        # Draw ring mask for articulations
        xy_1 = canvas_c[0] - radius
        xy_2 = canvas_c[0] + radius
        mask_surf.ellipse([xy_1, xy_1, xy_2, xy_2], ring_pen, transparent_brush)
        mask_surf.flush()
        
        # Apply ring mask to articulations
        canvas.putalpha(mask)
        
        return np.asarray(canvas)
def test_sanity():

    im1 = lena()
    im2 = Image.new(im1.mode, im1.size, 0)

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pos = x, y
            im2.putpixel(pos, im1.getpixel(pos))
    
    assert_image_equal(im1, im2)

    im2 = Image.new(im1.mode, im1.size, 0)
    im2.readonly = 1

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pos = x, y
            im2.putpixel(pos, im1.getpixel(pos))
    
    assert_false(im2.readonly)
    assert_image_equal(im1, im2)

    im2 = Image.new(im1.mode, im1.size, 0)

    pix1 = im1.load()
    pix2 = im2.load()

    for y in range(im1.size[1]):
        for x in range(im1.size[0]):
            pix2[x, y] = pix1[x, y]

    assert_image_equal(im1, im2)
Example #4
0
def __txt2img(fileName = "get_plot1.png", text="Hacked by Wirusiux", pos = (10, 10), bg="#ffffff",fg="#000000",font="DejaVuLGCSans-Bold.ttf",FontSize=56):
    """
Writes some text to image file
    """

    font_dir = "/usr/share/fonts/dejavu-lgc/"
    font_size = FontSize
    fnt = ImageFont.truetype(font_dir+font, font_size)
    lineWidth = 20
    img = fileName
    #try:
    #img = Image.open(fileName, 'png')
    #except:
    #    img = fileName
    imgbg = Image.new('RGBA', img.size, "#000000") # make an entirely black image
    mask = Image.new('L',img.size,"#000000")       # make a mask that masks out all
    draw = ImageDraw.Draw(img)                     # setup to draw on the main image
    drawmask = ImageDraw.Draw(mask)                # setup to draw on the mask
    drawmask.line((0, lineWidth/2, img.size[0],lineWidth/2),
                  fill="#999999", width=10)        # draw a line on the mask to allow some bg through
    img.paste(imgbg, mask=mask)                    # put the (somewhat) transparent bg on the main
    draw.text(pos, text, font=fnt, fill=bg)      # add some text to the main
    del draw 
    #img.save(fileName, "PNG")  
    return img
def fix_generated_thumbs(file, is_verbose, fix_thumb):
    try:
        cover = Image.open(file)
    except IOError:
        return False
    try:
        dpi = cover.info["dpi"]
    except KeyError:
        dpi = (96, 96)
    if dpi == (96, 96) and fix_thumb:
        if is_verbose:
            print('* Fixing generated thumbnail "%s"...' % (file))
        pdoc_cover = Image.new("L", (cover.size[0], cover.size[1] + 45),
                               "white")
        pdoc_cover.paste(cover, (0, 0))
        pdoc_cover.save(file, dpi=[72, 72])
    elif dpi == (72, 72) and not fix_thumb:
        if is_verbose:
            print('* Reverse fix for generated thumbnail "%s"...' % (file))
        pdoc_cover = Image.new("L", (cover.size[0], cover.size[1] - 45),
                               "white")
        pdoc_cover.paste(cover, (0, 0))
        pdoc_cover.save(file, dpi=[96, 96])
    else:
        if is_verbose:
            print('* Generated thumbnail "%s" is OK. DPI: %s. Skipping...'
                  % (os.path.basename(file), dpi))
    return False
Example #6
0
    def test_store_metadata(self):
        metadata = {
            'title': 'Test title',
            'description': 'describing the image',
            'tags': ['One', 'two', 'Seven'],
            'lat': 39.94119033054447, 
            'lng': -75.1519775390625,
            'license': 'All Rights Reserved',
            'isfamily': 0,
            'date_posted': datetime.datetime(2011, 4, 12, 16, 23, 4)
        }

        ## ensure it doesnt break with format that does not
        ## support EXIF/XMP/IPTC
        filename = '/tmp/image.gif'
        Image.new("RGB", (200, 400)).save(filename)
        self.mh.store_metadata(filename, metadata)

        filename = '/tmp/image.jpg'
        Image.new("RGB", (200, 400)).save(filename)

        ## check empty metadata dictionary
        self.mh.store_metadata(filename, {})

        photo_meta = pyexiv2.ImageMetadata(filename)
        photo_meta.read()
        self.assertEquals(photo_meta.keys(), [])

        self.mh.store_metadata(filename, metadata)
Example #7
0
    def check(self, mode, c=None):
        if not c:
            c = self.color(mode)

        # check putpixel
        im = Image.new(mode, (1, 1), None)
        im.putpixel((0, 0), c)
        self.assertEqual(
            im.getpixel((0, 0)), c,
            "put/getpixel roundtrip failed for mode %s, color %s" % (mode, c))

        # Check 0
        im = Image.new(mode, (0, 0), None)
        with self.assertRaises(IndexError):
            im.putpixel((0, 0), c)
        with self.assertRaises(IndexError):
            im.getpixel((0, 0))

        # check initial color
        im = Image.new(mode, (1, 1), c)
        self.assertEqual(
            im.getpixel((0, 0)), c,
            "initial color failed for mode %s, color %s " % (mode, c))

        # Check 0
        im = Image.new(mode, (0, 0), c)
        with self.assertRaises(IndexError):
            im.getpixel((0, 0))
Example #8
0
def _gen_ch_pic(ch, font, fg_level, bg_level, fixed_height=True):
    """Generate an image drawing a given character.

    Arguments
    ---------
    ch (str)
        a character to draw.
    font (ImageFont)
        the font.
    fg_level (0..255)
        the level for foregournd color.
    bg_level (0..255)
        the level of background color
    fixed_height (bool)
        Decide if use the maxima height to draw the character.
    """
    ch_w, ch_h = font.getsize(ch)
    if fixed_height:
        _w, ch_h = font.getsize('g')     # get the max height of the font
    size = (ch_w, ch_h)
    im = Image.new('1', size, color=1)
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), ch, font=font, color=0)
    del draw
    im = im.convert('L')
    mask = im.point(lambda x: x == 0 and 255)
    text = mask.point(lambda x: x == 255 and fg_level)
    im = Image.new('L', size, bg_level)
    im.paste(text, (0, 0), mask)
    return im
Example #9
0
 def save_uv(self, name):
     im = Image.new('L', (self.width, self.height))
     im.putdata([frpart(u) * 256 for u in self.umap])
     im.save('%s-u.png' % name, 'PNG')
     im = Image.new('L', (self.width, self.height))
     im.putdata([frpart(v) * 256 for v in self.vmap])
     im.save('%s-v.png' % name, 'PNG')
Example #10
0
def get_placeholder_image(width, height, name=None, fg_color=get_color('black'),
        bg_color=get_color('grey'), text=None, font=u'Verdana.ttf',
        fontsize=42, encoding=u'unic', mode='RGBA', fmt=u'PNG'):
    """Little spin-off from https://github.com/Visgean/python-placeholder
    that not saves an image and instead returns it."""
    size = (width, height)
    text = text if text else '{0}x{1}'.format(width, height)

    try:
        font = ImageFont.truetype(font, size=fontsize, encoding=encoding)
    except IOError:
        font = ImageFont.load_default()

    result_img = Image.new(mode, size, bg_color)

    text_size = font.getsize(text)
    text_img = Image.new("RGBA", size, bg_color)

    #position for the text:
    left = size[0] / 2 - text_size[0] / 2
    top = size[1] / 2 - text_size[1] / 2

    drawing = ImageDraw.Draw(text_img)
    drawing.text((left, top),
                 text,
                 font=font,
                 fill=fg_color)

    txt_img = ImageOps.fit(text_img, size, method=Image.BICUBIC, centering=(0.5, 0.5))

    result_img.paste(txt_img)
    file_obj = io.BytesIO()
    txt_img.save(file_obj, fmt)

    return file_obj.getvalue()
Example #11
0
 def facemasks(self):
     facemasks = getattr(self, "_facemasks", None)
     if facemasks:
         return facemasks
     
     white = Image.new("L", (24,24), 255)
     
     top = Image.new("L", (24,24), 0)
     left = Image.new("L", (24,24), 0)
     whole = Image.new("L", (24,24), 0)
     
     toppart = textures.Textures.transform_image_top(white)
     leftpart = textures.Textures.transform_image_side(white)
     
     # using the real PIL paste here (not alpha_over) because there is
     # no alpha channel (and it's mode "L")
     top.paste(toppart, (0,0))
     left.paste(leftpart, (0,6))
     right = left.transpose(Image.FLIP_LEFT_RIGHT)
     
     # Manually touch up 6 pixels that leave a gap, like in
     # textures._build_block()
     for x,y in [(13,23), (17,21), (21,19)]:
         right.putpixel((x,y), 255)
     for x,y in [(3,4), (7,2), (11,0)]:
         top.putpixel((x,y), 255)
 
     # special fix for chunk boundary stipple
     for x,y in [(13,11), (17,9), (21,7)]:
         right.putpixel((x,y), 0)
     
     self._facemasks = (top, left, right)
     return self._facemasks
Example #12
0
    def test_mesh(self):
        # this should be a checkerboard of halfsized hoppers in ul, lr
        im = hopper('RGBA')
        (w, h) = im.size
        transformed = im.transform(im.size, Image.MESH,
                                   [((0, 0, w//2, h//2),  # box
                                    (0, 0, 0, h,
                                     w, h, w, 0)),  # ul -> ccw around quad
                                    ((w//2, h//2, w, h),  # box
                                    (0, 0, 0, h,
                                     w, h, w, 0))],  # ul -> ccw around quad
                                   Image.BILINEAR)

        scaled = im.transform((w//2, h//2), Image.AFFINE,
                              (2, 0, 0, 0, 2, 0),
                              Image.BILINEAR)

        checker = Image.new('RGBA', im.size)
        checker.paste(scaled, (0, 0))
        checker.paste(scaled, (w//2, h//2))

        self.assert_image_equal(transformed, checker)

        # now, check to see that the extra area is (0, 0, 0, 0)
        blank = Image.new('RGBA', (w//2, h//2), (0, 0, 0, 0))

        self.assert_image_equal(blank, transformed.crop((w//2, 0, w, h//2)))
        self.assert_image_equal(blank, transformed.crop((0, h//2, w//2, h)))
Example #13
0
def image_resize_and_sharpen(image, size, preserve_aspect_ratio=False, factor=2.0, upper_limit=False):
    """
        Create a thumbnail by resizing while keeping ratio.
        A sharpen filter is applied for a better looking result.

        :param image: PIL.Image.Image()
        :param size: 2-tuple(width, height)
        :param preserve_aspect_ratio: boolean (default: False)
        :param factor: Sharpen factor (default: 2.0)
    """
    origin_mode = image.mode
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    image.thumbnail(size, Image.ANTIALIAS)
    if preserve_aspect_ratio:
        size = image.size
    sharpener = ImageEnhance.Sharpness(image)
    resized_image = sharpener.enhance(factor)
    # create a transparent image for background and paste the image on it
    if upper_limit:
        image = Image.new('RGBA', (size[0], size[1]-3), (255, 255, 255, 0)) # FIXME temporary fix for trimming the ghost border.
    else:
        image = Image.new('RGBA', size, (255, 255, 255, 0))
    image.paste(resized_image, ((size[0] - resized_image.size[0]) // 2, (size[1] - resized_image.size[1]) // 2))

    if image.mode != origin_mode:
        image = image.convert(origin_mode)
    return image
Example #14
0
 def testInflateMask(self):
   cross_image = Image.new('RGBA', (3, 3))
   white_image = Image.new('RGBA', (3, 3))
   dot_image = Image.new('RGBA', (3, 3))
   b = (0, 0, 0, 255)
   w = (255, 255, 255, 255)
   dot_image.putdata([b, b, b,
                      b, w, b,
                      b, b, b])
   cross_image.putdata([b, w, b,
                        w, w, w,
                        b, w, b])
   white_image.putdata([w, w, w,
                        w, w, w,
                        w, w, w])
   self.assertEquals(list(image_tools.InflateMask(dot_image, 1).getdata()),
                     list(cross_image.getdata()))
   self.assertEquals(list(image_tools.InflateMask(dot_image, 0).getdata()),
                     list(dot_image.getdata()))
   self.assertEquals(list(image_tools.InflateMask(dot_image, 2).getdata()),
                     list(white_image.getdata()))
   self.assertEquals(list(image_tools.InflateMask(dot_image, 3).getdata()),
                     list(white_image.getdata()))
   self.assertEquals(list(image_tools.InflateMask(self.black25, 1).getdata()),
                     list(self.black25.getdata()))
Example #15
0
def convert_to_background(background_path, target_size=(320, 1080)):
    """Converts a image to a pane background"""

    coverart = Image.open(background_path)
    coverart = coverart.convert("RGBA")

    target_width, target_height = target_size
    image_height = int(target_height * 0.80)  # 80% of the mask is visible
    orig_width, orig_height = coverart.size

    # Resize and crop coverart
    width = int(orig_width * (image_height / orig_height))
    offset = int((width - target_width) / 2)
    coverart = coverart.resize((width, image_height), resample=Image.BICUBIC)
    coverart = coverart.crop((offset, 0, target_width + offset, image_height))

    # Resize canvas of coverart by putting transparent pixels on the bottom
    coverart_bg = Image.new('RGBA', (target_width, target_height), (0, 0, 0, 0))
    coverart_bg.paste(coverart, (0, 0, target_width, image_height))

    # Apply a tint to the base image
    # tint = Image.new('RGBA', (target_width, target_height), (0, 0, 0, 255))
    # coverart = Image.blend(coverart, tint, 0.6)

    # Paste coverart on transparent image while applying a gradient mask
    background = Image.new('RGBA', (target_width, target_height), (0, 0, 0, 0))
    mask = Image.open(os.path.join(datapath.get(), "media/mask.png"))
    background.paste(coverart_bg, mask=mask)

    return background
Example #16
0
        def test_render_multiline_text(self):
            ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE)

            # Test that text() correctly connects to multiline_text()
            # and that align defaults to left
            im = Image.new(mode='RGB', size=(300, 100))
            draw = ImageDraw.Draw(im)
            draw.text((0, 0), TEST_TEXT, font=ttf)

            target = 'Tests/images/multiline_text.png'
            target_img = Image.open(target)

            self.assert_image_similar(im, target_img, .5)

            # Test align center and right
            for align, ext in {"center": "_center",
                               "right": "_right"}.items():
                im = Image.new(mode='RGB', size=(300, 100))
                draw = ImageDraw.Draw(im)
                draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align=align)

                target = 'Tests/images/multiline_text'+ext+'.png'
                target_img = Image.open(target)

                self.assert_image_similar(im, target_img, .5)
Example #17
0
def drop_shadow(image, color='black', offset=(2,3), blur=2):
    (w, h) = image.size

    original = image

    new_width = w + abs(offset[0])
    new_height = h + abs(offset[1])

    new_image = Image.new('RGBA', (new_width, new_height))

    image_x = abs(min(0, offset[0]))
    image_y = abs(min(0, offset[1]))

    shadow_x = max(0, offset[0])
    shadow_y = max(0, offset[1])
        
    new_image.paste(original, (image_x, image_y, original.size[0], original.size[1]))
    alpha = new_image.split()[3]

    highlight = Image.new('RGBA', new_image.size, color)
    highlight.putalpha(alpha)
    blurred = highlight
    for i in xrange(blur):
        blurred = blurred.filter(ImageFilter.BLUR)

    final = Image.new('RGBA', new_image.size)
    final.paste(blurred, (shadow_x, shadow_y))
    final.paste(new_image, (image_x, image_y), alpha)

    return final
Example #18
0
    def buffer_image(self, width, height, save_path=None):
        """
        Adds buffer space space to size the image properly
        """
        target_ratio = float(height) / float(width)

        if target_ratio == self._ratio:
            buffered_image = self.create_any_size(width, height)
        elif target_ratio > self._ratio:
            # uploaded image is too wide
            height = int(self._image.size[0] * target_ratio)
            width = self._image.size[0]
            buffered_image = Image.new("RGBA", (width, height), (255, 255, 255, 255))
            offset = (0, ((height - self._image.size[1]) / 2))
            buffered_image.paste(self._image, offset)
        else:
            # uploaded image is too tall
            height = self._image.size[1]
            width = int(self._image.size[1] / target_ratio)
            buffered_image = Image.new("RGBA", (width, height), (255, 255, 255, 255))
            offset = ((width - self._image.size[0]) / 2, 0)
            buffered_image.paste(self._image, offset)

        if save_path:
            self._save_image(buffered_image, save_path)

        return buffered_image
def normalize_picture(input_image_path, output_image_path, num_of_colors):
    """
        Reduces the amount of colors a picture has has.
        :param input_image_path the path input file
        :param output_image_path the output file path
        :param num_of_colors the number of colors to reduce the image to
    """
    print("Loading files...")
    input_image = Image.open(input_image_path)
    output_image = Image.new("RGB", (input_image.width, input_image.height))
    clusterMap = ClusterMap(size=int(255 / num_of_colors))
    pixel_count = input_image.width * input_image.height
    print("Analyzing image...")
    count = 0
    for color in input_image.getcolors(maxcolors=1000000):
        clusterMap.plot(list(color[1]), color[0])
        count = count + color[0]
        print_loading_bar(count, pixel_count, 20)

    clusterMap.average_colors()

    plotted_points = [cluster for cluster in clusterMap.cluster_list if len(cluster.plots) > 0]
    plotted_points = sorted(plotted_points, key=lambda x: len(x.plots), reverse=True)[:num_of_colors]
    color_list = [cluster.average_coord for cluster in plotted_points]
    count = 0
    print("Recreating image...")
    for w in range(0, output_image.width):
        for h in range(0, output_image.height):
            input_pixel_rgb = input_image.getpixel((w, h))
            color = find_nearest_coord(color_list, input_pixel_rgb)
            temp = Image.new("RGB", (1, 1), tuple(color))
            output_image.paste(temp, box=(w, h))
            count = count + 1
            print_loading_bar(count, pixel_count, 20)
    output_image.save(output_image_path)
Example #20
0
def getHorizontalAngleForText(image):
    width, height = image.size
    longest_axis = math.sqrt(width ** 2 + height ** 2)
    collage = Image.new('RGBA', (longest_axis, longest_axis), 'white')
    test_image = image.copy().convert('RGBA')
    y_to_paste = (longest_axis - test_image.size[1]) / 2
    x_to_paste = (longest_axis - test_image.size[0]) / 2
    original_paste = collage.copy()
    original_paste.paste(test_image, (x_to_paste, y_to_paste), test_image)
    previous_text_begin = getTextBeginHeight(original_paste)
    paste_image = original_paste.copy()
    angle = 0
    while angle > -360:
        current_text_begin = getTextBeginHeight(paste_image)
        if previous_text_begin > current_text_begin or current_text_begin == -1:
            break
        previous_text_begin = getTextBeginHeight(paste_image)
        angle -=5
        paste_image = original_paste.rotate(angle)
        collage = Image.new('RGBA', paste_image.size, 'white')
        collage.paste(paste_image, (0,0), paste_image)
        paste_image = collage
    if angle:
        return angle + 5
    return angle
Example #21
0
    def text(self, xy, string, font, **kwargs):
        fill = kwargs.get('fill')
        ttfont = ttfont_for(font)

        if ttfont is None:
            if self.scale_ratio == 1 and font.size == FontMap.BASE_FONTSIZE:
                self.draw.text(xy, string, fill=fill)
            else:
                size = self.draw.textsize(string)
                image = Image.new('RGBA', size)
                draw = ImageDraw.Draw(image)
                draw.text((0, 0), string, fill=fill)
                del draw

                basesize = (size[0] * self.scale_ratio,
                            size[1] * self.scale_ratio)
                text_image = image.resize(basesize, Image.ANTIALIAS)
                self.paste(text_image, xy, text_image)
        else:
            size = ttfont.getsize(string)

            # Avoid offset problem in Pillow (>= 2.2.0)
            if hasattr(ttfont, 'getoffset'):
                offset = ttfont.getoffset(string)
                size = (size[0] + offset[0], size[1] + offset[1])

            # Generate mask to support BDF(bitmap font)
            mask = Image.new('1', size)
            draw = ImageDraw.Draw(mask)
            draw.text((0, 0), string, fill='white', font=ttfont)

            # Rendering text
            filler = Image.new('RGB', size, fill)
            self.paste(filler, xy, mask)
Example #22
0
    def test_numpy_sources(self):
        table = numpy.ones((5, 6, 7, 3), dtype=numpy.float16)
        with self.assertRaisesRegex(ValueError, "should have either channels"):
            lut = ImageFilter.Color3DLUT((5, 6, 7), table)

        table = numpy.ones((7, 6, 5, 3), dtype=numpy.float16)
        lut = ImageFilter.Color3DLUT((5, 6, 7), table)
        self.assertIsInstance(lut.table, numpy.ndarray)
        self.assertEqual(lut.table.dtype, table.dtype)
        self.assertEqual(lut.table.shape, (table.size,))

        table = numpy.ones((7 * 6 * 5, 3), dtype=numpy.float16)
        lut = ImageFilter.Color3DLUT((5, 6, 7), table)
        self.assertEqual(lut.table.shape, (table.size,))

        table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16)
        lut = ImageFilter.Color3DLUT((5, 6, 7), table)
        self.assertEqual(lut.table.shape, (table.size,))

        # Check application
        Image.new('RGB', (10, 10), 0).filter(lut)

        # Check copy
        table[0] = 33
        self.assertEqual(lut.table[0], 1)

        # Check not copy
        table = numpy.ones((7 * 6 * 5 * 3), dtype=numpy.float16)
        lut = ImageFilter.Color3DLUT((5, 6, 7), table, _copy_table=False)
        table[0] = 33
        self.assertEqual(lut.table[0], 33)
Example #23
0
    def test_alpha_composite(self):
        # http://stackoverflow.com/questions/3374878
        # Arrange
        from PIL import ImageDraw

        expected_colors = sorted([
            (1122, (128, 127, 0, 255)),
            (1089, (0, 255, 0, 255)),
            (3300, (255, 0, 0, 255)),
            (1156, (170, 85, 0, 192)),
            (1122, (0, 255, 0, 128)),
            (1122, (255, 0, 0, 128)),
            (1089, (0, 255, 0, 0))])

        dst = Image.new('RGBA', size=(100, 100), color=(0, 255, 0, 255))
        draw = ImageDraw.Draw(dst)
        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))
        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))
        src = Image.new('RGBA', size=(100, 100), color=(255, 0, 0, 255))
        draw = ImageDraw.Draw(src)
        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))
        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))

        # Act
        img = Image.alpha_composite(dst, src)

        # Assert
        img_colors = sorted(img.getcolors())
        self.assertEqual(img_colors, expected_colors)
Example #24
0
    def test_mesh(self):
        # this should be a checkerboard of halfsized lenas in ul, lr
        im = lena("RGBA")
        (w, h) = im.size
        transformed = im.transform(
            im.size,
            Image.MESH,
            [
                ((0, 0, w // 2, h // 2), (0, 0, 0, h, w, h, w, 0)),  # box  # ul -> ccw around quad
                ((w // 2, h // 2, w, h), (0, 0, 0, h, w, h, w, 0)),  # box
            ],  # ul -> ccw around quad
            Image.BILINEAR,
        )

        # transformed.save('transformed.png')

        scaled = im.resize((w // 2, h // 2), Image.BILINEAR)

        checker = Image.new("RGBA", im.size)
        checker.paste(scaled, (0, 0))
        checker.paste(scaled, (w // 2, h // 2))

        self.assert_image_equal(transformed, checker)

        # now, check to see that the extra area is (0, 0, 0, 0)
        blank = Image.new("RGBA", (w // 2, h // 2), (0, 0, 0, 0))

        self.assert_image_equal(blank, transformed.crop((w // 2, 0, w, h // 2)))
        self.assert_image_equal(blank, transformed.crop((0, h // 2, w // 2, h)))
Example #25
0
    def test_ne(self):
        # Arrange
        im1 = Image.new('RGB', (25, 25), 'black')
        im2 = Image.new('RGB', (25, 25), 'white')

        # Act / Assert
        self.assertTrue(im1 != im2)
Example #26
0
    def test_render_multiline_text(self):
        ttf = self.get_font()

        # Test that text() correctly connects to multiline_text()
        # and that align defaults to left
        im = Image.new(mode='RGB', size=(300, 100))
        draw = ImageDraw.Draw(im)
        draw.text((0, 0), TEST_TEXT, font=ttf)

        target = 'Tests/images/multiline_text.png'
        target_img = Image.open(target)

        # Epsilon ~.5 fails with FreeType 2.7
        self.assert_image_similar(im, target_img, self.metrics['multiline'])

        # Test that text() can pass on additional arguments
        # to multiline_text()
        draw.text((0, 0), TEST_TEXT, fill=None, font=ttf, anchor=None,
                  spacing=4, align="left")
        draw.text((0, 0), TEST_TEXT, None, ttf, None, 4, "left")

        # Test align center and right
        for align, ext in {"center": "_center",
                           "right": "_right"}.items():
            im = Image.new(mode='RGB', size=(300, 100))
            draw = ImageDraw.Draw(im)
            draw.multiline_text((0, 0), TEST_TEXT, font=ttf, align=align)

            target = 'Tests/images/multiline_text'+ext+'.png'
            target_img = Image.open(target)

            # Epsilon ~.5 fails with FreeType 2.7
            self.assert_image_similar(im, target_img,
                                      self.metrics['multiline'])
Example #27
0
    def test_ne(self):
        # Arrange
        im1 = Image.new("RGB", (25, 25), "black")
        im2 = Image.new("RGB", (25, 25), "white")

        # Act / Assert
        self.assertTrue(im1 != im2)
Example #28
0
    def test_wrong_mode(self):
        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('L', (10, 10), 0)
            im.im.color_lut_3d('RGB', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('L', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('L', (10, 10), 0)
            im.im.color_lut_3d('L', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('RGBA', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('RGB', Image.LINEAR,
                               *self.generate_identity_table(4, 3))
Example #29
0
def add_watermarks(inputname,outputname,wartermark,color,fontsize=24,rotate=0,locate='lefttop'):
    assert(fontsize>0)
    im=Image.open(inputname)
    p = Image.new('RGB', im.size, (255,255,255))
    p.paste(im,(0, 0, im.size[0], im.size[1]), im)
    '''
    im = Image.open("C:/Users/Leo/Desktop/Pic/513174045073095280.jpg")
    im.thumbnail((45,45))
    '''
    #im.fill('white')
    # draw=ImageDraw.Draw(p)
    #字体
    font = ImageFont.truetype('C:\Windows\Fonts\STCAIYUN.TTF', fontsize) 
    txt=Image.new('RGBA', font.getsize(wartermark))
    d = ImageDraw.Draw(txt)
    d.text((0, 0), wartermark,  font=font, fill=color)
    #旋转
    w=txt.rotate(rotate,expand=1)
    
    if w.size[0]>p.size[0] or w.size[1]>p.size[1]:
        print('water mark is too large')
    if locate == 'lefttop':
        p.paste(w,(0, 0),w)
    elif locate == 'righttop':
        p.paste(w,(p.size[0]-w.size[0],0),w)
    elif locate == 'rightbottom':
        p.paste(w,(im.size[0]-w.size[0],im.size[1]-w.size[1]),w)
    elif locate == 'leftbottom':
        p.paste(w,(0, im.size[1]-w.size[1]),w)
    else:
        print('input location error!')
        return
    p.show()
    p.save(outputname,'JPEG')
 def debugCreatePartitionImage(self, savepath):
   new_image = Image.new("RGB", (self.width, self.height), "white")
   for el in  self.getPartition():
     section = img_partition[el]
     colour_img = Image.new("RGB", section.getSize(), section.getColour())
     new_image.paste(colour_img, section.getPosition())
   new_image.save(savepath)
            generating_points[index] = (generating_points[index][0],
                                        len(np_image[0]) - 1)

    generating_points_dict = {}
    temp = []
    for pt in generating_points:
        if pt not in generating_points_dict and pt[0] != len(
                np_image) and pt[1] != len(np_image[0]):
            generating_points_dict[pt] = 1
            temp.append(pt)
        generating_points = temp
    return generating_points


for i in range(0, 5):
    generating_points = run_single_iteration(generating_points)
    print("Iteration " + str(i) + " successful.")
    if i % 50 == 0:
        im = Image.new('RGB', (len(np_image), len(np_image[0])),
                       (255, 255, 255))
        draw = ImageDraw.Draw(im)
        for j in generating_points:
            im.putpixel((j[0], j[1]), (0, 0, 0))
        im.save("output_" + str(i) + ".png")

im = Image.new('RGB', (len(np_image), len(np_image[0])), (255, 255, 255))
draw = ImageDraw.Draw(im)
for j in generating_points:
    im.putpixel((j[0], j[1]), (0, 0, 0))
im.save("output_image.png")
pickle.dump(generating_points, open('generating_points', 'wb'))
Example #32
0
def img_calc_thumb(request, image, max_width, max_height=False):

	def reduce_wide(im, background, new_size):
		im.thumbnail(new_size, Image.ANTIALIAS)
		height = im.size[1]
		width = im.size[0]
		#print("asked for size: %s %s" % (new_size))
		#print("actual size: %s %s" % (width, height))
		middle = int(width / 2)
		delta = int(max_width / 2)
		x_min = middle - delta
		x_max = middle + delta
		#print("%s %s %s %s") % (x_min, 0, x_max, thumb_height)
		crop = im.crop((x_min, 0, x_max, height)) # left, upper, right, lower)-tuple
		crop.load()
		background.paste(crop, (0, 0))
		print("%s : %s" % ((x_min, 0, x_max, height), (background.size[0], background.size[1])))
		return background

	def reduce_tall(im, background, new_size):
		im.thumbnail(new_size, Image.ANTIALIAS)
		height = im.size[1]
		width = im.size[0]
		#print("asked for size: %s %s" % (new_size))
		#print("actual size: %s %s" % (width, height))
		middle = int(height / 2)
		delta = int(max_height / 2)
		y_min = middle - delta
		y_max = middle + delta # + (max_height - (delta * 2))  # last + is adjustment for making exactly size
		#print("%s %s %s %s") % (0, y_min, width, y_max)
		#crop = im.crop((0, y_min, width, y_max))
		crop = im.crop((0, y_min, width, y_max)) # left, upper, right, lower)-tuple
		crop.load()
		background.paste(crop, (0, 0))
		print("%s : %s" % ((0, y_min, width, y_max), (background.size[0], background.size[1])))
		return background

	# open large version of image
	filename_large = '%s%s' % (settings.MEDIA_ROOT, image.large)
	try:
		im = Image.open(filename_large)
	except:
		messages.error(request, 'Could not find a large version of image')
		return False

	# determine thumbnail filename
	filename_thumb = image.original if (image.original is not None) else image.large
	filename_thumb = 'thumb_%s.%s' % (filename_thumb, "jpg")

	# create a background
	if max_height:
		background = Image.new('RGB', (max_width, max_height), (255, 255, 255))

	# find width and height of large image
	width = im.size[0]
	height = im.size[1]
	#print((width, height))

	# determine if image is tall or wide
	if not max_height:
		# don't care about height
		new_height = int((width / max_width) * height)
		im.thumbnail((max_width, new_height), Image.ANTIALIAS)

	else:
		if width >= (height * (max_width / float(max_height))):
			# image is too wide
			new_height = max_height
			new_width = int((height / max_height) * width)
			im = reduce_wide(im, background, (new_width, new_height))
		else:
			#image is too tall
			new_width = max_width
			new_height = int((width / max_width) * height)
			im = reduce_tall(im, background, (new_width, new_height))

	# paste reduced image onto background
	thumb_path = '%s%s' % (settings.MEDIA_ROOT, filename_thumb)
	rgb_im = im.convert('RGB')
	rgb_im.save(thumb_path, "jpeg", quality=85)
	messages.success(request, 'Thumbnail was recalculated')
	image.thumbnail = filename_thumb
	image.save()
from PIL import Image, ImageDraw

def is_prime(a):
    r = False
    for i in range(2, a//2):
        if a%i==0: r = True
    return r

img = Image.new('RGB', (100, 100))
imgDraw = ImageDraw.Draw(img)
pix = img.load()

for x in range(img.size[0]):
    for y in range(img.size[1]):
        if not is_prime(x^y):
            imgDraw.point((x, y), (0, 0, 255))

img.save('xor.png')
Example #34
0
from PIL import Image

pname = "C:/Users/Ben/Dropbox/Coding/App Coding/D&D App Design Stuff/DesignSupportingImages/Scroll 2"
fname = "C:/Users/Ben/Dropbox/Coding/Python Coding/ImageOutliner/For Ben/Originals/swoopytoinvert"
fextension = ".png"
fdest = fname.replace("Originals", "Edited") + "Inverted.png"
picture = Image.open(fname + fextension)
pdest = pname + "WhitedOut.png"
mirror = Image.new('RGB', (picture.width, picture.height))
xtot = picture.width-1
ytot = picture.height-1
for x in range(picture.width):
    for y in range(picture.height):
        mirror.putpixel((x, ytot-y), picture.getpixel((x,y)))

mirror.save(fdest, 'PNG')
Example #35
0
 def save(self, image_name):
     flat_canvas = list(chain.from_iterable(self.canvas))
     image = Image.new("RGB", (self.dimensions, self.dimensions), (0, 0, 0))
     image.putdata(flat_canvas)
     image.save(image_name, "JPEG")
     image.close()
Example #36
0
 def rt_text(value):
     im = Image.new("RGB", (32, 32))
     info = PngImagePlugin.PngInfo()
     info.add_text("Text", value)
     im = roundtrip(im, pnginfo=info)
     self.assertEqual(im.info, {"Text": value})
Example #37
0
#e_parsed=json.loads(e.json())
# Load default font.
font = ImageFont.load_default()

aval = 36.85
bval = 19.25
cval = 40.95
dval = 49.40
eval = 25.18
fval = 40.20

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = 128
height = 64
image = Image.new('1', (width, height))

# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0

RST = 25
CS = 8		
DC = 24

USER_I2C = 0

if  USER_I2C == 1:
Example #38
0
def create_validate_code(size=(120, 30),
                         chars=init_chars,
                         img_type="GIF",
                         mode="RGB",
                         bg_color=(255, 255, 255),
                         fg_color=(0, 0, 255),
                         font_size=18,
                         font_type="Monaco.ttf",
                         length=4,
                         draw_lines=True,
                         n_line=(1, 2),
                         draw_points=True,
                         point_chance=2):
    """
    @todo: 生成验证码图片
    @param size: 图片的大小,格式(宽,高),默认为(120, 30)
    @param chars: 允许的字符集合,格式字符串
    @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
    @param mode: 图片模式,默认为RGB
    @param bg_color: 背景颜色,默认为白色
    @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
    @param font_size: 验证码字体大小
    @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
    @param length: 验证码字符个数
    @param draw_lines: 是否划干扰线
    @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
    @param draw_points: 是否画干扰点
    @param point_chance: 干扰点出现的概率,大小范围[0, 100]
    @return: [0]: PIL Image实例
    @return: [1]: 验证码图片中的字符串
    """

    width, height = size  # 宽高
    # 创建图形
    img = Image.new(mode, size, bg_color)
    draw = ImageDraw.Draw(img)  # 创建画笔

    def get_chars():
        """生成给定长度的字符串,返回列表格式"""
        return random.sample(chars, length)

    def create_lines():
        """绘制干扰线"""
        line_num = random.randint(*n_line)  # 干扰线条数

        for i in range(line_num):
            # 起始点
            begin = (random.randint(0, size[0]), random.randint(0, size[1]))
            # 结束点
            end = (random.randint(0, size[0]), random.randint(0, size[1]))
            draw.line([begin, end], fill=(0, 0, 0))

    def create_points():
        """绘制干扰点"""
        chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]

        for w in range(width):
            for h in range(height):
                tmp = random.randint(0, 100)
                if tmp > 100 - chance:
                    draw.point((w, h), fill=(0, 0, 0))

    def create_strs():
        """绘制验证码字符"""
        c_chars = get_chars()
        strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开

        font = ImageFont.truetype(font_type, font_size)
        font_width, font_height = font.getsize(strs)

        draw.text(((width - font_width) / 3, (height - font_height) / 3),
                  strs, font=font, fill=fg_color)

        return ''.join(c_chars)

    if draw_lines:
        create_lines()
    if draw_points:
        create_points()
    strs = create_strs()

    # 图形扭曲参数
    params = [1 - float(random.randint(1, 2)) / 100,
              0,
              0,
              0,
              1 - float(random.randint(1, 10)) / 100,
              float(random.randint(1, 2)) / 500,
              0.001,
              float(random.randint(1, 2)) / 500
              ]
    img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)

    return img, strs
Example #39
0
def test_keras_generator_from_disk():

    batch_size = random.randint(1, 50)
    width = 80
    height = 80

    tmpdir = tempfile.mkdtemp()
    tmps = []

    for i in range(10):
        tmps.append(tempfile.NamedTemporaryFile(dir=tmpdir, suffix='.JPEG'))

        bytestream = io.BytesIO()

        im = Image.new('RGB', (width, height))
        im.save(bytestream, 'JPEG')

        tmps[i].file.write(bytestream.getvalue())
        tmps[i].flush()

    p = Augmentor.Pipeline(tmpdir)
    assert len(p.augmentor_images) == len(tmps)

    p.rotate(probability=0.5, max_left_rotation=5, max_right_rotation=5)
    p.flip_left_right(probability=0.333)
    p.flip_top_bottom(probability=0.5)

    g = p.keras_generator(batch_size=batch_size,
                          image_data_format="channels_last")

    X, y = next(g)

    assert len(X) == batch_size
    assert len(X) == batch_size
    assert len(X) == len(y)

    assert np.shape(X) == (batch_size, width, height, 3)

    # Call next() more than the total number of images in the pipeline
    for i in range(20):
        X, y = next(g)
        assert len(X) == batch_size
        assert len(X) == batch_size
        assert len(X) == len(y)
        assert np.shape(X) == (batch_size, width, height, 3)

    g2 = p.keras_generator(batch_size=batch_size,
                           image_data_format="channels_first")

    X2, y2 = next(g2)

    assert len(X2) == batch_size
    assert len(X2) == batch_size
    assert len(X2) == len(y2)

    assert np.shape(X2) == (batch_size, 3, width, height)

    # Close all temporary files which will also delete them automatically
    for i in range(len(tmps)):
        tmps[i].close()

    # Finally remove the directory (and everything in it) as mkdtemp does
    # not delete itself after closing automatically
    shutil.rmtree(tmpdir)
Example #40
0
logging.basicConfig(level=logging.DEBUG)

try:

    logging.info("epd2in7 Demo")
    epd = epd2in7.EPD()
    '''2Gray(Black and white) display'''
    logging.info("init and Clear")
    epd.init()
    epd.Clear(0xFF)
    font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)
    font18 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 18)
    font35 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 35)
    # Drawing on the Horizontal image
    logging.info("1.Drawing on the Horizontal image...")
    Himage = Image.new('1', (epd.height, epd.width),
                       255)  # 255: clear the frame
    draw = ImageDraw.Draw(Himage)
    draw.text((10, 0), 'hello world', font=font24, fill=0)
    draw.text((150, 0), u'微雪电子', font=font24, fill=0)
    draw.line((20, 50, 70, 100), fill=0)
    draw.line((70, 50, 20, 100), fill=0)
    draw.rectangle((20, 50, 70, 100), outline=0)
    draw.line((165, 50, 165, 100), fill=0)
    draw.line((140, 75, 190, 75), fill=0)
    draw.arc((140, 50, 190, 100), 0, 360, fill=0)
    draw.rectangle((80, 50, 130, 100), fill=0)
    draw.chord((200, 50, 250, 100), 0, 360, fill=0)
    epd.display(epd.getbuffer(Himage))
    time.sleep(2)

    # Drawing on the Vertical image
Example #41
0
def sim_density_search(choices,rot_ret,queueSize,cur_results_dir):
	most_sim = []   # format: [(1.0 - density, (sx, sy))] for each choice

	size = rot_ret.template.size

	nIterations = 0
	for c in choices:
		cx,cy = c.size()
		nIterations += (cx-size+1) * (cy-size+1)

	print nIterations
	global_counter = 0
	for c_index, c in enumerate(choices):
		slice_easel_choice_path = os.path.join(cur_results_dir, 'slot%d' % c_index)
		if not os.path.exists(slice_easel_choice_path):
			os.makedirs(slice_easel_choice_path)

		all_sim_choice = []	# format: [(1.0 - density, (sx, sy))]
		most_sim.append([])
		#density_data.append([])
		cx,cy = c.size()
		print('Easel %d: %d total locations' % (c_index, (cx-size+1) * (cy-size+1)))
		#print('Slot %d:\nc.size(): %s\nc.im.size: %s\n' % (c_index, str(c.size()), str(c.im.size)))
		#assert(c.size() == c.im.size)
		counter = 0
		#print cx,cy
		for sx in range(cx-size+1):
			for sy in range(cy-size+1):
				density_delta = rot_ret.ringwiseDensityDelta(c.pix[sx:sx+size,sy:sy+size])
				res = 1.0 - density_delta

				all_sim_choice.append((res,(sx,sy)))

				if counter < queueSize:
					hq.heappush(most_sim[c_index],(res,(sx,sy)))
				else:
					hq.heappushpop(most_sim[c_index],(res,(sx,sy)))

				if global_counter % 5000 == 0:
					print(str(round(100*(float(global_counter)/nIterations),2)) + r'% done')

				#print(str(counter) + ': ' + str(most_sim['sp']))

				counter += 1
				global_counter += 1

		all_sim_choice.sort(reverse=True)
		most_sim[c_index] = sorted(most_sim[c_index],reverse=True)
		deltas, locs = tuple(zip(*most_sim[c_index]))

		# need to flip axes to make points
		point_locs = [(y,x) for (x,y) in locs]

		cutoff = 0.5 * (all_sim_choice[0][0] + all_sim_choice[-1][0])
		cutoff_index = queueSize - 1
		while all_sim_choice[cutoff_index][0] > cutoff and cutoff_index < counter:
			cutoff_index += 1

		cutoff_index += 1

		with open(os.path.join(slice_easel_choice_path, 'all_deltas.csv'), 'wb') as deltas_file:
			wr = csv.writer(deltas_file,delimiter=',')
			wr.writerows(all_sim_choice[:cutoff_index])

		# format: (cutoff, color)
		# cutoffs refer to fraction of distance between worst and best deltas in queue
		heatmap_input_alt = [	(0.0 , 'violet'),
							(0.5 , 'indigo'),
							(0.8 , 'blue'),
							(0.95 , 'green'),
							(0.97 , 'yellow'),
							(0.98 , 'orange'),
							(0.99 , 'red')	]

		heatmap_input = [	(0.0 , 'violet'),
							(0.5 , 'indigo'),
							(0.8 , 'blue'),
							(0.95 , 'green'),
							(0.97 , 'yellow'),
							(0.98 , 'orange'),
							(0.99 , 'red')	]

		cutoffs, colors = tuple(zip(*heatmap_input))

		heatmap_cutoffs = [co*deltas[0] + (1-co)*deltas[-1] for co in cutoffs]
		heatmap = {	cutoff	:	color for cutoff, color in zip(heatmap_cutoffs, colors)}

		points_im = Image.new('RGB',(cy,cx),color='white')
		pointer = ImageDraw.Draw(points_im)

		end_index = 0
		for cutoff in reversed(heatmap_cutoffs[1:]):
			start_index = end_index
			while deltas[end_index] > cutoff:
				end_index += 1

			pointer.point(point_locs[start_index:end_index],fill=heatmap[cutoff])

		final_color = heatmap[heatmap_cutoffs[0]]
		pointer.point(point_locs[end_index:],fill=final_color)

		slot_im = c.im.convert('RGB')
		overlay_im = Image.blend(points_im, slot_im, alpha=0.2)

		overlay_im.save(os.path.join(slice_easel_choice_path, 'sim_deltas.png'))

	return [[tup[1] for tup in choice] for choice in most_sim]
Example #42
0
# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('C:\\WINDOWS\\Fonts\\Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')
Example #43
0
from PIL import Image
im = Image.open("./westbrook.jpg")
pixelMap = im.load()

img = Image.new(im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        temp = pixelMap[i, j]
        pixelsNew[i,
                  j] = (int(temp[0] / 2), int(temp[1] / 2), int(temp[2] / 2))
img.save("reverse.jpg")
Example #44
0
def generateUpperTile(toTileIndex, cacheRoot, collection, zoomFrom, topZoom, date, compress, blankTile):

    setupLogger()

    logger = logging.getLogger("py4j")

    zoomTo = str(zoomFrom - 1).zfill(2) # e.g. 03
    zoomFrom = str(zoomFrom).zfill(2) # e.g. 04
    topZoom = str(topZoom).zfill(2)

    toXLevels = cacheLevels(toTileIndex[0])
    toYLevels = cacheLevels(toTileIndex[1])

    fromX0Levels = cacheLevels(toTileIndex[0] * 2)
    fromX1Levels = cacheLevels((toTileIndex[0] * 2) + 1)
    fromY0Levels = cacheLevels(toTileIndex[1] * 2)
    fromY1Levels = cacheLevels((toTileIndex[1] * 2) + 1)

    blank = os.path.join(cacheRoot, collection, "g", "blanks", blankTile + ".png")

    fromX0Y0Path = buildFromPath(cacheRoot, collection, date, zoomFrom, toTileIndex, 0, 0, blankTile)
    fromX0Y1Path = buildFromPath(cacheRoot, collection, date, zoomFrom, toTileIndex, 0, 1, blankTile)
    fromX1Y0Path = buildFromPath(cacheRoot, collection, date, zoomFrom, toTileIndex, 1, 0, blankTile)
    fromX1Y1Path = buildFromPath(cacheRoot, collection, date, zoomFrom, toTileIndex, 1, 1, blankTile)

    if(fromX0Y0Path == blank and fromX1Y0Path == blank
            and fromX0Y1Path == blank and fromX1Y1Path == blank):
        logger.info("Skipping tile %s, level %s because found no non-empty parent tiles found", toTileIndex, zoomTo)

    else:
        logger.info("Processing tile %s, level %s", toTileIndex, zoomTo)
        todir = os.path.join(cacheRoot, collection, "g", date, zoomTo,
                             toXLevels[0], toXLevels[1], toXLevels[2],
                             toYLevels[0], toYLevels[1])

        if not os.path.exists(todir):
            try:
                os.umask(0) # reset umask before setting the mode in makedirs
                os.makedirs(todir, 0o755)
            except OSError as e:
                # check if error was raised because another process already created the 'todir' directory
                if e.errno == errno.EEXIST and os.path.isdir(todir):
                    pass
                else:
                    raise

        to = os.path.join(todir, toYLevels[2] + ".png")

        if blankTile == "00000000":
            toImage = Image.new("RGBA", (512,512))
        else:
            toImage = Image.new("RGB", (512,512))

        if fromX0Y0Path != blank:
            fromX0Y0Image = Image.open(fromX0Y0Path)
            toImage.paste(fromX0Y0Image, box=(0, 256))
        if fromX1Y0Path != blank:
            fromX1Y0Image = Image.open(fromX1Y0Path)
            toImage.paste(fromX1Y0Image, box=(256, 256))
        if fromX0Y1Path != blank:
            fromX0Y1Image = Image.open(fromX0Y1Path)
            toImage.paste(fromX0Y1Image, box=(0, 0))
        if fromX1Y1Path != blank:
            fromX1Y1Image = Image.open(fromX1Y1Path)
            toImage.paste(fromX1Y1Image, box=(256, 0))

        toImage = toImage.resize((256, 256), resample=Image.BICUBIC)

        # if this is the last level we need to generate, we can already convert to PNG8
        if compress and zoomTo == topZoom:
            toImage.convert('P', palette=Image.ADAPTIVE, colors=256)

        # don't try to overwrite symlinks to blanks generated by GeoServer
        # can be removed when pyramis is built in a temporary cache
        if not (os.path.islink(to) and os.path.realpath(to) == blank):
            toImage.save(to, quality=95)
            os.chmod(to, 0o644)
            toImage.close()

        # now also convert the "from" tiles to PNG8
        if compress:
            if fromX0Y0Path != blank:
                convertRGBToPNG8(fromX0Y0Image, fromX0Y0Path)
                fromX0Y0Image.close()
            if fromX1Y0Path != blank:
                convertRGBToPNG8(fromX1Y0Image, fromX1Y0Path)
                fromX1Y0Image.close()
            if fromX0Y1Path != blank:
                convertRGBToPNG8(fromX0Y1Image, fromX0Y1Path)
                fromX0Y1Image.close()
            if fromX1Y1Path != blank:
                convertRGBToPNG8(fromX1Y1Image, fromX1Y1Path)
                fromX1Y1Image.close()
Example #45
0
time4 = "13:00am"
time5 = "9:02pm"

regexpression = "^([1-9]|1[0-2])(:\d\d)?[ap]m?$"
print(re.search(regexpression, time))
print(re.search(regexpression, time2))
print(re.search(regexpression, time3))
print(re.search(regexpression, time4))
print(re.search(regexpression, time5))


# phone number (either with or without area code)

#%%
txt = "aaaaaaaaa"
x = re.search("a+", txt)
print(x)

#%%
#Pixels:
# do i need to install PIL ?
from PIL import Image
#%%
mode = 'RGBA'
size = (100, 100)
color = (0, 255, 0, 255)
ourimage = Image.new(mode, size, color)
ourimage

#%%
Example #46
0
#!/usr/bin/env python
# Generated by BigMap 2. Permalink: http://bigmap.osmz.ru/bigmap.php?xmin=68188&xmax=68218&ymin=43494&ymax=43524&zoom=17&scale=256&tiles=toner

import io, urllib2, datetime, time, re, random
from PIL import Image, ImageDraw
# ^^^^^^ install "python-pillow" package | pip install Pillow | easy_install Pillow

(zoom, xmin, ymin, xmax, ymax) = (17, 68188, 43494, 68218, 43524)
layers = ["http://{abc}.tile.stamen.com/toner/!z/!x/!y.png"]
attribution = 'Map data (c) OpenStreetMap, Tiles (c) Stamen Design'
xsize = xmax - xmin + 1
ysize = ymax - ymin + 1

resultImage = Image.new("RGBA", (xsize * 256, ysize * 256), (0, 0, 0, 0))
counter = 0
for x in range(xmin, xmax + 1):
    for y in range(ymin, ymax + 1):
        for layer in layers:
            url = layer.replace("!x", str(x)).replace("!y", str(y)).replace(
                "!z", str(zoom))
            match = re.search("{([a-z0-9]+)}", url)
            if match:
                url = url.replace(match.group(0),
                                  random.choice(match.group(1)))
            print url, "... "
            try:
                req = urllib2.Request(url,
                                      headers={'User-Agent': 'BigMap/2.0'})
                tile = urllib2.urlopen(req).read()
            except Exception, e:
                print "Error", e
Example #47
0
    def newDataFrame(self, frameNo, speed, lat, lon):
        #check to make sure the frame has moved on since last time
        if frameNo > self.lastFrameNo:

            #create sumbolic links between last frame and this frame
            for missingFrameNo in range(self.lastFrameNo + 1, frameNo):
                os.symlink(
                    self.imagesFolder + "/" +
                    "{0:06d}".format(self.lastFrameNo) + ".jpg",
                    self.imagesFolder + "/" +
                    "{0:06d}".format(missingFrameNo) + ".jpg")

            #create new image
            frame = Image.new("RGBA", (DATAFRAME_WIDTH, DATAFRAME_HEIGHT))
            frameDraw = ImageDraw.Draw(frame)

            #data
            frameDraw.text((315, 10),
                           "    Speed " + str(round(speed, 2)),
                           font=self.font)
            frameDraw.text((315, 50), " Latitude " + str(lat), font=self.font)
            frameDraw.text((315, 90), "Longitude " + str(lon), font=self.font)

            #map
            #only create map if we have a GPS fix
            if lat != 0 and lon != 0:
                #only add a new set of coords if the lat and lon have changed
                if self.lastLat != lat or self.lastLon != lon:
                    #get x & y coords
                    x, y = GpsUtils.latLongToXY(lat, lon)

                    #add x,y to list
                    self.xyPositions.append([x, y])

                    #update mins and maxs
                    if x < self.minX: self.minX = x
                    if x > self.maxX: self.maxX = x
                    if y < self.minY: self.minY = y
                    if y > self.maxY: self.maxY = y

                    #persist lat and lon
                    self.lastLat = lat
                    self.lastLon = lon

                    #calculate scale
                    diffX = self.maxX - self.minX
                    #print "diffX " + str(diffX)
                    diffY = self.maxY - self.minY
                    #print "diffY " + str(diffY)
                    if diffX > diffY:
                        if diffX != 0: self.mapScale = MAP_WIDTH / float(diffX)
                        else: self.mapScale = 1
                    else:
                        if diffY != 0:
                            self.mapScale = MAP_HEIGHT / float(diffY)
                        else:
                            self.mapScale = 1

                    #print "mapScale " + str(self.mapScale)

                    #set max scale
                    if self.mapScale > MAX_SCALE: self.mapScale = MAX_SCALE

                    #re-calculate padding
                    self.padX = int((MAP_WIDTH - (diffX * self.mapScale)) / 2)
                    self.padY = int((MAP_HEIGHT - (diffY * self.mapScale)) / 2)

                #draw lines
                #print len(self.xyPositions)
                for position in range(1, len(self.xyPositions)):
                    #print self.xyPositions[position-1]
                    #print self.xyPositions[position]
                    #draw line between previous position and this one
                    x1 = self.padX + abs(
                        (self.xyPositions[position - 1][0] * self.mapScale) -
                        (self.minX * self.mapScale))
                    y1 = self.padY + abs(
                        (self.xyPositions[position - 1][1] * self.mapScale) -
                        (self.maxY * self.mapScale))
                    x2 = self.padX + abs(
                        (self.xyPositions[position][0] * self.mapScale) -
                        (self.minX * self.mapScale))
                    y2 = self.padY + abs(
                        (self.xyPositions[position][1] * self.mapScale) -
                        (self.maxY * self.mapScale))
                    #x1 = self.padX + int((self.xyPositions[position-1][0] - self.minX) * self.mapScale)
                    #y1 = self.padY + int((self.xyPositions[position-1][1] - self.minY) * self.mapScale)
                    #x2 = self.padX + int((self.xyPositions[position][0] - self.minX) * self.mapScale)
                    #y2 = self.padY + int((self.xyPositions[position][1] - self.minY) * self.mapScale)
                    #print "coords - " + str(x1) + " " + str(y1) + " " + str(x2) + " " + str(y2)
                    frameDraw.line((x1, y1, x2, y2), fill="white", width=3)

                #draw start and end point
                if len(self.xyPositions) > 1:
                    # start
                    drawPoint(
                        frameDraw, self.padX +
                        abs((self.xyPositions[0][0] * self.mapScale) -
                            (self.minX * self.mapScale)), self.padY +
                        abs((self.xyPositions[0][1] * self.mapScale) -
                            (self.maxY * self.mapScale)), 10, "red")
                    # end
                    drawPoint(
                        frameDraw, self.padX +
                        abs((self.xyPositions[len(self.xyPositions) - 1][0] *
                             self.mapScale) - (self.minX * self.mapScale)),
                        self.padY +
                        abs((self.xyPositions[len(self.xyPositions) - 1][1] *
                             self.mapScale) - (self.maxY * self.mapScale)), 10,
                        "green")
            #save image
            frame.save(
                self.imagesFolder + "/" + "{0:06d}".format(frameNo) + ".jpg",
                "JPEG")
            #time.sleep(3)
            #update last frame
            self.lastFrameNo = frameNo
Example #48
0
rightJoy.pull = Pull.UP
 
upJoy = DigitalInOut(board.D17)
upJoy.direction = Direction.INPUT
upJoy.pull = Pull.UP
 
downJoy = DigitalInOut(board.D22)
downJoy.direction = Direction.INPUT
downJoy.pull = Pull.UP
 
pressJoy = DigitalInOut(board.D4)
pressJoy.direction = Direction.INPUT
pressJoy.pull = Pull.UP

# create image and font
image = Image.new('1', (oled.width, oled.height))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 16)

# startup screen
oled.fill(0)
draw.rectangle((0, 0, oled.width, oled.height * 2), outline=0, fill=0)
draw.text((0,0), "Starting up", font=font, fill=255)
draw.text((0,18), "Program...", font=font, fill=255)
oled.image(image)
oled.show()

# this code is deprecated. It works, but connection is intermitent.
# enable connection to OBD-II, continue trying to connect if connection isn't established
#tryAgain = True
#while tryAgain:
def create_image(data, mute, scale, cropframe, file_prefix, output_dir,
                 darkenrange, lightenrange, multiplyrange, darken, lighten,
                 multiply):
    # here we remove comments, errors and empty lines from the input
    dump = []
    for line in data:
        if (line[0] not in ['!', '#', '{']) and (len(line) > 1):
            dump.append(line.strip())

    # some outputs
    if not mute:
        for line in dump:
            print(line)
        print(len(dump))

    # for every 4 b/w images we create one RGB image
    for c in range(0, len(dump) // TILE_SIZE, 4):
        # we create our canvas here
        channels = [
            Image.new('L', (TILE_WIDTH * 8, TILE_HEIGHT * 8)),
            Image.new('L', (TILE_WIDTH * 8, TILE_HEIGHT * 8)),
            Image.new('L', (TILE_WIDTH * 8, TILE_HEIGHT * 8)),
            Image.new('L', (TILE_WIDTH * 8, TILE_HEIGHT * 8))
        ]

        for idx, channel in enumerate(channels):
            pixels = channel.load()
            for h in range(TILE_HEIGHT):
                for w in range(TILE_WIDTH):
                    tile = bytes.fromhex(dump[((c + idx) * TILE_SIZE) +
                                              (h * TILE_WIDTH) + w])
                    for i in range(8):
                        for j in range(8):
                            hi = (tile[i * 2] >> (7 - j)) & 1
                            lo = (tile[i * 2 + 1] >> (7 - j)) & 1
                            pixels[(w * 8) + j, (h * 8) + i] = COLORS[hi][lo]

        # the number of saved images depends on the parameters for enhancements
        # create list of operations
        enhancements = [(.0, 'n')]  # image with no additional operations

        # range of darken images
        if darkenrange:
            darken.extend(DEFAULT_RANGE)

        # single darken image with specified value
        for v in darken:
            enhancements.append((v / 100, 'd'))

        # range of lighten images
        if lightenrange:
            lighten.extend(DEFAULT_RANGE)

        # single lighten image with specified value
        for v in lighten:
            enhancements.append((v / 100, 'l'))

        # range of multiply images
        if multiplyrange:
            multiply.extend(DEFAULT_RANGE)

        # single multiply image with specified value
        for v in multiply:
            enhancements.append((v / 100, 'm'))

        # image creation and enhancement
        for f, m in enhancements:
            # create single image from RGB channels
            img = Image.merge('RGB', channels[1:])
            img.putalpha(255)
            img = img.convert('RGBA')

            # opacity of the b/W layer
            bwLayer = channels[0]
            bwLayer.putalpha(int(255 * f))
            bwLayer = bwLayer.convert('RGBA')

            # apply opacity layer to helper image
            helperImg = img.copy()
            helperImg.alpha_composite(bwLayer)

            if m == 'd':  # darken
                img = ImageChops.darker(img, helperImg)
            elif m == 'm':  # multiply
                img = ImageChops.multiply(img, helperImg)
            elif m == 'l':  # lighten
                img = ImageChops.lighter(img, helperImg)

            # cropping
            if cropframe:
                img = img.crop((16, 16, (18 * 8), (16 * 8)))

            # resizing
            img = img.resize((img.width * scale, img.height * scale),
                             resample=Image.NEAREST)

            # saving
            img.save(
                os.path.join(
                    output_dir,
                    f'{file_prefix} {time.strftime("%Y%m%d - %H%M%S")} {c:03d} {m} {int(100 * f)}.png'
                ))
Example #50
0
    def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5):

        line = annotation_line.split()
        image = Image.open(line[0])
        iw, ih = image.size
        h, w = input_shape
        box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])

        new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)
        scale = rand(.25, 2)
        if new_ar < 1:
            nh = int(scale*h)
            nw = int(nh*new_ar)
        else:
            nw = int(scale*w)
            nh = int(nw/new_ar)
        image = image.resize((nw,nh), Image.BICUBIC)

        # place image
        dx = int(rand(0, w-nw))
        dy = int(rand(0, h-nh))
        new_image = Image.new('RGB', (w,h), (128,128,128))
        new_image.paste(image, (dx, dy))
        image = new_image

        # flip image or not
        flip = rand()<.5
        if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)

        # distort image
        hue = rand(-hue, hue)
        sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)
        val = rand(1, val) if rand()<.5 else 1/rand(1, val)
        x = cv2.cvtColor(np.array(image,np.float32)/255, cv2.COLOR_RGB2HSV)
        x[..., 0] += hue*360
        x[..., 0][x[..., 0]>1] -= 1
        x[..., 0][x[..., 0]<0] += 1
        x[..., 1] *= sat
        x[..., 2] *= val
        x[x[:,:, 0]>360, 0] = 360
        x[:, :, 1:][x[:, :, 1:]>1] = 1
        x[x<0] = 0
        image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB)*255

        # correct boxes
        box_data = np.zeros((len(box),5))
        if len(box)>0:
            np.random.shuffle(box)
            box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
            box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
            if flip: box[:, [0,2]] = w - box[:, [2,0]]
            box[:, 0:2][box[:, 0:2]<0] = 0
            box[:, 2][box[:, 2]>w] = w
            box[:, 3][box[:, 3]>h] = h
            box_w = box[:, 2] - box[:, 0]
            box_h = box[:, 3] - box[:, 1]
            box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box
            box_data = np.zeros((len(box),5))
            box_data[:len(box)] = box
        if len(box) == 0:
            return image_data, []

        if (box_data[:,:4]>0).any():
            return image_data, box_data
        else:
            return image_data, []
    def __getitem__(self, idx):
        imgpath = os.path.join(self.img_root,
                            self.landmarks_frame.iloc[idx, 0])
        pil_image = Image.open(imgpath)

        if pil_image.mode != "RGB":
            # if input is grayscale image, convert it to 3 channel image
            if self.enhance:
                pil_image = power_transform(pil_image, 0.5)
            temp_image = Image.new('RGB', pil_image.size)
            temp_image.paste(pil_image)
            pil_image = temp_image
        image = np.array(pil_image)
        if self.gray_scale:
            image = rgb2gray(image)
            image = np.expand_dims(image, axis=2)
            image = np.concatenate((image, image, image), axis=2)
            image = image * 255.0
            # image = image.astype(np.uint8)
        
        image = image.astype("float32")
        # if not self.detect_face:
        #     center = [450//2, 450//2+0]
        #     if self.center_shift != 0:
        #         center[0] += int(np.random.uniform(-self.center_shift,
        #                                        self.center_shift))
        #         center[1] += int(np.random.uniform(-self.center_shift,
        #                                        self.center_shift))
        #     scale = 1.8
        # else:
        #     detected_faces = self.face_detector.detect_image(image)
        #     if len(detected_faces) > 0:
        #         box = detected_faces[0]
        #         left, top, right, bottom, _ = box
        #         center = [right - (right - left) / 2.0,
        #                 bottom - (bottom - top) / 2.0]
        #         center[1] = center[1] - (bottom - top) * 0.12
        #         scale = (right - left + bottom - top) / 195.0
        #     else:
        #         center = [450//2, 450//2+0]
        #         scale = 1.8
        #     if self.center_shift != 0:
        #         shift = self.center * self.center_shift / 450
        #         center[0] += int(np.random.uniform(-shift, shift))
        #         center[1] += int(np.random.uniform(-shift, shift))
        
        landmarks =  self.landmarks_frame.iloc[idx, 4:140].values.astype('float64').reshape(-1, 2)
        center = [self.landmarks_frame.iloc[idx,2],self.landmarks_frame.iloc[idx,3]]
        scale = self.landmarks_frame.iloc[idx,1]
        scale *= 1.25

        ###做随机的在线处理#############
        if self.phase == "train":
            print("I will deal with the data!")
            scale = scale * (random.uniform(1 - self.scale_factor,
                                            1 + self.scale_factor))
            r = random.uniform(-self.rot_factor, self.rot_factor) \
            if random.random() <= 0.6 else 0
            if random.random() <= 0.5 and self.flip:
                image = np.fliplr(image)
                landmarks = fliplr_joints(landmarks, width=image.shape[1], dataset='300W')
                center[0] = image.shape[1] - center[0]

        new_image, new_landmarks = cv_crop(image, landmarks, center,
                                               scale, 256, self.center_shift)

        # if landmarks != []:
        #     new_image, new_landmarks = cv_crop(image, landmarks, center,
        #                                        scale, 256, self.center_shift)
        #     tries = 0
        #     while self.center_shift != 0 and tries < 5 and (np.max(new_landmarks) > 240 or np.min(new_landmarks) < 15):
        #         center = [450//2, 450//2+0]
        #         scale += 0.05
        #         center[0] += int(np.random.uniform(-self.center_shift,
        #                                     self.center_shift))
        #         center[1] += int(np.random.uniform(-self.center_shift,
        #                                     self.center_shift))

        #         new_image, new_landmarks = cv_crop(image, landmarks,
        #                                             center, scale, 256,
        #                                             self.center_shift)
        #         tries += 1
        #     if np.max(new_landmarks) > 250 or np.min(new_landmarks) < 5:
        #         center = [450//2, 450//2+0]
        #         scale = 2.25
        #         new_image, new_landmarks = cv_crop(image, landmarks,
        #                                             center, scale, 256,
        #                                             100)
        #     print(np.min(new_landmarks), np.max(new_landmarks) )
        # assert (np.min(new_landmarks) > 0 and np.max(new_landmarks) < 256), \
        #     "Landmarks out of boundary!"

        # if  not (np.min(new_landmarks) > 0 and np.max(new_landmarks) < 256):
        #     print(np.min(new_landmarks))
        #     print(np.max(new_landmarks))
        #     print(imgpath)
        #     print("Landmarks out of boundary!")
            
        image = new_image
        landmarks = new_landmarks
        heatmap = np.zeros((self.num_lanmdkars, 64, 64))
        for i in range(self.num_lanmdkars):
            if landmarks[i][0] > 0:
                heatmap[i] = draw_gaussian(heatmap[i], landmarks[i]/4.0+1, 1)
        center = np.array(center)
        sample = {"index": idx,'image': image, 'center': center, 'scale': scale, 'heatmap': heatmap, 'landmarks': landmarks}
        if self.transform:
            sample = self.transform(sample)

        return sample
friends = itchat.get_friends(update=True)
i = 0
for friend in friends:
    img = itchat.get_head_img(userName=friend['UserName'])
    with open('./images/' + str(i) + ".jpg", "wb") as img_file:
        img_file.write(img)
        i += 1

# number of pics in one side
num_in_side = int(math.sqrt(i))
# total number of pics
total_num = num_in_side**2
# small images side length
each_side_length = int(float(1200 / num_in_side))

to_image = image.new('RGB', (1200, 1200))
x = 0
y = 0
for j in range(i):
    if total_num == i:
        break
    if j == total_num:
        break
    try:
        img = image.open('./images/' + str(j) + '.jpg')
    except IOError:
        print(IOError)
        total_num += 1
    else:
        # resize pics
        img = img.resize((each_side_length, each_side_length), image.ANTIALIAS)
import os

from PIL import Image, ImageDraw

files = os.listdir("squares")

files.sort()

files = [file for file in files if file.endswith(".png")]

composite = Image.new("RGBA",
                      (300, 300))  # <-- this represents the final image

files = files[0:9]

x = 0
y = 0

for square in files:
    if x % 3 == 0 and x != 0:  # <-- change the 3 to however many imgs per row
        x = 0
        y += 1
    sq = Image.open(f"squares/{square}")
    print(f"Opening {square}.")
    composite.paste(
        sq,
        (x * 100, y * 100))  # <-- change the 100s depending on your img size
    x += 1

composite.save("composite.png")
Example #54
0
    def genQrcode(self, code, text):

        if code is None:
            print "please input code"
            return

        self.qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=self.__size / self.__ratio,
            border=0)

        self.qr.add_data(code)
        self.qr.make(fit=True)

        # generate qrcode image
        img = self.qr.make_image()
        w, h = img.size
        mode = img.mode

        # generate output filename
        outfile = self.genFilename(code)

        # generate font object
        font = ImageFont.truetype(self.__font, self.__fontsize)

        if text:
            # convert text to unicode
            text = text.decode(self.__encoding)

            draw = ImageDraw.Draw(img)

            # calc text size
            textsize = draw.textsize(text, font)

            if self.__pos == 'bottom':
                # calc new image width and height
                newimg_height = h + textsize[1]
                newimg_width = w if w > textsize[0] else textsize[0]

                # make the qrcode center align.
                if newimg_width > w:
                    qr_x = (newimg_width - w) / 2
                else:
                    qr_x = 0
                qr_y = 0

                # make the text center align.
                if newimg_width > textsize[0]:
                    text_x = (newimg_width - textsize[0]) / 2
                else:
                    text_x = 0
                text_y = h

            elif self.__pos == 'top':
                newimg_height = h + textsize[1]
                newimg_width = w if w > textsize[0] else textsize[0]

                # make the qrcode center align.
                if newimg_width > w:
                    qr_x = (newimg_width - w) / 2
                else:
                    qr_x = 0

                qr_y = textsize[1]

                # make the text center align.
                if newimg_width > textsize[0]:
                    text_x = (newimg_width - textsize[0]) / 2
                else:
                    text_x = 0
                text_y = 0

            elif self.__pos == 'left':
                newimg_height = h if h > textsize[1] else textsize[1]
                newimg_width = w + textsize[0]

                qr_x = textsize[0]
                if newimg_height > h:
                    qr_y = (newimg_height - h) / 2
                else:
                    qr_y = 0

                text_x = 0
                if newimg_height > textsize[1]:
                    text_y = (newimg_height - textsize[1]) / 2
                else:
                    text_y = 0
            else:  # position right
                newimg_height = h if h > textsize[1] else textsize[1]
                newimg_width = w + textsize[0]

                qr_x = 0
                if newimg_height > h:
                    qr_y = (newimg_height - h) / 2
                else:
                    qr_y = 0

                text_x = w
                if newimg_height > textsize[1]:
                    text_y = (newimg_height - textsize[1]) / 2
                else:
                    text_y = 0

            # create new image
            newimg = Image.new(mode, (newimg_width, newimg_height), 255)
            newimg.paste(img, (qr_x, qr_y))

            newdraw = ImageDraw.Draw(newimg)
            newdraw.text((text_x, text_y), text, font=font, fill='black')

            newimg.save(outfile)
import os

from PIL import Image

files = [
    'siti_scatter_plot_matlab/VSG.png', 'siti_scatter_plot_matlab/SAVAM.png',
    'siti_scatter_plot_matlab/LEDOV.png',
    'siti_scatter_plot_matlab/HOLLYWOOD.png',
    'siti_scatter_plot_matlab/GAZECOM.png',
    'siti_scatter_plot_matlab/DIEM.png', 'siti_scatter_plot_matlab/DHF1K.png'
]

width = 1167
height = 875

col = 4
row = 2
result = Image.new("RGB", (width * col, height * row))

for index, file in enumerate(files):
    path = os.path.expanduser(file)
    print(index, path)
    img = Image.open(path)
    img.thumbnail((width, height), Image.ANTIALIAS)
    x = index % col * width
    y = index // col * height
    w, h = img.size
    print('pos {0},{1} size {2},{3}'.format(x, y, w, h))
    result.paste(img, (x, y, x + w, y + h))

result.save(os.path.expanduser('combine.png'))
    def __getitem__(self, idx):
        img_name = self.img_names[idx]
        pil_image = Image.open(img_name)
        if pil_image.mode != "RGB":
            # if input is grayscale image, convert it to 3 channel image
            if self.enhance:
                pil_image = power_transform(pil_image, 0.5)
            temp_image = Image.new('RGB', pil_image.size)
            temp_image.paste(pil_image)
            pil_image = temp_image
        image = np.array(pil_image)
        if self.gray_scale:
            image = rgb2gray(image)
            image = np.expand_dims(image, axis=2)
            image = np.concatenate((image, image, image), axis=2)
            image = image * 255.0
            image = image.astype(np.uint8)
        if not self.detect_face:
            center = [450//2, 450//2+0]
            if self.center_shift != 0:
                center[0] += int(np.random.uniform(-self.center_shift,
                                               self.center_shift))
                center[1] += int(np.random.uniform(-self.center_shift,
                                               self.center_shift))
            scale = 1.8
        else:
            detected_faces = self.face_detector.detect_image(image)
            if len(detected_faces) > 0:
                box = detected_faces[0]
                left, top, right, bottom, _ = box
                center = [right - (right - left) / 2.0,
                        bottom - (bottom - top) / 2.0]
                center[1] = center[1] - (bottom - top) * 0.12
                scale = (right - left + bottom - top) / 195.0
            else:
                center = [450//2, 450//2+0]
                scale = 1.8
            if self.center_shift != 0:
                shift = self.center * self.center_shift / 450
                center[0] += int(np.random.uniform(-shift, shift))
                center[1] += int(np.random.uniform(-shift, shift))
        base_name = os.path.basename(img_name)
        landmarks_base_name = base_name[:-4] + '_pts.mat'
        landmarks_name = os.path.join(self.landmarks_dir, landmarks_base_name)
        if os.path.isfile(landmarks_name):
            mat_data = sio.loadmat(landmarks_name)
            landmarks = mat_data['pts_2d']
        elif os.path.isfile(landmarks_name[:-8] + '.pts.npy'):
            landmarks = np.load(landmarks_name[:-8] + '.pts.npy')
        else:
            landmarks = []
            heatmap = []

        if landmarks != []:
            new_image, new_landmarks = cv_crop(image, landmarks, center,
                                               scale, 256, self.center_shift)
            tries = 0
            while self.center_shift != 0 and tries < 5 and (np.max(new_landmarks) > 240 or np.min(new_landmarks) < 15):
                center = [450//2, 450//2+0]
                scale += 0.05
                center[0] += int(np.random.uniform(-self.center_shift,
                                            self.center_shift))
                center[1] += int(np.random.uniform(-self.center_shift,
                                            self.center_shift))

                new_image, new_landmarks = cv_crop(image, landmarks,
                                                    center, scale, 256,
                                                    self.center_shift)
                tries += 1
            if np.max(new_landmarks) > 250 or np.min(new_landmarks) < 5:
                center = [450//2, 450//2+0]
                scale = 2.25
                new_image, new_landmarks = cv_crop(image, landmarks,
                                                    center, scale, 256,
                                                    100)
            assert (np.min(new_landmarks) > 0 and np.max(new_landmarks) < 256), \
                "Landmarks out of boundary!"
            image = new_image
            landmarks = new_landmarks
            heatmap = np.zeros((self.num_lanmdkars, 64, 64))
            for i in range(self.num_lanmdkars):
                if landmarks[i][0] > 0:
                    heatmap[i] = draw_gaussian(heatmap[i], landmarks[i]/4.0+1, 1)
        sample = {'image': image, 'heatmap': heatmap, 'landmarks': landmarks}
        if self.transform:
            sample = self.transform(sample)

        return sample
def main():
    image_names, labels, annotations = load_info()
    model_vgg, rl_model = build_model()
    test_count = test_size
    IoU_storage = []

    for image_index in range(len(image_names)):
        image_index += 10
        if not labels[image_index] == '1':
            continue
        if not test_count > 0:
            break
        test_count -= 1
        image_name = image_names[image_index]
        image = np.array(obtain_image(image_name))
        image_for_search = image
        tmp = 0

        '''Create Masks'''
        annotation = annotations[image_index]
        gt_masks = create_masks(annotation, image.shape)
        object_num = np.size(annotation[:, 0])
        size_mask = (image.shape[0], image.shape[1])
        original_shape = size_mask
        region_mask = np.ones([image.shape[0], image.shape[1]])

        '''The draw image part for each step'''
        background = Image.new('RGBA', (10000, 2000), (255, 255, 255, 255))
        draw = ImageDraw.Draw(background)

        '''The draw image part for bounding box move'''
        background2 = Image.fromarray(image)
        draw2 = ImageDraw.Draw(background2)
        color_number = 0

        '''object within the image'''
        objects = annotation[:, 0]

        '''Crop Initialization'''
        offset = (0, 0)

        '''RL Initialization'''
        # absolute status is a boolean we indicate if the agent will continue
        # searching object or not. If the first object already covers the whole
        # image, we can put it at 0 so we do not further search there
        absolute_status = True
        action = 0
        step = 0
        q_value = [[0]]

        region_image = image_for_search
        region_mask = np.ones([image.shape[0], image.shape[1]])

        while (step < step_num_test) and absolute_status:
            # box_color = (color_number, 0, 100)
            box_color = (255, 0, 0)
            # color_number = 0
            iou = 0

            '''Set History Vector'''
            # we init history vector as we are going to find another object
            history_vector = np.zeros([24])
            status = 1

            draw_sequences_test(step, action, q_value, draw, region_image, background, path_testing_folder,
                                region_mask, image_name, bool_draw_test)

            size_mask = (image.shape[0], image.shape[1])
            original_shape = size_mask
            region_mask = np.ones(size_mask)

            state = get_state(region_image, history_vector, model_vgg)

            while (status == 1) and (step < step_num_test):
                step += 1
                q_value = rl_model.predict(state.T, batch_size=1)
                # print (q_value)
                action = (np.argmax(q_value)) + 1
                box_area = ((int(offset[1] + size_mask[1]), int(offset[0] + size_mask[0])),
                            (int(offset[1]), int(offset[0])))

                if action == 6:
                    box_color = (0, 0, 255)
                    draw_sequences_test_box(draw2, background2, box_area, box_color, path_testing_folder, image_name,
                                            bool_draw_test)
                    offset = (0, 0)
                    status = 0

                    if step == 1:
                        absolute_status = False
                    if only_first_object == 1:
                        absolute_status = False

                    image_for_search = mask_image_with_mean_background(region_mask, image_for_search)
                    region_image = image_for_search


                else:
                    region_image, region_mask, offset, size_mask = agent_move_mask(action, original_shape,
                                                                                   size_mask, offset, region_image)
                    box_area = ((int(offset[1] + size_mask[1]), int(offset[0] + size_mask[0])),
                                (int(offset[1]), int(offset[0])))

                    draw_sequences_test(step, action, q_value, draw, region_image, background, path_testing_folder,
                                        region_mask, image_name, bool_draw_test)

                    draw_sequences_test_box(draw2, background2, box_area, box_color, path_testing_folder, image_name,
                                            bool_draw_test)
                    # color_number += 30
                    # box_color = (color_number, 0, 100)

                history_vector = update_history_vector(history_vector, action)
                new_state = get_state(region_image, history_vector, model_vgg)
                state = new_state

        tmp = []
        for index_o in range(object_num):
            gt_mask = gt_masks[:, :, index_o]
            happy = iou_calculator(region_mask, gt_mask)
            tmp.append(happy)

        iou_result = max(tmp)
        IoU_storage.append(iou_result)

    print(averagenum(IoU_storage))
    def display_frame(self):
        '''used to display the next frame of the clock mode (should be run at least once a second)'''

        # loads config
        PLAIN_COLOR = self.config.getboolean('CLOCK_MODE', 'PLAIN_COLOR', fallback=False)
        COLOR_ROTATION_SPEED = self.config.getfloat('CLOCK_MODE', 'COLOR_ROTATION_SPEED', fallback=0.5)
        COLOR_PAN_SPEED = self.config.getfloat('CLOCK_MODE', 'COLOR_PAN_SPEED', fallback=0.5)
        COLOR_SPACING = self.config.getfloat('CLOCK_MODE', 'COLOR_SPACING', fallback=0.05)
        HOUR_12_TIME = self.config.getboolean('CLOCK_MODE', 'HOUR_12_TIME', fallback=False)


        display_width, display_height = self.unicornhatmini.get_shape()

        # Create a new PIL image big enough to fit the text
        image = Image.new('RGBA', (display_width, display_height), 0)
        draw = ImageDraw.Draw(image)

        # gets the current time
        current_time = datetime.datetime.now()

        hour = current_time.hour
        # determines if 12 hour time is needed
        if HOUR_12_TIME:
            hour = hour % 12

        # determines characters
        hour_char_1 = math.floor(hour / 10)
        hour_char_2 = hour % 10
        min_char_1 = math.floor(current_time.minute / 10)
        min_char_2 = current_time.minute % 10

        # loads the needed images
        image_pos_1 = self.get_image_for_number(hour_char_1)
        image_pos_2 = self.get_image_for_number(hour_char_2)
        image_pos_3 = self.get_image_for_number(min_char_1)
        image_pos_4 = self.get_image_for_number(min_char_2)

        # draws digits on bitmap
        draw.bitmap((0, 1), image_pos_1)
        draw.bitmap((4, 1), image_pos_2)
        draw.bitmap((10, 1), image_pos_3)
        draw.bitmap((14, 1), image_pos_4)

        # determines if : should be shown
        if current_time.second % 2 == 0:
            draw.point([(8, 2), (8, 4)])

        x_multi = math.sin(time.time() * COLOR_ROTATION_SPEED)
        y_multi = math.cos(time.time() * COLOR_ROTATION_SPEED)

        for y in range(display_height):
            for x in range(display_width):
                pixel = image.getpixel((x, y))

                # if using plain color
                if PLAIN_COLOR:
                    self.unicornhatmini.set_pixel(x, y, pixel[0], pixel[1], pixel[2])

                # uses texture for bool input, as hue is used for color
                elif pixel[0] > 0:
                    # picks hue value
                    time_offset = time.time() * COLOR_PAN_SPEED
                    x_offset = (x - display_width/2) * x_multi
                    y_offset = (y - display_height/2) * y_multi
                    hue = (time_offset + x_offset + y_offset) * COLOR_SPACING
                    r_color, g_color, b_color = [int(c * 255) for c in hsv_to_rgb(hue, 1.0, 1.0)]
                    self.unicornhatmini.set_pixel(x, y, r_color, g_color, b_color)
                # blank pixel
                else:
                    self.unicornhatmini.set_pixel(x, y, 0, 0, 0)

        self.unicornhatmini.show()

        return self.config.getint('CLOCK_MODE', 'FPS', fallback=30)
    def GenerateBackgrounds(self) -> None:
        for i in range(160, 256, 5):
            img = Image.new('RGB', (500, 500), (i, i, i))
            img.save(os.path.join(self.bgDir, "bg_" + str(i) + ".png"))

        return None
 def parse(raw_data: bytes, width, height, colors,
           image_config) -> Tuple[ImageType, dict]:
     rooms = {}
     scale = image_config[CONF_SCALE]
     trim_left = int(image_config[CONF_TRIM][CONF_LEFT] * width / 100)
     trim_right = int(image_config[CONF_TRIM][CONF_RIGHT] * width / 100)
     trim_top = int(image_config[CONF_TRIM][CONF_TOP] * height / 100)
     trim_bottom = int(image_config[CONF_TRIM][CONF_BOTTOM] * height / 100)
     trimmed_height = height - trim_top - trim_bottom
     trimmed_width = width - trim_left - trim_right
     image = Image.new('RGBA', (trimmed_width, trimmed_height))
     if width == 0 or height == 0:
         return ImageHandler.create_empty_map_image(colors), {}
     pixels = image.load()
     for img_y in range(trimmed_height):
         for img_x in range(trimmed_width):
             pixel_type = raw_data[img_x + trim_left + width *
                                   (img_y + trim_bottom)]
             x = img_x
             y = trimmed_height - img_y - 1
             if pixel_type == ImageHandlerXiaomi.MAP_OUTSIDE:
                 pixels[x, y] = ImageHandler.__get_color__(
                     COLOR_MAP_OUTSIDE, colors)
             elif pixel_type == ImageHandlerXiaomi.MAP_WALL:
                 pixels[x, y] = ImageHandler.__get_color__(
                     COLOR_MAP_WALL, colors)
             elif pixel_type == ImageHandlerXiaomi.MAP_INSIDE:
                 pixels[x, y] = ImageHandler.__get_color__(
                     COLOR_MAP_INSIDE, colors)
             elif pixel_type == ImageHandlerXiaomi.MAP_SCAN:
                 pixels[x,
                        y] = ImageHandler.__get_color__(COLOR_SCAN, colors)
             else:
                 obstacle = pixel_type & 0x07
                 if obstacle == 0:
                     pixels[x, y] = ImageHandler.__get_color__(
                         COLOR_GREY_WALL, colors)
                 elif obstacle == 1:
                     pixels[x, y] = ImageHandler.__get_color__(
                         COLOR_MAP_WALL_V2, colors)
                 elif obstacle == 7:
                     room_number = (pixel_type & 0xFF) >> 3
                     room_x = img_x + trim_left
                     room_y = img_y + trim_bottom
                     if room_number not in rooms:
                         rooms[room_number] = (room_x, room_y, room_x,
                                               room_y)
                     else:
                         rooms[room_number] = (min(rooms[room_number][0],
                                                   room_x),
                                               min(rooms[room_number][1],
                                                   room_y),
                                               max(rooms[room_number][2],
                                                   room_x),
                                               max(rooms[room_number][3],
                                                   room_y))
                     default = ImageHandler.ROOM_COLORS[room_number >> 1]
                     pixels[x, y] = ImageHandler.__get_color__(
                         f"{COLOR_ROOM_PREFIX}{room_number}", colors,
                         default)
                 else:
                     pixels[x, y] = ImageHandler.__get_color__(
                         COLOR_UNKNOWN, colors)
     if image_config["scale"] != 1 and width != 0 and height != 0:
         image = image.resize(
             (int(trimmed_width * scale), int(trimmed_height * scale)),
             resample=Image.NEAREST)
     return image, rooms