Python PIL.ImageDraw() Examples

The following are 22 code examples of PIL.ImageDraw(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL , or try the search function .
Example #1
Source File: augmentations.py    From autoclint with Apache License 2.0 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #2
Source File: augment.py    From autogluon with Apache License 2.0 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #3
Source File: augmentations.py    From pytorch-randaugment with MIT License 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #4
Source File: text.py    From EInk-Calendar with MIT License 6 votes vote down vote up
def draw(self, draw: ImageDraw) -> None:
        super().draw(draw)
        font_w, font_h = draw.textsize(self._text, font=self._font)
        if font_h <= self.height and font_w <= self.width:
            horizontal_offset = self.abs_col
            if self._horizontal_align == Alignments.CENTER:
                horizontal_offset += (self.width - font_w) // 2
            elif self._horizontal_align == Alignments.RIGHT:
                horizontal_offset += self.width - font_w
            vertical_offset = self.abs_row
            if self._vertical_align == Alignments.CENTER:
                vertical_offset += (self.height - font_h) // 2 - 1
            elif self._vertical_align == Alignments.BOTTOM:
                vertical_offset += self.height - font_h
            draw.text((horizontal_offset, vertical_offset),
                      self.text,
                      fill=self.foreground,
                      font=self._font) 
Example #5
Source File: Fun.py    From NotSoBot with MIT License 6 votes vote down vote up
def generate_ascii(self, image):
		font = PIL.ImageFont.truetype(self.files_path('FreeMonoBold.ttf'), 15, encoding="unic")
		image_width, image_height = image.size
		aalib_screen_width= int(image_width/24.9)*10
		aalib_screen_height= int(image_height/41.39)*10
		screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height)
		im = image.convert("L").resize(screen.virtual_size)
		screen.put_image((0,0), im)
		y = 0
		how_many_rows = len(screen.render().splitlines()) 
		new_img_width, font_size = font.getsize(screen.render().splitlines()[0])
		img = PIL.Image.new("RGBA", (new_img_width, how_many_rows*15), (255,255,255))
		draw = PIL.ImageDraw.Draw(img)
		for lines in screen.render().splitlines():
			draw.text((0,y), lines, (0,0,0), font=font)
			y = y + 15
		imagefit = PIL.ImageOps.fit(img, (image_width, image_height), PIL.Image.ANTIALIAS)
		return imagefit 
Example #6
Source File: Fun.py    From NotSoBot with MIT License 6 votes vote down vote up
def do_ascii(self, text):
		try:
			i = PIL.Image.new('RGB', (2000, 1000))
			img = PIL.ImageDraw.Draw(i)
			txt = figlet_format(text, font='starwars')
			img.text((20, 20), figlet_format(text, font='starwars'), fill=(0, 255, 0))
			text_width, text_height = img.textsize(figlet_format(text, font='starwars'))
			imgs = PIL.Image.new('RGB', (text_width + 30, text_height))
			ii = PIL.ImageDraw.Draw(imgs)
			ii.text((20, 20), figlet_format(text, font='starwars'), fill=(0, 255, 0))
			text_width, text_height = ii.textsize(figlet_format(text, font='starwars'))
			final = BytesIO()
			imgs.save(final, 'png')
			final.seek(0)
			return final, txt
		except:
			return False, False 
Example #7
Source File: __init__.py    From GeoVis with MIT License 6 votes vote down vote up
def NewImage(self):
        """
this must be called before doing any rendering.
Note: this replaces any previous image drawn on so be sure to
retrieve the old image before calling it again to avoid losing work
"""
        #first mode
        mode = "RGBA"
        #then other specs
        if not self.upscaled:
            global MAPWIDTH, MAPHEIGHT
            MAPWIDTH = MAPWIDTH*2
            MAPHEIGHT = MAPHEIGHT*2
            _UpdateMapDims()
            self.upscaled = True
        width = int(MAPWIDTH)
        height = int(MAPHEIGHT)
        background = MAPBACKGROUND
        dimensions = (width, height)
        self.img = PIL.Image.new(mode, dimensions, background)
        self.drawer = PIL.ImageDraw.Draw(self.img) 
Example #8
Source File: augmentations.py    From cutmix with MIT License 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #9
Source File: augmentations.py    From cutmix with MIT License 6 votes vote down vote up
def Cutout(img, v):  # [0, 60] => percentage: [0, 0.2]
    assert 0.0 <= v <= 0.2
    if v <= 0.:
        return img

    v = v * img.size[0]

    return CutoutAbs(img, v)

    # x0 = np.random.uniform(w - v)
    # y0 = np.random.uniform(h - v)
    # xy = (x0, y0, x0 + v, y0 + v)
    # color = (127, 127, 127)
    # img = img.copy()
    # PIL.ImageDraw.Draw(img).rectangle(xy, color)
    # return img 
Example #10
Source File: augmentations.py    From fast-autoaugment with MIT License 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #11
Source File: augmentations.py    From unsupervised-data-augmentation with Apache License 2.0 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #12
Source File: augmentations.py    From unsupervised-data-augmentation with Apache License 2.0 6 votes vote down vote up
def Cutout(img, v):  # [0, 60] => percentage: [0, 0.2]
    assert 0.0 <= v <= 0.2
    if v <= 0.:
        return img

    v = v * img.size[0]

    return CutoutAbs(img, v)

    # x0 = np.random.uniform(w - v)
    # y0 = np.random.uniform(h - v)
    # xy = (x0, y0, x0 + v, y0 + v)
    # color = (127, 127, 127)
    # img = img.copy()
    # PIL.ImageDraw.Draw(img).rectangle(xy, color)
    # return img 
Example #13
Source File: autoaug.py    From PyTorch-Encoding with MIT License 6 votes vote down vote up
def CutoutAbs(img, v):  # [0, 60] => percentage: [0, 0.2]
    # assert 0 <= v <= 20
    if v < 0:
        return img
    w, h = img.size
    x0 = np.random.uniform(w)
    y0 = np.random.uniform(h)

    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = min(w, x0 + v)
    y1 = min(h, y0 + v)

    xy = (x0, y0, x1, y1)
    color = (125, 123, 114)
    # color = (0, 0, 0)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #14
Source File: augmentations.py    From autoclint with Apache License 2.0 6 votes vote down vote up
def Cutout(img, v):  # [0, 60] => percentage: [0, 0.2]
    assert 0.0 <= v <= 0.2
    if v <= 0.:
        return img

    v = v * img.size[0]

    return CutoutAbs(img, v)

    # x0 = np.random.uniform(w - v)
    # y0 = np.random.uniform(h - v)
    # xy = (x0, y0, x0 + v, y0 + v)
    # color = (127, 127, 127)
    # img = img.copy()
    # PIL.ImageDraw.Draw(img).rectangle(xy, color)
    # return img 
Example #15
Source File: __init__.py    From GeoVis with MIT License 5 votes vote down vote up
def __init__(self):
        global PIL
        import PIL, PIL.Image, PIL.ImageDraw, PIL.ImageTk, PIL.ImageFont
        self.upscaled = False
        self.sysfontfolders = dict([("windows","C:/Windows/Fonts/"),
                                    ("darwin", "/Library/Fonts/"),
                                    ("linux", "/usr/share/fonts/truetype/") ])
        self.fontfilenames = dict([("default", "TIMES.TTF"),
                                   ("times new roman","TIMES.TTF"),
                                   ("arial","ARIAL.TTF")]) 
Example #16
Source File: __init__.py    From GeoVis with MIT License 5 votes vote down vote up
def __init__(self):
        global aggdraw, PIL
        import aggdraw, PIL, PIL.Image, PIL.ImageDraw, PIL.ImageTk
        self.sysfontfolders = dict([("windows","C:/Windows/Fonts/"),
                                    ("darwin", "/Library/Fonts/"),
                                    ("linux", "/usr/share/fonts/truetype/") ])
        self.fontfilenames = dict([("default", "TIMES.TTF"),
                                   ("times new roman","TIMES.TTF"),
                                   ("arial","ARIAL.TTF")]) 
Example #17
Source File: listy.py    From GeoVis with MIT License 5 votes vote down vote up
def Show(self):
        import numpy, PIL, PIL.Image, PIL.ImageTk, PIL.ImageDraw
        import Tkinter as tk
        import colour
        win = tk.Tk()
        nparr = numpy.array(self.grid.lists)
        npmin = numpy.min(nparr)
        npmax = numpy.max(nparr)
        minmaxdiff = npmax-npmin
        colorstops = [colour.Color("red").rgb,colour.Color("yellow").rgb,colour.Color("green").rgb]
        colorstops = [list(each) for each in colorstops]
        colorgrad = Listy(*colorstops)
        colorgrad.Convert("250*value")
        colorgrad.Resize(int(minmaxdiff))
        valuerange = range(int(npmin),int(npmax))
        colordict = dict(zip(valuerange,colorgrad.lists))
        print len(valuerange),len(colorgrad.lists),len(colordict)
        print "minmax",npmin,npmax
        for ypos,horizline in enumerate(self.grid.lists):
            for xpos,value in enumerate(horizline):
                relval = value/float(npmax)
                self.grid.lists[ypos][xpos] = colorgrad.lists[int((len(colorgrad.lists)-1)*relval)]
        nparr = numpy.array(self.grid.lists,"uint8")
        print "np shape",nparr.shape
        img = PIL.Image.fromarray(nparr)
        drawer = PIL.ImageDraw.ImageDraw(img)
        size = 3
        for knowncell in self.knowncells:
            x,y = (knowncell.x,knowncell.y)
            drawer.ellipse((x-size,y-size,x+size,y+size),fill="black")
        img.save("C:/Users/BIGKIMO/Desktop/test.png")
        tkimg = PIL.ImageTk.PhotoImage(img)
        lbl = tk.Label(win, image=tkimg)
        lbl.pack()
        win.mainloop()
    #INTERNAL USE ONLY 
Example #18
Source File: randAug.py    From Tricks-of-Semi-supervisedDeepLeanring-Pytorch with MIT License 5 votes vote down vote up
def CutoutAbs(img, v, **kwarg):
    w, h = img.size
    x0 = np.random.uniform(0, w)
    y0 = np.random.uniform(0, h)
    x0 = int(max(0, x0 - v / 2.))
    y0 = int(max(0, y0 - v / 2.))
    x1 = int(min(w, x0 + v))
    y1 = int(min(h, y0 + v))
    xy = (x0, y0, x1, y1)
    # gray
    color = (127, 127, 127)
    img = img.copy()
    PIL.ImageDraw.Draw(img).rectangle(xy, color)
    return img 
Example #19
Source File: panel.py    From EInk-Calendar with MIT License 5 votes vote down vote up
def draw(self, draw: ImageDraw) -> None:
        super().draw(draw)
        for child in self._children:
            child.draw(draw) 
Example #20
Source File: widget_base.py    From EInk-Calendar with MIT License 5 votes vote down vote up
def draw(self, draw: ImageDraw) -> None:
        if self._draw_border:
            draw.rectangle(
                (self.abs_col, self.abs_row, self.abs_col + self.width - 1,
                 self.abs_row + self.height - 1),
                outline=self.foreground,
                fill=self.background) 
Example #21
Source File: event.py    From EInk-Calendar with MIT License 4 votes vote down vote up
def draw(self, draw: ImageDraw) -> None:
        super().draw(draw)
        if not self.show:
            return
        horizontal_pad = self.width // 25
        bottom_pad = self.height // 4
        draw.line((self.abs_col + horizontal_pad, self.abs_row + self.height -
                   bottom_pad, self.abs_col + self.width - horizontal_pad,
                   self.abs_row + self.height - bottom_pad),
                  fill=self.foreground)
        text_w, text_h = self.font.getsize(' ')
        # How many character's size the tab will take
        tab_width_char = 14
        polygon_pts = ((self.abs_col + horizontal_pad,
                        self.abs_row + self.height - bottom_pad),
                       (self.abs_col + horizontal_pad,
                        self.abs_row + self.height - bottom_pad - text_h),
                       (self.abs_col + horizontal_pad + text_w *
                        (tab_width_char - 1),
                        self.abs_row + self.height - bottom_pad - text_h),
                       (self.abs_col + horizontal_pad +
                        text_w * tab_width_char,
                        self.abs_row + self.height - bottom_pad))
        week_day_str = WEEK_DAYS[self.date.weekday()]
        date_str = '%s, %s' % (datetime.datetime.strftime(
            self.date, ' %b %d'), week_day_str)
        draw.polygon(polygon_pts, fill=self.foreground)
        draw.text((self.abs_col + horizontal_pad,
                   self.abs_row + self.height - bottom_pad - text_h),
                  date_str,
                  fill=self.background,
                  font=self.font)
        # We save three char's space between tab and event text
        event_max_chars = ((self.width - 2 * horizontal_pad) // text_w -
                           tab_width_char - 3)
        if len(self.event) > event_max_chars:
            self.event = self.event[:event_max_chars - 3] + '...'
        draw.text(
            (self.abs_col + text_w * (tab_width_char + 3) + horizontal_pad,
             self.abs_row + self.height - bottom_pad - text_h),
            self.event,
            fill=self.foreground,
            font=self.font) 
Example #22
Source File: create_dataset.py    From deep-fonts with Apache License 2.0 4 votes vote down vote up
def read_font(fn):
    font = PIL.ImageFont.truetype(fn, min(w0, h0))

    # We need to make sure we scale down the fonts but preserve the vertical alignment
    min_ly = float('inf')
    max_hy = float('-inf')
    max_width = 0
    imgs = []

    for char in chars:
        print '...', char
        # Draw character
        img = PIL.Image.new("L", (w0*5, h0*3), 255)
        draw = PIL.ImageDraw.Draw(img)
        draw.text((w0, h0), char, font=font)

        # Get bounding box
        diff = PIL.ImageChops.difference(img, blank)
        lx, ly, hx, hy = diff.getbbox()
        min_ly = min(min_ly, ly)
        max_hy = max(max_hy, hy)
        max_width = max(max_width, hx - lx)
        imgs.append((lx, hx, img))

    print 'crop dims:', max_hy - min_ly, max_width
    scale_factor = min(1.0 * h / (max_hy - min_ly), 1.0 * w / max_width)
    data = []

    for lx, hx, img in imgs:
        img = img.crop((lx, min_ly, hx, max_hy))

        # Resize to smaller
        new_width = (hx-lx) * scale_factor
        new_height = (max_hy - min_ly) * scale_factor
        img = img.resize((int(new_width), int(new_height)), PIL.Image.ANTIALIAS)

        # Expand to square
        img_sq = PIL.Image.new('L', (w, h), 255)
        offset_x = (w - new_width)/2
        offset_y = (h - new_height)/2
        print offset_x, offset_y
        img_sq.paste(img, (int(offset_x), int(offset_y)))

        # Convert to numpy array
        matrix = numpy.array(img_sq.getdata()).reshape((h, w))
        matrix = 255 - matrix
        data.append(matrix)

    return numpy.array(data)