def str2fnt(string,font_size,h):
    res_block=''
    n=0
    str_lst=checkMaxPages(string,1024,h,32)
    for i in range(len(str_lst)):
        x=0
        y=0
        char_list = str_lst[i]
        im = Image.new(mode='RGBA',size=(1024,1024),color=(255,255,255,0))
        ImageFont.load_default()
        draw = ImageDraw.Draw(im)
        Font = ImageFont.truetype("xhei.ttc", font_size-2)
        for char in char_list:
            char_tuple=Font.getsize(char)
            
            draw.text((x,y),char,fill=(255,255,255,255),font=Font)#CR:x>1024:y+=font_size+1
            logcat.write('id:%d,%s,%d,%d\r\n'%(i,char,x,y))
            char_width = char_tuple[0]
            char_height = font_size+1
            bindat = math_xy(char,x,y,char_width,char_height,i)
            res_block += bindat
            x += char_tuple[0]+1
            if x + char_tuple[0] >= 1024:
                y += font_size+1
                x = 0
        im.save('font00_jpn_%02d_BM_NOMIP.tex.PVRTC4.png'%i,'png')
    return res_block
Beispiel #2
0
def renderTable(j1, j2, path, wedges):
	jTot = j1 + j2
	
	#Calculate the necessary image size
	divotPosition = (2*DefaultCellWidth + 6, 2*DefaultCellHeight + 2)
	imgWidth = sum([wedge.getWidthFromDivot() for wedge in wedges]) + divotPosition[0] + 1
	imgHeight = sum([wedge.getHeightFromDivot() for wedge in wedges]) + divotPosition[1] + 1
	
	#P = palette, (width, height), white background
	#See http://effbot.org/zone/creating-palette-images.htm
	img = Image.new('P',(imgWidth,imgHeight), 255)
	draw = ImageDraw.Draw(img)
	jFont = ImageFont.load_default()
	cFont = ImageFont.load_default()
	
	#Render the big J stuff
	j1 = getCondonShortleyForm(sqrt(j1)) #Safe to pass in sqrts because j1, j1 shouldn't be negative, although we need TODO double check this
	j2 = getCondonShortleyForm(sqrt(j2))
	j1Str = "%i/%i" % (j1[1], j1[2]) if j1[2] != 1 else "%i" % j1[1]
	j2Str = "%i/%i" % (j2[1], j2[2]) if j2[2] != 1 else "%i" % j2[1]
	draw.text((0,0), "%s X %s" % (j1Str, j2Str), font=jFont)
	
	#Positions specified as (x, y), y runs downward
	for wedge in wedges:
		divotPosition = wedge.render(draw, cFont, divotPosition)
	
	#Save file
	try:
		img.save(path)
	except(KeyError):
		print("Couldn't save due to invalid file path.")
 def createNewImage(self):
     """Create a new image with current timestamp as text marker"""
     current_timestamp = time.time()
     filename = repr(current_timestamp) + ".png"
     ImageFont.load_default()
     image = Image.new("RGB", (125, 25))
     draw = ImageDraw.Draw(image)
     draw.text((10, 10), repr(current_timestamp), (255, 255, 255))
     # TODO(aarcos): Store in /tmp
     image.save(filename, "PNG")
     return filename
Beispiel #4
0
    def getfont(self):
        if not self.font:
            # FIXME: should add a font repository
            from PIL import ImageFont

            self.font = ImageFont.load_default()
        return self.font
Beispiel #5
0
def write_tour_to_img(coords,tour,title,img_file):
    padding=20
    # shift all coords in a bit
    coords=[(x+padding,y+padding) for (x,y) in coords]
    maxx,maxy=0,0
    for x,y in coords:
        maxx=max(x,maxx)
        maxy=max(y,maxy)
    maxx+=padding
    maxy+=padding
    img=Image.new("RGB",(int(maxx),int(maxy)),color=(255,255,255))
    
    font=ImageFont.load_default()
    d=ImageDraw.Draw(img);
    num_cities=len(tour)
    for i in range(num_cities):
        j=(i+1)%num_cities
        city_i=tour[i]
        city_j=tour[j]
        x1,y1=coords[city_i]
        x2,y2=coords[city_j]
        d.line((int(x1),int(y1),int(x2),int(y2)),fill=(0,0,0))
        d.text((int(x1)+7,int(y1)-5),str(i),font=font,fill=(32,32,32))
    
    
    for x,y in coords:
        x,y=int(x),int(y)
        d.ellipse((x-5,y-5,x+5,y+5),outline=(0,0,0),fill=(196,196,196))
    
    d.text((1,1),title,font=font,fill=(0,0,0))
    
    del d
    img.save(img_file, "PNG")
Beispiel #6
0
    def draw_word_wrap(self,img, text, xpos=0, ypos=0, max_width=95):
        from PIL import Image,ImageDraw,ImageFont
        font=ImageFont.load_default()
        font=ImageFont.truetype("mw8_5.ttf", 8)

        # textwrapping adapted from http://jesselegg.com/archives/2009/09/5/simple-word-wrap-algorithm-pythons-pil/

        draw = ImageDraw.Draw(img)
        text_size_x, text_size_y = draw.textsize(text, font=font)
        remaining = max_width
        space_width, space_height = draw.textsize(' ', font=font)
        # use this list as a stack, push/popping each line
        output_text = []
        # split on whitespace...
        for word in text.split(None):
            word_width, word_height = draw.textsize(word, font=font)
            if word_width + space_width > remaining:
                output_text.append(word)
                remaining = max_width - word_width
            else:
                if not output_text:
                    output_text.append(word)
                else:
                    output = output_text.pop()
                    output += ' %s' % word
                    output_text.append(output)
            remaining = remaining - (word_width + space_width)
        for text in output_text:
            draw.text((xpos, ypos), text, font=font, fill='white')
            ypos += text_size_y+1
Beispiel #7
0
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)):
    """Draws text over the image. Requires PIL.

    Args:
        img: The image to use.
        text: The text string to overlay.
        position: The text (x, y) position. (Default value = (10, 10))
        font: The ttf or open type font to use. (Default value = 'FreeSans.ttf')
        font_size: The text font size. (Default value = 12)
        color: The (r, g, b) values for text color. (Default value = (0, 0, 0))

    Returns: Image overlayed with text.
    """
    _check_pil()

    font_files = _find_font_file(font)
    if len(font_files) == 0:
        logger.warn("Failed to lookup font '{}', falling back to default".format(font))
        font = ImageFont.load_default()
    else:
        font = ImageFont.truetype(font_files[0], font_size)

    # Don't mutate original image
    img = Image.fromarray(img)
    draw = ImageDraw.Draw(img)
    draw.text(position, text, fill=color, font=font)
    return np.asarray(img)
Beispiel #8
0
  def _Textmark(self, image, text, truefont=None, opacity=50):
    """Creates an image watermarked with the given text.

    Pastes the text in the given font and size TEXTMARK_HEIGHT of the image's
    height, in the bottom right corner of the image.

    Args:
      image: The image to watermark.
      text: The text to paste in the image.
      truefont: A truefont filename for the font to be used.
      opacity: The opacity of the watermark (default: 50).
    Returns:
      A new watermarked Image with the given text.
    """
    img = image.convert('RGB')
    wm = Image.new('RGBA', img.size)
    draw = ImageDraw.ImageDraw(wm, 'RGBA')
    fontsize = int(TEXTMARK_HEIGHT * img.size[1])
    if truefont:
      font = ImageFont.truetype(truefont, fontsize)
    else:
      font = ImageFont.load_default()
    textsize = font.getsize(text)
    draw.setfont(font)
    # Draw text in bottom right corner
    draw.text(((wm.size[0] - textsize[0] - TEXTMARK_SPACE),
               (wm.size[1] - textsize[1] - TEXTMARK_SPACE)), text)
    # Make transperent by adding an alpha layer on the watermark
    # (PIL alpha layer must be of type 'L' or '1')
    mask = wm.convert('L').point(lambda x: min(x, opacity))
    wm.putalpha(mask)
    img.paste(wm, None, wm)
    return img
 def getFont(self, size):
     try:
         font_path = os.path.join(self.font_path, "Fontin-Bold.otf")
         font = ImageFont.truetype(font_path, size*300/72)
         return font
     except IOError:
         return ImageFont.load_default()
Beispiel #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()
def draw_text( data, text, color = 255, pos = 'lr' ):
    from PIL.Image import fromarray
    from PIL.ImageDraw import Draw
    from PIL import ImageFont
    from numpy import asarray

    font = ImageFont.load_default()

    image = fromarray( data )
    draw = Draw( image )
    w, h = draw.textsize( text, font = font )

    position = {
        'ul': lambda iw, ih, tw, th: ( 2, 0 ),
        'ur': lambda iw, ih, tw, th: ( iw - tw - 2, 0 ),
        'll': lambda iw, ih, tw, th: ( 2, ih - th ),
        'lr': lambda iw, ih, tw, th: ( iw - tw - 2, ih - th ),
    }

    pos = position[ pos ]( data.shape[ 1 ], data.shape[ 0 ], w, h )

    draw.text( pos, text, fill = color, font = font )
    del draw

    return asarray( image )
Beispiel #12
0
    def __init__(self, coder, **options):
        """Initializes a new BarcodeImage generator.

        Arguments:
          @ coder: barcode generator
            A callable object that takes an iterable and returns a string of ones
            and zeroes that describes the barcode.
          % barwidth: int ~~ 1
            The width of the smallest bar in pixels.
          % dpi: int ~~ 96
            Print resolution of the generated images.
          % font_file: str ~~ None
            Font file to use for the barcode text. This should be a full pathname
            to a True- or Open Type font. If omitted, the default (courier) is used.
          % font_size: int ~~ 9
            The font size to use with the given font_file. This is a size in points.
          % format: str ~~ 'png'
            The output image format.
          % height: int ~~ 30 * barwidth
            The height of the generated images.
          % print_text: bool ~~ True
            Configures whether text should be printed on the baseline of the image.
        """
        self.coder = coder
        self.options = options
        self.options.setdefault('barwidth', 1)
        self.options.setdefault('height', 30 * self.options['barwidth'])
        self.options.setdefault('dpi', 96)
        self.options.setdefault('format', 'png')
        self.options.setdefault('print_text', True)
        if 'font_file' in self.options:
            self.font = ImageFont.truetype(self.options['font_file'],
                                           self.options['font_size'])
        else:
            self.font = ImageFont.load_default()
Beispiel #13
0
    def __blank_tile_default(self):
        import pkg_resources
        from PIL import Image as PilImage
        from PIL import ImageDraw, ImageFont

        im = PilImage.new('RGB', (256, 256), (234, 224, 216))

        text = 'Image not available'
        try:
            font_file = pkg_resources.resource_filename(
                'mapping.enable', 'fonts/Verdana.ttf'
            )
            font = ImageFont.truetype(font_file, 18)
        except IOError:
            font = ImageFont.load_default()
        size = font.getsize(text)
        pos = (256-size[0])//2, (256-size[1])//2

        draw = ImageDraw.Draw(im)
        draw.text(pos, text, fill=(200, 200, 200), font=font)
        del draw

        tile = StringIO()
        im.save(tile, format='png')
        return Image(StringIO(tile.getvalue()))
Beispiel #14
0
def _get_placeholder_instance(c, text=None):
    imsize = (160, 80)
    immode = 'RGBA'
    imfont = 'Arial.ttf'
    imfontsize = 22
    imtext = c.mimetype if text is None else text
    imtext = imtext.replace('/', ' ').split(' ')
    if len(imtext) == 1:
        imtext.append(u'')
    im = Image.new(immode, imsize, '#eeeeee')
    draw = ImageDraw.Draw(im)
    try:
        font = ImageFont.truetype(imfont, imfontsize, encoding='unic')
    except IOError:
        font = ImageFont.load_default()
        raise
    
    draw.text((5,10), imtext[0], font=font, fill='#333333')
    draw.text((5,35), imtext[1], font=font, fill='#333333')
    #corners = [(0,0), 
    #           (imsize[0], 0), 
    #           (imsize[0], imsize[1]),
    #           (0, imsize[1]),
    #           (0,0)
    #           ]
    #for i in range(0,len(corners)-1):
    #    draw.line((corners[i], corners[i+1]), width=3, fill='#000000')
    del draw
    #im.save("/tmp/text.png", "PNG")
    return im 
Beispiel #15
0
 def __init__(self, text, font=ImageFont.load_default()):
     self.text = " " + text + " "
     size = font.getsize(self.text)
     self.img = Image.new('RGBA', size, BLACK)
     draw = ImageDraw.Draw(self.img)
     draw.text((0, 0), self.text, font=font, fill=TRANSPARENT)
     self.mask = self.img.split()[3]
def write_tour_to_img(coords, tour, img_file):
    """ The function to plot the graph """
    padding = 20
    coords = [(x + padding, y + padding) for (x, y) in coords]
    maxx, maxy = 0, 0
    for x, y in coords:
        maxx, maxy = max(x, maxx), max(y, maxy)
    maxx += padding
    maxy += padding
    img = Image.new("RGB", (int(maxx), int(maxy)), color=(255, 255, 255))
    font = ImageFont.load_default()
    d = ImageDraw.Draw(img)
    num_cities = len(tour)
    for i in range(num_cities):
        j = (i + 1) % num_cities
        city_i = tour[i]
        city_j = tour[j]
        x1, y1 = coords[city_i]
        x2, y2 = coords[city_j]
        d.line((int(x1), int(y1), int(x2), int(y2)), fill=(0, 0, 0))
        d.text((int(x1) + 7, int(y1) - 5), str(i),
               font=font, fill=(32, 32, 32))

    for x, y in coords:
        x, y = int(x), int(y)
        d.ellipse((x - 5, y - 5, x + 5, y + 5),
                  outline=(0, 0, 0), fill=(196, 196, 196))
    del d
    img.save(img_file, "PNG")
    print "The plot was saved into the %s file." % (img_file,)
Beispiel #17
0
    def load_text(self,text,width=None,height=None,color=(255,255,255),ttf=None):
        img = Image.new("RGBA",(1000,200), (0,0,0))
        draw = ImageDraw.Draw(img)
        if ttf==None:
            font = ImageFont.load_default()
        else:
            font = ImageFont.truetype(ttf,100)

        size = draw.textsize(text, font=font)
        w,h = size
        if width==None:
            width = int(w * (float(height)/h))
        img = Image.new("RGBA",size,(0,0,0,0))
        draw = ImageDraw.Draw(img)
        draw.text((0,0), text, color, font=font )
        
        # The below silliness is because bbox does not work well with truetype fonts.
        w,h = img.size
        x1 = int(w)
        y1 = int(h)
        x2 = 0
        y2 = 0
        for y in xrange(h):
            for x in xrange(w):
                alpha = img.getpixel((x,y))[3]
                if alpha > 0:
                    x1 = min(x1,x)
                    x2 = max(x2,x)
                    y1 = min(y1,y)
                    y2 = max(y1,y)
        x2 = min(w,x2+1)
        y2 = min(h,y2+1)
        img = img.crop((x1,y1,x2,y2))
        self.load_image(width=width, height=height, image=img)
        return self
    def save_image(self):
        try:
            font = ImageFont.truetype(self.font, size=self.fontsize, encoding=self.encoding)
        except IOError:
            font = ImageFont.load_default()

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

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

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

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

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

        result_img.paste(txt_img)
        txt_img.save(self.path, self.fmt)
Beispiel #19
0
def create_png(num):
    path = get_solution(num)
    city = get_start_end()
    path.append(city)
    size = (500,500)
    padding = (50,50)
    im = Image.new("RGB",size,(255,255,255))

    draw = ImageDraw.Draw(im)
    font = ImageFont.load_default()

    s = 4 #scale
    p = 50 #padding, shift map over to middle of image
    tp = 15 + p #shift over text padding a bit to account for vertices later        
    low_bound = 90
    color = (255 - low_bound) / (len(path) - 1) # use to change colors

    #draw edges
    for i in range(len(path) - 1):
        c1 = path[i]
        c2 = path[i+1]

        draw.line((s*c1[0]+p, s*c1[1]+p, s*c2[0]+p, s*c2[1]+p), fill = (0,0,0))
        #label each city with coordinates
        draw.text((s*c1[0]+tp, s*c1[1]+p), str(c1), font=font, fill = (0,0,i*color+low_bound))

    c1 = path[len(path)-1] #this is the starting city due to the way append works
    c2 = path[0]
    draw.line((s*c1[0]+p, s*c1[1]+p, s*c2[0]+p, s*c2[1]+p), fill = (0,0,0))
    draw.text((s*c1[0]+tp, s*c1[1]+p), str(c1), font=font, fill = (255,0,0))
    
    #draw vertices (that aren't the starting/ending)
    path.remove(city)
    for i in range(len(path)):
        pos = path[i]
        x = s*pos[0] + p
        y = s*pos[1] + p
        draw.ellipse((x-5, y-5, x+5, y+5), outline=(0,0,0), fill = ((0,0,(i*color+low_bound))))

    #draw starting/ending city with RED
    x = s*city[0] + p
    y = s*city[1] + p
    draw.ellipse((x-5, y-5, x+5, y+5), outline=(0,0,0), fill = (255,0,0))

    draw.text((10,10), "Distance: " + str(get_dist(num)), font=font, fill = (0,0,0))
    if num == 0:
        name = "greedy"
    elif num == 1:
        name = "genetic"
    else:
        name = "dynamic"
    filename = "tsp_"+name+".png"
    draw.text((10,20), "Algorithm used: " + name, font=font, fill = (0,0,0))

    del draw
    im.save(filename, "PNG")

    os.system(filename)
    
    print ".png drawn!"
Beispiel #20
0
def save_swatches(filename=None):
    from PIL import ImageFont, ImageDraw

    cellw, cellh = 24, 24
    im = Image.new('P', (16*cellw, 5*cellh), 0x0F)
    im.putpalette(b''.join(bisqpal) + b'\xff\x00\xff'*192)
    fnt = ImageFont.load_default()
    dc = ImageDraw.Draw(im)
    captiontxt = "savtool's NES palette"
    tw, th = dc.textsize(captiontxt, font=fnt)
    captionpos = ((cellw * 16 - tw) // 2, (cellh - th) // 2)
    dc.text(captionpos, captiontxt, font=fnt, fill=0x20)
    for row in range(4):
        y = (row + 1) * cellh
        for col in range(16):
            x = col * cellw
            colornumber = row * 16 + col
            dc.rectangle((x, y, x + cellw, y + cellh), fill=colornumber)

            # draw caption
            graylevel = (row + 1 if col < 1
                         else row if col < 13
                         else row - 1 if col < 14
                         else 0)
            captioncolor = 0x20 if graylevel < 2 else 0x0F
            captiontxt = '%02x' % colornumber
            tw, th = dc.textsize(captiontxt, font=fnt)
            captionpos = (x + cellw - tw, y + cellh - th)
            dc.text(captionpos, captiontxt, font=fnt, fill=captioncolor)
    if filename:
        im.save(filename)
    else:
        im.show()
Beispiel #21
0
  def __init__(self, json):
    """ Parse out the various settings of a text label and clean them up """
    self.source =     util.get_default(json, "source", "text.txt")
    self.x =          util.get_default(json, "x", 10, int)
    self.y =          util.get_default(json, "y", 10, int)
    self.width =      util.get_default(json, "width", 40000, int)
    self.height =     util.get_default(json, "height", 40000, int)
    self.color =      util.get_default(json, "color", "#000000")
    self.fontface =   util.get_default(json, "font-face", "Palatino Linotype")
    self.fontsize =   util.get_default(json, "font-size", 10, int)
    self.spacing =    util.get_default(json, "line-spacing", 4, int)
    self.justify =    util.get_default(json, "justify", "left")
    self.x_align =    util.get_default(json, "x-align", "left")
    self.y_align =    util.get_default(json, "y-align", "top")
    self.wordwrap =   util.get_default(json, "wordwrap", True, bool)
    self.rotation =   util.get_default(json, "rotation", 0, int)
    weight =          util.get_default(json, "font-weight", "regular")

    self.fontweight = sysfont.STYLE_NORMAL
    if (weight == "bold"):   self.fontweight = sysfont.STYLE_BOLD
    if (weight == "italic"): self.fontweight = sysfont.STYLE_ITALIC

    # Try to auto-select a font based on the user's string
    candidate_font = sysfont.get_font(self.fontface, self.fontweight)
    if (candidate_font is None):
      # Fallback to arial
      sys.stderr.write("Unable to locate font %s. Falling back to Arial.\n" % self.fontface)
      candidate_font = sysfont.get_font("arial black", self.fontweight)

    self.font = ImageFont.load_default()
    if (candidate_font is not None):
      self.font = ImageFont.truetype(candidate_font, self.fontsize)
def render(charset, fontsize, datalist=[]): # Render each char to raw grayscales
	if os.path.isfile(FONT):
		font = ImageFont.truetype(FONT, fontsize)
	else:
		font = ImageFont.load_default()
	print("Render:%s" % fontsize)
	for char in charset:
		canvas = Image.new('L', (fontsize, fontsize))
		painter = ImageDraw.Draw(canvas)
		size = painter.textsize(char, font = font)
		width = size[0]
		if width > fontsize:
			padding_w = (fontsize + 1 - size[0])/2
			print("FAT CHAR!")
			width = fontsize
		else:
			padding_w = 0
#		padding_h = (fontsize - size[1])/2
		padding_h = fontsize - size[1]-1
		if width==fontsize: padding_h = PADDING
		print("size %s\t:%s\t:%s" % (char.encode('utf-8'), width, padding_h))
		painter.text((padding_w, padding_h), char, font=font, fill = (255))	
#		canvas.show()
		datalist.append(np.array(canvas, dtype = np.uint8)[:,:width] >> 4)
	return datalist
Beispiel #23
0
def draw_text(image, text, horizontal_offset, vertical_offset,
              horizontal_justification, vertical_justification, size,
              color='#FFFFFF', orientation=None, font=None):
    """Draws text on an image."""
    image = convert_safe_mode(image)
    if orientation:
        orientation = getattr(Image, orientation)

    draw = ImageDraw.Draw(image)
    if font.strip():
        font = ImageFont.truetype(font, size)
    else:
        font = ImageFont.load_default()
        text = text.encode('ascii', 'replace')

    if orientation:
        font = ImageFont.TransposedFont(font, orientation)

    location = calculate_location(
        horizontal_offset, vertical_offset,
        horizontal_justification, vertical_justification,
        image.size, draw.textsize(text, font=font))

    # draw
    draw.text(location, text, font=font, fill=color)

    # composite the watermark with the layer
    return image
Beispiel #24
0
def makeScaleBar(img, pxRatio):
    import ImageFont
    windir = os.environ.get("WINDIR")
    fontfile = os.path.join(windir, "Fonts", "ProFontWindows.ttf")
    font = ImageFont.load_default() #ImageFont.truetype(fontfile, 14)

    
    width = 100 # pixel width for scalebar
    margin = 10
    
    draw = aggdraw.Draw(img)
    
    pen = aggdraw.Pen("000000", width=2, opacity=255)
    xMax, yMax = img.size
    x = xMax-margin
    y = yMax-margin
    draw.line([x, y, x-width, y], pen)
    draw.line([x, y-5, x, y+5], pen)
    draw.line([x-width, y-5, x-width, y+5], pen)

    textVal = str(round(pxRatio/1000.0 * width)) + " km"

    draw.textsize(textVal, font.font)   #[10, 10], textVal, None) #[x-width/2, y-15]
    draw.flush()
    del draw
    return img
Beispiel #25
0
def draw_word_wrap(draw, text, xpos=0, ypos=0, max_width=130, ypos_max=None,
                   fill=(0,0,0), font=ImageFont.load_default()):
    '''Draw the given ``text`` to the x and y position of the image, using
    the minimum length word-wrapping algorithm to restrict the text to
    a pixel width of ``max_width.``
    http://en.wikipedia.org/wiki/Word_wrap
    '''
    # draw = ImageDraw(img)
    text_size_x, text_size_y = draw.textsize(text, font=font)
    remaining = max_width
    space_width, space_height = draw.textsize(' ', font=font)
    # use this list as a stack, push/popping each line
    output_text = []
    # split on whitespace...
    for word in list(text): # text.split(None):
        word_width, word_height = draw.textsize(word, font=font)
        if word_width + space_width > remaining:
            output_text.append(word)
            remaining = max_width - word_width
        else:
            if not output_text:
                output_text.append(word)
            else:
                output = output_text.pop()
                output += ' %s' % word
                output_text.append(output)
            remaining = remaining - (word_width + space_width)
            
    print xpos, ypos, max_width, len(output_text)
    for text in output_text:
        draw.text((xpos, ypos), text, font=font, fill=fill)
        ypos += text_size_y
        if ypos_max is not None and ypos > ypos_max: break
Beispiel #26
0
  def __init__(self, nobjects=1, alpha_in=0.9):
    """Initialize the colour map that will be used to give a different colour for every object in the image.
       Every object will have an ID starting from 0 to 254.

    Args:
      nobjects (int): The number of objects in the image
      alpha_in (float): the transparance of the circles. It should be between 0 and 1. 
    """


    if not isinstance(nobjects, int):
      raise Exception('nobjects should be a positive integer less than 255. Received:"{0}"'.format(nobjects))

    if not (nobjects > 0 and nobjects < 255):
      raise Exception('nobjects should be a positive integer less than 255. Received:"{0}"'.format(nobjects))

    if alpha_in < 0 or alpha_in > 1: 
      raise Exception ('ERROR: alpha_in should be between 0 and 1. Received:"{0}"'.format(alpha_in))


    #Distribute the colour over the 255 range for the color map
    color_step =  255  / float(nobjects) 
    streched_ids = [ int(math.floor(float(set_id) * color_step)) for set_id in range (0,nobjects)] 
    scalar_colors = [  cm.Accent(s_id, bytes=True, alpha = alpha_in) for s_id in streched_ids] 

    rgb_color_map = zip(range(0, nobjects), scalar_colors)

    #rgb_color_map = [ (particle, scalar_color[set_id]) \
    #  for particle, set_id in zip(range(0, nobjects), range(0, nobjects))] 

    #Create the dictionary that maps an object to a colour. 
    self.color_dict = dict(rgb_color_map)

    #define a font
    self.fnt = ImageFont.load_default()
def validatePicGenerate(word, psize=(120,30), font_file='', font_size=20, format='GIF', fg=-1, bg=-1):
    if fg == -1:
        fg = random.randint(0, 0xffffff)
    if bg == -1:
        bg = fg ^ 0xffffff

    if os.path.exists(font_file):
        font = ImageFont.truetype(font_file, font_size)
    else:
        font = ImageFont.load_default()
    #
    #size = font.getsize(word)
    #
    img = Image.new('RGB', psize, bg)
    draw = ImageDraw.Draw(img)
    #
    for i in range(5):
        lines = []
        for i in range(random.randint(3,5)):
            lines.append((random.randint(0, 100), random.randint(0, 100)))        
        draw.polygon(lines, outline=fg)
    #
    width = psize[0]/len(word)
    i = 0
    for w in word:
        x = (i * width) + 1
        y = random.randint(-1, 4)
        draw.text((x, y), w, font=font, fill=fg)
        i += 1
    #
    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img
Beispiel #28
0
def main():
    # Initialize and create object for led strip, starting with initial
    # brightness of 0 (all off)
    mraa_init()
    ds = Dotstar(init_brightness=0,led_count = 216)
    font = ImageFont.load_default()
    img = Image.open("logo.png").rotate(0).resize((ds.led_count/72,72))
    #img = Image.new("RGB", (2,2), (255,0,0))
    pixels = img.load()
    width = img.size[0]
    height = img.size[1]
    print ds.led_count
    
    if height > ds.led_count:
        height=ds.led_count
    
    print "WIDTH: ", width
    print "HEIGHT: ", height
    gamma = bytearray(256)
    for i in range(256):
        gamma[i] = int(pow(float(i) / 255.0, 2.7) * 255.0 + 0.5)
      
    for x in range(width):
        for y in range(height):
            value = pixels[x,y]
            if (x%2 is 0):
                # We need to reverse here!
                ds.set((x*72)+y,1,gamma[value[0]],gamma[value[1]],gamma[value[2]])
            else:
                # Normal section, do not reverse
                ds.set((x*72)+y,5,gamma[value[0]],gamma[value[1]],gamma[value[2]])
    ds.draw() 
Beispiel #29
0
	def calibrate_line(self):
		l=Lcd()
		l.reset()
		font = ImageFont.load_default()
		k=Key()
		c=BetterColorSensor()
		l.draw.text((50, 10), "KALIBRIERUNG", font=font)
		l.draw.text((10, 50), "Farbsensor auf schwarze Linie richten", font=font)
		l.draw.text((10, 70), "weiter mit nach-oben Taste!") 
		while(True):
			l.update()
			black=c.grey
			print('Schwarz:'+str(black))
			if k.up:break
		time.sleep(1)
		l.reset()
		l.draw.text((50, 10), "KALIBRIERUNG", font=font)
		l.draw.text((10, 50), "Farbsensor NEBEN schwarze Linie richten", font=font)
		l.draw.text((10, 70), "weiter mit nach-oben Taste!")
		while(True):
			l.update()
			white=c.grey
			print('Weiss:'+str(white))
			if k.up:break
		l.reset()	
		self.set('Line','white',str(white))
		self.set('Line','black',str(black))
		self.set('Init','calibrate',str(False))
		os.remove(self.path)
		with open(self.path, 'wb') as configfile:
			self.write(configfile)
Beispiel #30
0
def ascii2image(ss, im, constrast = True, font_size = 4, delta = 1):
    # fnt = ImageFont.truetype('Courier_New.ttf', size = font_size)
    # fnt = ImageFont.truetype('Consolas.ttf', size = font_size)
    fnt = ImageFont.load_default()
    (sw, sh) = fnt.getsize(ss[0][0])
    (ew, eh) = im.size
    # print ew, eh, len(ss[0]), len(ss)
    assert(ew == len(ss[0]) and eh == len(ss))
    w = (sw + delta) * len(ss[0])
    h = (sh + delta) * len(ss)
    # print ew, eh, w, h
    (dx, dy) = (0, 0)
    if (ew * 1.0 / eh) > (w * 1.0 / h):
        nw = int(ew * 1.0 * h / eh)
        dx = (nw - w) * 0.5
        w = nw
    else:
        nh = int(eh * 1.0 * w / ew)
        dy = (nh - h) * 0.5
        h = nh
    # print dx, dy, w, h
    txt = Image.new('RGB', (w, h), (0, 0, 0) if constrast else (255, 255, 255))
    d = ImageDraw.Draw(txt)
    for (idx , s) in enumerate(ss):
        y = dy + idx * (sh + delta) + delta * 0.5
        x = dx + delta * 0.5
        for (idx2, s2) in enumerate(s):
            pixel = im.getpixel((idx2, idx))
            d.text((x, y), s2, font = fnt, fill = pixel if constrast else (0, 0, 0))
            x += (sw + delta)
    return txt
Beispiel #31
0
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color=(255, 0, 0),
                               thickness=4,
                               display_str='',
                               use_normalized_coordinates=True):
    """Adds a bounding box to an image.

    Bounding box coordinates can be specified in either absolute (pixel) or
    normalized coordinates by setting the use_normalized_coordinates argument.

    The string passed in display_str is displayed above the
    bounding box in black text on a rectangle filled with the input 'color'.
    If the top of the bounding box extends to the edge of the image, the string
    is displayed below the bounding box.

    Args:
        image (PIL.Image): PIL.Image object
        ymin (float): ymin of bounding box
        xmin (float): xmin of bounding box
        ymax (float): ymax of bounding box
        xmax (float): xmax of bounding box
        color (int, int, int): RGB tuple describing color to draw bounding box
        thickness (int): line thickness
        display_str (str): string to display in box
        use_normalized_coordinates (bool): If True, treat coordinates
            ymin, xmin, ymax, xmax as relative to the image. Otherwise treat
            coordinates as absolute
    """
    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size
    #解析相应的预测值
    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    #画框的边
    draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=tuple(color))
    try:
        font = ImageFont.truetype('arial.ttf', 24)
    except IOError:
        font = ImageFont.load_default()
    
    # If the total height of the display string added to the top of the bounding
    # box exceeds the top of the image, move the string below the bounding box
    # instead of above
    #像是相应的字符串
    display_str_height = font.getsize(display_str)[1]
    # Each display_str has a top and bottom margin of 0.05x
    total_display_str_height = (1 + 2 * 0.05) * display_str_height

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height
    
    text_width, text_height = font.getsize(display_str)
    margin = np.ceil(0.05 * text_height)
    draw.rectangle(
        [(left, text_bottom - text_height - 2 * margin), (left + text_width,
            text_bottom)],
        fill=tuple(color))
    draw.text(
        (left + margin, text_bottom - text_height - margin),
        display_str,
        fill='black',
        font=font)
    text_bottom -= text_height - 2 * margin
Beispiel #32
0
def visualize_detections(img_path,
                         roi_coords,
                         roi_labels,
                         roi_scores,
                         pad_width,
                         pad_height,
                         classes,
                         draw_negative_rois=False,
                         decision_threshold=0.0):
    # read and resize image
    imgWidth, imgHeight = imWidthHeight(img_path)
    scale = 800.0 / max(imgWidth, imgHeight)
    imgHeight = int(imgHeight * scale)
    imgWidth = int(imgWidth * scale)
    if imgWidth > imgHeight:
        h_border = 0
        v_border = int((imgWidth - imgHeight) / 2)
    else:
        h_border = int((imgHeight - imgWidth) / 2)
        v_border = 0

    PAD_COLOR = [103, 116, 123]  # [114, 114, 114]
    cv_img = cv2.imread(img_path)
    rgb_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
    resized = cv2.resize(rgb_img, (imgWidth, imgHeight),
                         interpolation=cv2.INTER_NEAREST)
    result_img = cv2.copyMakeBorder(resized,
                                    v_border,
                                    v_border,
                                    h_border,
                                    h_border,
                                    cv2.BORDER_CONSTANT,
                                    value=PAD_COLOR)
    rect_scale = 800 / pad_width

    assert (len(roi_labels) == len(roi_coords))
    if roi_scores is not None:
        assert (len(roi_labels) == len(roi_scores))
        minScore = min(roi_scores)
        if minScore > decision_threshold:
            decision_threshold = minScore * 0.5

    # draw multiple times to avoid occlusions
    for iter in range(0, 3):
        for roiIndex in range(len(roi_coords)):
            label = roi_labels[roiIndex]
            if roi_scores is not None:
                score = roi_scores[roiIndex]
                if decision_threshold and score < decision_threshold:
                    label = 0

            # init drawing parameters
            thickness = 1
            if label == 0:
                color = (255, 0, 0)
            else:
                color = getColorsPalette()[label]

            rect = [(rect_scale * i) for i in roi_coords[roiIndex]]
            rect[0] = int(max(0, min(pad_width, rect[0])))
            rect[1] = int(max(0, min(pad_height, rect[1])))
            rect[2] = int(max(0, min(pad_width, rect[2])))
            rect[3] = int(max(0, min(pad_height, rect[3])))

            # draw in higher iterations only the detections
            if iter == 0 and draw_negative_rois:
                drawRectangles(result_img, [rect],
                               color=color,
                               thickness=thickness)
            elif iter == 1 and label > 0:
                thickness = 4
                drawRectangles(result_img, [rect],
                               color=color,
                               thickness=thickness)
            elif iter == 2 and label > 0:
                try:
                    font = ImageFont.truetype(available_font, 18)
                except:
                    font = ImageFont.load_default()
                text = classes[label]
                if roi_scores is not None:
                    text += "(" + str(round(score, 2)) + ")"
                result_img = drawText(result_img, (rect[0], rect[1]),
                                      text,
                                      color=(255, 255, 255),
                                      font=font,
                                      colorBackground=color)
    return result_img
def draw_bounding_box_on_image(current_frame_number,image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color='red',
                               thickness=4,
                               display_str_list=(),
                               use_normalized_coordinates=True):
  """Adds a bounding box to an image.

  Each string in display_str_list is displayed on a separate line above the
  bounding box in black text on a rectangle filled with the input 'color'.
  If the top of the bounding box extends to the edge of the image, the strings
  are displayed below the bounding box.

  Args:
    image: a PIL.Image object.
    ymin: ymin of bounding box.
    xmin: xmin of bounding box.
    ymax: ymax of bounding box.
    xmax: xmax of bounding box.
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list: list of strings to display in box
                      (each to be shown on its own line).
    use_normalized_coordinates: If True (default), treat coordinates
      ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
      coordinates as absolute.
  """
  csv_line = "" # to create new csv line consists of vehicle type, predicted_speed, color and predicted_direction
  update_csv = False # update csv for a new vehicle that are passed from ROI - just one new line for each vehicles
  is_vehicle_detected = [0]
  draw = ImageDraw.Draw(image)
  im_width, im_height = image.size
  if use_normalized_coordinates:
    (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                  ymin * im_height, ymax * im_height)
  else:
    (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
  draw.line([(left, top), (left, bottom), (right, bottom),
             (right, top), (left, top)], width=thickness, fill=color)

  predicted_speed = "n.a." # means not available, it is just initialization
  predicted_direction = "n.a." # means not available, it is just initialization

  image_temp = numpy.array(image)
  detected_vehicle_image = image_temp[int(top):int(bottom), int(left):int(right)]

  if(bottom > ROI_POSITION):
      # if the vehicle get in ROI area, vehicle predicted_speed predicted_color algorithms are
      #  called - 200 is an arbitrary value, for my case it looks very well to set position of ROI line at y pixel 200
        predicted_direction, predicted_speed,  is_vehicle_detected, update_csv = speed_prediction.predict_speed(top, bottom, right, left, current_frame_number, detected_vehicle_image, ROI_POSITION)

  predicted_color = color_recognition_api.color_recognition(detected_vehicle_image)

  try:
    font = ImageFont.truetype('arial.ttf', 16)
  except IOError:
    font = ImageFont.load_default()

  # If the total height of the display strings added to the top of the bounding
  # box exceeds the top of the image, stack the strings below the bounding box
  # instead of above.
  display_str_list[0] = predicted_color + " " + display_str_list[0]
  csv_line = predicted_color + "," + str (predicted_direction) + "," + str(predicted_speed) # csv line created
  display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]

  # Each display_str has a top and bottom margin of 0.05x.
  total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

  if top > total_display_str_height:
    text_bottom = top
  else:
    text_bottom = bottom + total_display_str_height

  # Reverse list and print from bottom to top.
  for display_str in display_str_list[::-1]:
    text_width, text_height = font.getsize(display_str)
    margin = np.ceil(0.05 * text_height)
    draw.rectangle(
        [(left, text_bottom - text_height - 2 * margin), (left + text_width,
                                                          text_bottom)],
        fill=color)
    draw.text(
        (left + margin, text_bottom - text_height - margin),
        display_str,
        fill='black',
        font=font)
    text_bottom -= text_height - 2 * margin
    return is_vehicle_detected, csv_line, update_csv
Beispiel #34
0
def asciiart(input_file,
             HORIZONTAL_SAMPLING_RATE,
             GCF,
             output_file,
             color1='black',
             color2='blue',
             bgcolor='white'):

    # The array of ascii symbols from white to black
    chars = np.asarray(list(' .,:irs?@9B&#'))

    # Load the fonts and then get the the height and width of a typical symbol
    # You can use different fonts here
    font = ImageFont.load_default()
    letter_width = font.getsize("x")[0]
    letter_height = font.getsize("x")[1]

    height_width_ratio = letter_height / letter_width

    #open the input file
    img = Image.open(input_file)

    #Calculate how many ascii letters are needed on the width and height
    width_by_letter = round(img.size[0] * HORIZONTAL_SAMPLING_RATE *
                            height_width_ratio)
    height_by_letter = round(img.size[1] * HORIZONTAL_SAMPLING_RATE)
    letter_size = (width_by_letter, height_by_letter)

    #Resize the image based on the symbol width and height
    img = img.resize(letter_size)

    #Get the RGB color values of each sampled pixel and convert them to graycolor using average.
    #https://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
    img = np.sum(np.asarray(img), axis=2)

    # Normalize the results, enhance and reduce the brightness contrast.
    # Map grayscale values to bins of symbols
    img -= img.min()
    img = (1.0 - img / img.max())**GCF * (chars.size - 1)

    # Generate the ascii art symbols
    lines = ("\n".join(
        ("".join(r) for r in chars[img.astype(int)]))).split("\n")

    # Create gradient color bins
    nbins = len(lines)
    color_range = list(Color(color1).range_to(Color(color2), nbins))

    #Create an image object, set its width and height
    new_image_width = letter_width * width_by_letter
    new_image_height = letter_height * height_by_letter
    new_image = Image.new("RGBA", (new_image_width, new_image_height), bgcolor)
    draw = ImageDraw.Draw(new_image)

    # Print symbols to image
    left_padding = 0
    y = 0
    line_index = 0
    for line in lines:
        color = color_range[line_index]
        line_index += 1

        draw.text((left_padding, y), line, color.hex, font=font)
        y += letter_height

    # Save the image file
    new_image.save(output_file)
Beispiel #35
0
    def DepthFirstSearch(self, st: Struct, drawed, cur, pos, im: Image):
        self.atom_pos[cur] = pos
        #Updating size of molecule to correct drawing
        self.__min_x = min(self.__min_x, pos[0])
        self.__max_x = max(self.__max_x, pos[0])
        self.__min_y = min(self.__min_y, pos[1])
        self.__max_y = max(self.__max_y, pos[1])

        size = st.getSize()
        draw = ImageDraw.Draw(im)
        drawed[cur] = True

        #Calculating degree between bonds
        cur_degree = 120
        num_of_neighbours = len(st.getAdjacencyList(cur))
        if (num_of_neighbours > 3):
            cur_degree = 360 / num_of_neighbours
        step = cur_degree
        cur_degree /= 2
        k = 1 - 2 * (len(drawed) % 2)

        for u in st.getAdjacencyList(cur):
            if (not u in drawed):
                new_pos = (pos[0] + self.__bondLength * \
                    math.sin(math.radians(cur_degree)), \
                    pos[1] + self.__bondLength * \
                    k * math.cos(math.radians(cur_degree)))

                if (cur in st.vertex_cycles):
                    cycle = -1
                    for c in st.vertex_cycles[cur]:
                        if (cur in st.cy_list[c] and u in st.cy_list[c]):
                            cycle = c
                            break
                    if (cycle != -1):
                        cur_cycle_degree, step = self.current_cdegree[c]
                        print(cur_cycle_degree, step)
                        new_pos = (pos[0] + self.__bondLength * \
                                math.sin(math.radians(cur_cycle_degree)), \
                                pos[1] + self.__bondLength * \
                                math.cos(math.radians(cur_cycle_degree)))
                        cur_cycle_degree -= step
                        self.current_cdegree[c] = (cur_cycle_degree, step)

                cur_degree += step

                if (st.getMatrixElement(cur, u) == 1):
                    draw.line(pos + new_pos, fill=(0, 0, 0, 255), width=3)
                elif (st.getMatrixElement(cur, u) == 2):
                    x_ = 0
                    y_ = 0
                    tg_a = 0
                    if ((new_pos[0] - pos[0]) != 0):
                        tg_a = (new_pos[1] - pos[1]) / (new_pos[0] - pos[0])
                        x_ = self.__d * tg_a / math.sqrt(1 + tg_a**2)
                        y_ = self.__d / math.sqrt(1 + tg_a**2)
                    else:
                        x_ = self.__d
                    draw.line((pos[0] - x_, pos[1] + y_,\
                               new_pos[0] - x_, new_pos[1] + y_),\
                               fill = (0, 0, 0, 255), width = 3)
                    draw.line((pos[0] + x_, pos[1] - y_,\
                               new_pos[0] + x_, new_pos[1] - y_),\
                               fill = (0, 0, 0, 255), width = 3)
                elif (st.getMatrixElement(cur, u) == 3):
                    new_pos = (pos[0] + self.__bondLength * \
                               math.sin(math.radians(cur_degree)), \
                               pos[1] + self.__bondLength * \
                               p_k * math.cos(math.radians(cur_degree)))
                    x_ = 0
                    y_ = 0
                    tg_a = 0
                    if ((new_pos[0] - pos[0]) != 0):
                        tg_a = (new_pos[1] - pos[1]) / (new_pos[0] - pos[0])
                        x_ = self.__td * tg_a / math.sqrt(1 + tg_a**2)
                        y_ = self.__td / math.sqrt(1 + tg_a**2)
                    else:
                        x_ = self.__td
                    draw.line((pos[0] - x_, pos[1] + y_,\
                           new_pos[0] - x_, new_pos[1] + y_),\
                           fill = (0, 0, 0, 255), width = 2)
                    draw.line((pos[0] + x_, pos[1] - y_,\
                           new_pos[0] + x_, new_pos[1] - y_),\
                           fill = (0, 0, 0, 255), width = 2)
                    draw.line(pos + new_pos, fill=(0, 0, 0, 255), width=3)

                if (cur in st.cycles and st.cycles[cur] == "START"):
                    im = self.DepthFirstSearch(st, drawed, u, new_pos, im)
                elif (cur in st.cycles and st.cycles[cur] == "END"):
                    im = self.DepthFirstSearch(st, drawed, u, new_pos, im)
                else:
                    im = self.DepthFirstSearch(st, drawed, u, new_pos, im)

            elif((cur in st.cycles) and (u in st.cycles) \
                 and (st.cycles[u] == "START") and \
                 (st.cycles[cur] == "END")):
                # !!! Here we will chek if u and cur in same cycles
                draw.line(pos + self.atom_pos[u], \
                          fill = (0, 0, 0, 255), width = 2)

        if (st.getAtom(cur).getType() != 'c'):
            draw.ellipse((pos[0] - 3, pos[1] - 3, pos[0] + 3, pos[1] + 3),
                         fill=(0, 0, 0, 0),
                         outline=(0, 0, 0, 0))
            draw.text((pos[0] - 2, pos[1] - 5), \
                      st.getAtom(cur).getFormattedType(), \
                      font = ImageFont.load_default(), fill = \
                      AtomInfo.getColor(st.getAtom(cur)))

        del draw
        return im
Beispiel #36
0
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
disp.begin()
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = -2
top = padding
bottom = height-padding
x = 0
font = ImageFont.load_default() 
sensor = Adafruit_DHT.DHT11
GPIO.setmode(GPIO.BCM)
led_pin = 20
temp_pin = 21
GPIO.setup(led_pin,GPIO.OUT)

def index(request):
	hum,temperature = Adafruit_DHT.read_retry(sensor,temp_pin)
	value = str(temperature)
	return render(request,"home.html",{"temp":value})

def led(request):
	if request.method=="POST":
		hum,temperature = Adafruit_DHT.read_retry(sensor,temp_pin)
		value = request.POST.get('led_status')
Beispiel #37
0
    def to_pil(self,
               bpc: Bpc,
               palettes: List[List[int]],
               bpas: List[Bpa],
               include_collision=True,
               include_unknown_data_block=True) -> List[Image.Image]:
        """
        Converts the entire map into an image, as shown in the game. Each PIL image in the list returned is one
        frame. The palettes argument can be retrieved from the map's BPL (bpl.palettes).

        The method does not care about frame speeds. Each step of animation is simply returned as a new image,
        so if BPAs use different frame speeds, this is ignored; they effectively run at the same speed.
        If BPAs are using a different amount of frames per tile, the length of returned list of images will be the lowest
        common multiple of the different frame lengths.

        Does not include palette animations. You can apply them by switching out the palettes of the PIL
        using the information provided by the BPL.

        The list of bpas must be the one contained in the bg_list. It needs to contain 8 slots, with empty
        slots being None.

        TODO: The speed can be increased if we only re-render the changed animated tiles instead!
        """

        chunk_width = BPC_TILE_DIM * self.tiling_width
        chunk_height = BPC_TILE_DIM * self.tiling_height

        width_map = self.map_width_chunks * chunk_width
        height_map = self.map_height_chunks * chunk_height

        final_images = []
        lower_layer_bpc = 0 if bpc.number_of_layers == 1 else 1
        chunks_lower = bpc.chunks_animated_to_pil(lower_layer_bpc, palettes,
                                                  bpas, 1)
        for img in chunks_lower:
            fimg = Image.new('P', (width_map, height_map))
            fimg.putpalette(img.getpalette())

            # yes. self.layer0 is always the LOWER layer! It's the opposite from BPC
            for i, mt_idx in enumerate(self.layer0):
                x = i % self.map_width_chunks
                y = math.floor(i / self.map_width_chunks)
                fimg.paste(
                    img.crop((0, mt_idx * chunk_width, chunk_width,
                              mt_idx * chunk_width + chunk_height)),
                    (x * chunk_width, y * chunk_height))

            final_images.append(fimg)

        if bpc.number_of_layers > 1:
            # Overlay higher layer tiles
            chunks_higher = bpc.chunks_animated_to_pil(0, palettes, bpas, 1)
            len_lower = len(chunks_lower)
            len_higher = len(chunks_higher)
            if len_higher != len_lower:
                # oh fun! We are missing animations for one of the layers, let's stretch to the lowest common multiple
                lm = lcm(len_higher, len_lower)
                for i in range(len_lower, lm):
                    final_images.append(final_images[i % len_lower].copy())
                for i in range(len_higher, lm):
                    chunks_higher.append(chunks_higher[i % len_higher].copy())

            for j, img in enumerate(chunks_higher):
                fimg = final_images[j]
                for i, mt_idx in enumerate(self.layer1):
                    x = i % self.map_width_chunks
                    y = math.floor(i / self.map_width_chunks)

                    cropped_img = img.crop(
                        (0, mt_idx * chunk_width, chunk_width,
                         mt_idx * chunk_width + chunk_height))
                    cropped_img_mask = cropped_img.copy()
                    cropped_img_mask.putpalette(MASK_PAL)
                    fimg.paste(cropped_img,
                               (x * chunk_width, y * chunk_height),
                               mask=cropped_img_mask.convert('1'))

        final_images_were_rgb_converted = False
        if include_collision and self.number_of_collision_layers > 0:
            for i, img in enumerate(final_images):
                final_images_were_rgb_converted = True
                # time for some RGB action!
                final_images[i] = img.convert('RGB')
                img = final_images[i]
                draw = ImageDraw.Draw(img, 'RGBA')
                for j, col in enumerate(self.collision):
                    x = j % self.map_width_camera
                    y = math.floor(j / self.map_width_camera)
                    if col:
                        draw.rectangle(
                            ((x * BPC_TILE_DIM, y * BPC_TILE_DIM),
                             ((x + 1) * BPC_TILE_DIM, (y + 1) * BPC_TILE_DIM)),
                            fill=(0xff, 0x00, 0x00, 0x40))
                # Second collision layer
                if self.number_of_collision_layers > 1:
                    for j, col in enumerate(self.collision2):
                        x = j % self.map_width_camera
                        y = math.floor(j / self.map_width_camera)
                        if col:
                            draw.ellipse(((x * BPC_TILE_DIM, y * BPC_TILE_DIM),
                                          ((x + 1) * BPC_TILE_DIM,
                                           (y + 1) * BPC_TILE_DIM)),
                                         fill=(0x00, 0x00, 0xff, 0x40))

        if include_unknown_data_block and self.unk6 > 0:
            fnt = ImageFont.load_default()
            for i, img in enumerate(final_images):
                if not final_images_were_rgb_converted:
                    final_images[i] = img.convert('RGB')
                    img = final_images[i]
                draw = ImageDraw.Draw(img, 'RGBA')
                for j, unk in enumerate(self.unknown_data_block):
                    x = j % self.map_width_camera
                    y = math.floor(j / self.map_width_camera)
                    if unk > 0:
                        draw.text((x * BPC_TILE_DIM, y * BPC_TILE_DIM),
                                  str(unk),
                                  font=fnt,
                                  fill=(0x00, 0xff, 0x00))

        return final_images
Beispiel #38
0
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color='red',
                               thickness=4,
                               display_str_list=(),
                               use_normalized_coordinates=True):
    """Adds a bounding box to an image.

  Bounding box coordinates can be specified in either absolute (pixel) or
  normalized coordinates by setting the use_normalized_coordinates argument.

  Each string in display_str_list is displayed on a separate line above the
  bounding box in black text on a rectangle filled with the input 'color'.
  If the top of the bounding box extends to the edge of the image, the strings
  are displayed below the bounding box.

  Args:
    image: a PIL.Image object.
    ymin: ymin of bounding box.
    xmin: xmin of bounding box.
    ymax: ymax of bounding box.
    xmax: xmax of bounding box.
    color: color to draw bounding box. Default is red.
    thickness: line thickness. Default value is 4.
    display_str_list: list of strings to display in box
                      (each to be shown on its own line).
    use_normalized_coordinates: If True (default), treat coordinates
      ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
      coordinates as absolute.
  """
    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size
    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)
    draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
               (left, top)],
              width=thickness,
              fill=color)
    try:
        font = ImageFont.truetype('arial.ttf', 24)
    except IOError:
        font = ImageFont.load_default()

    # If the total height of the display strings added to the top of the bounding
    # box exceeds the top of the image, stack the strings below the bounding box
    # instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]
    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height
    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)
        draw.rectangle([(left, text_bottom - text_height - 2 * margin),
                        (left + text_width, text_bottom)],
                       fill=color)
        draw.text((left + margin, text_bottom - text_height - margin),
                  display_str,
                  fill='black',
                  font=font)
        text_bottom -= text_height - 2 * margin
def drawText(draw, x, y, title="", fill = 1):
    font = ImageFont.load_default()
    draw.text((x,y), title, font = font, fill= fill )
Beispiel #40
0
from third_party import step

import conf
import emoticons
import images
import main
import skypedata
import templates
import util

try:  # Used in measuring text extent for Excel column auto-width.
    FONT_XLSX = ImageFont.truetype(conf.FontXlsxFile, 15)
    FONT_XLSX_BOLD = ImageFont.truetype(conf.FontXlsxBoldFile, 15)
except IOError:
    FONT_XLSX = FONT_XLSX_BOLD = ImageFont.load_default()
"""FileDialog wildcard strings, matching extensions lists and default names."""
CHAT_WILDCARD = ("HTML document (*.html)|*.html|Text document (*.txt)|*.txt|"
                 "%sCSV spreadsheet (*.csv)|*.csv" % XLSX_WILDCARD)
CHAT_EXTS = ["html", "txt", "xlsx", "csv"] if xlsxwriter \
            else ["html", "txt", "csv"]
CHAT_WILDCARD_SINGLEFILE = "Excel workbook (*.xlsx)|*.xlsx"  # Cannot end with |
CHAT_EXTS_SINGLEFILE = ["xlsx"]

TABLE_WILDCARD = ("HTML document (*.html)|*.html|"
                  "SQL INSERT statements (*.sql)|*.sql|"
                  "%sCSV spreadsheet (*.csv)|*.csv" % XLSX_WILDCARD)
TABLE_EXTS = ["html", "sql", "xlsx", "csv"] if xlsxwriter \
             else ["html", "sql", "csv"]

QUERY_WILDCARD = ("HTML document (*.html)|*.html|"
Beispiel #41
0
def main():
    if os.path.isfile(pidfile):
        print "%s already exists, exiting" % pidfile
        sys.exit()
    file(pidfile, 'w').write(pid)

    config = configparser.ConfigParser({'interval': '5'})
    config.sections()
    config.read('/etc/status.cfg')

    display = config.get('display', 'type')
    sleeptime = float(config.get('display', 'interval'))

    if display == "128x32":
        # 128x32 display with hardware I2C:
        disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
        numLines = 5

    elif display == "128x64":
        # 128x64 display with hardware I2C:
        disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
        numLines = 9

    try:
        Status = stat()
        # Initialize library.
        disp.begin()

        # Clear display.
        disp.clear()
        disp.display()

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

        # Get drawing object to draw on image.
        draw = ImageDraw.Draw(image)

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, width, height), outline=0, fill=0)

        # Load default font.
        font = ImageFont.load_default()

        # Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
        # Some other nice fonts to try: http://www.dafont.com/bitmap.php
        # font = ImageFont.truetype('Minecraftia.ttf', 8)
        top = 0
        lheight = 8

        while True:
            if not killer.kill_now:
                # Draw a black filled box to clear the image.
                draw.rectangle((0, 0, width, height), outline=0, fill=0)
                for i in range(1, numLines):
                    item = config.get('display', 'line' + str(i))
                    draw.text((1, lheight * (i - 1)),
                              Status.get(item),
                              font=font,
                              fill=255)
                # Display image.
                disp.image(image)
                disp.display()
                time.sleep(sleeptime)
            else:
                draw.rectangle((0, 0, width, height), outline=0, fill=0)
                draw.text((1, top), "shutting down")
                draw.text((1, top + 8), "daemon")
                disp.image(image)
                disp.display()

                os.unlink(pidfile)
                exit
    finally:
        os.unlink(pidfile)
Beispiel #42
0
def serial_displays(**kwargs):

    if kwargs['serial_display_type'] == 'oled_sh1106':
        from luma.core.interface.serial import i2c, spi
        from luma.core.render import canvas
        # from luma.core import lib
        from luma.oled.device import sh1106
        # from PIL import Image
        # from PIL import ImageDraw
        from PIL import ImageFont
        from time import sleep
        import logging
        # import socket

        # Load default font.
        font = ImageFont.load_default()
        # 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 = 0
        top = padding
        bottom = height-padding
        display_rotate = kwargs['serial_display_rotate']
        # Move left to right keeping track of the current x position for drawing shapes.
        x = 0

        logging.basicConfig(filename='/tmp/rpims_serial_display.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s')
        logger = logging.getLogger(__name__)

        serial_type = kwargs['serial_type']

        #if serial_type == 'i2c':
        serial = i2c(port=1, address=0x3c)
        if serial_type == 'spi':
            serial = spi(device=0, port=0, bus_speed_hz=8000000, transfer_size=4096, gpio_DC=24, gpio_RST=25)

        try:
            device = sh1106(serial, rotate=display_rotate)
            while True:
                with canvas(device) as draw:
                    # get data from redis db
                    values = redis_db.mget('BME280_Temperature', 'BME280_Humidity', 'BME280_Pressure', 'GPIO_5', 'GPIO_6', 'CPU_Temperature', 'hostip')

                    t,h,p = values[0], values[1], values[2]
                    if t == None or h == None or p == None:
                        temperature = '--.--'
                        humidity = '--.--'
                        pressure = '--.--'
                    elif t.replace('.','',1).isdigit() and h.replace('.','',1).isdigit() and p.replace('.','',1).isdigit():
                        temperature = round(float(t), 1)
                        humidity = int(round(float(h), 1))
                        pressure = int(round(float(p), 1))

                    door_sensor_1, door_sensor_2  = values[3], values[4]
                    if door_sensor_1 == None or door_sensor_2 == None:
                        door_sensor_1 = '-----'
                        door_sensor_2 = '-----'

                    cputemp = values[5]
                    if cputemp == None:
                        cputemp = '-----'
                    else:
                        cputemp = round(float(cputemp), 1)
                    hostip = values[6]
                    if hostip == None:
                        hostip = '---.---.---.---'

                    # draw on oled
                    draw.text((x, top),       'IP:' + str(hostip), font=font, fill=255)
                    draw.text((x, top+9),     f'Temperature..{temperature}°C', font=font, fill=255)
                    draw.text((x, top+18),    f'Humidity.....{humidity}%',  font=font, fill=255)
                    draw.text((x, top+27),    f'Pressure.....{pressure}hPa',  font=font, fill=255)
                    draw.text((x, top+36),    f'Door 1.......{door_sensor_1}',  font=font, fill=255)
                    draw.text((x, top+45),    f'Door 2.......{door_sensor_2}',  font=font, fill=255)
                    draw.text((x, top+54),    f'CpuTemp......{cputemp}°C', font=font, fill=255)
                sleep(1/kwargs['serial_display_refresh_rate'])
        except Exception as err:
            logger.error(err)

    if kwargs['serial_display_type'] == 'lcd_st7735':
        from luma.core.interface.serial import spi
        from luma.core.render import canvas
        # from luma.core import lib
        from luma.lcd.device import st7735
        # from PIL import Image
        # from PIL import ImageDraw
        from PIL import ImageFont
        # from PIL import ImageColor
        # import RPi.GPIO as GPIO
        from time import time, sleep
        import datetime
        import logging
        # import socket
        import redis
    # Load default font.
        font = ImageFont.load_default()
    # Display width/height
        width = 128
        height = 128
    # First define some constants to allow easy resizing of shapes.
        padding = 0
        top = padding
        # bottom = height-padding
    # Move left to right keeping track of the current x position for drawing shapes.
        x = 0

        logging.basicConfig(filename='/tmp/rpims_serial_display.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s')
        logger = logging.getLogger(__name__)
        display_rotate = kwargs['serial_display_rotate']
        serial = spi(device=0, port=0, bus_speed_hz=8000000, transfer_size=4096, gpio_DC=25, gpio_RST=27)

        try:
            device = st7735(serial)
            device = st7735(serial, width=128, height=128, h_offset=1, v_offset=2, bgr=True, persist=False, rotate=display_rotate)

            while True:
                # get data from redis db
                values = redis_db.mget('BME280_Temperature', 'BME280_Humidity', 'BME280_Pressure', 'GPIO_5', 'GPIO_6', 'CPU_Temperature', 'hostip')

                t,h,p = values[0], values[1], values[2]
                if t == None or h == None or p == None:
                    temperature = '--.--'
                    humidity = '--.--'
                    pressure = '--.--'
                elif t.replace('.','',1).isdigit() and h.replace('.','',1).isdigit() and p.replace('.','',1).isdigit():
                    temperature = round(float(t), 1)
                    humidity = int(round(float(h), 1))
                    pressure = int(round(float(p), 1))

                door_sensor_1, door_sensor_2  = values[3], values[4]
                if door_sensor_1 == None or door_sensor_2 == None:
                    door_sensor_1 = '-----'
                    door_sensor_2 = '-----'

                cputemp = values[5]
                if cputemp == None:
                    cputemp = '-----'
                else:
                    cputemp = round(float(cputemp), 1)

                hostip = values[6]
                if hostip == None:
                    hostip = '---.---.---.---'

                now = datetime.datetime.now()
                # Draw
                with canvas(device) as draw:
                    draw.text((x+35, top), 'R P i M S', font=font, fill="cyan")
                    draw.text((x, top+15), ' Temperature', font=font, fill="lime")
                    # draw.text((x+71, top+15),'', font=font, fill="blue")
                    draw.text((x+77, top+15), str(temperature) + ' *C', font=font, fill="lime")

                    draw.text((x, top+28), ' Humidity',  font=font, fill="lime")
                    # draw.text((x+70, top+28),'', font=font, fill="blue")
                    draw.text((x+77, top+28), str(humidity) + ' %',  font=font, fill="lime")

                    draw.text((x, top+41), ' Pressure',  font=font, fill="lime")
                    # draw.text((x+70, top+41),'', font=font, fill="blue")
                    draw.text((x+77, top+41), str(pressure) + ' hPa',  font=font, fill="lime")

                    draw.text((x, top+57), ' Door 1',  font=font, fill="yellow")
                    # draw.text((x+70, top+57),'', font=font, fill="yellow")
                    draw.text((x+77, top+57), str(door_sensor_1),  font=font, fill="yellow")

                    draw.text((x, top+70), ' Door 2',  font=font, fill="yellow")
                    # draw.text((x+70, top+70),'', font=font, fill="yellow")
                    draw.text((x+77, top+70), str(door_sensor_2),  font=font, fill="yellow")

                    draw.text((x, top+86), ' CPUtemp',  font=font, fill="cyan")
                    draw.text((x+77, top+86), str(cputemp) + " *C",  font=font, fill="cyan")

                    draw.text((x, top+99), ' IP', font=font, fill="cyan")
                    draw.text((x+17, top+99), ':', font=font, fill="cyan")
                    draw.text((x+36, top+99), str(hostip), font=font, fill="cyan")

                    draw.text((x+5, top+115), now.strftime("%Y-%m-%d %H:%M:%S"),  font=font, fill="floralwhite")

                sleep(1/kwargs['serial_display_refresh_rate'])
        except Exception as err:
            logger.error(err)
Beispiel #43
0
def invert(draw,x,y,text):
    font = ImageFont.load_default()
    draw.rectangle((x, y, x+120, y+10), outline=255, fill=255)
    draw.text((x, y), text, font=font, outline=0,fill="black")
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               clss=None,
                               thickness=4,
                               expansion=0,
                               display_str_list=(),
                               use_normalized_coordinates=True,
                               label_font_size=16):
    """
    Adds a bounding box to an image.

    Bounding box coordinates can be specified in either absolute (pixel) or
    normalized coordinates by setting the use_normalized_coordinates argument.

    Each string in display_str_list is displayed on a separate line above the
    bounding box in black text on a rectangle filled with the input 'color'.
    If the top of the bounding box extends to the edge of the image, the strings
    are displayed below the bounding box.

    Args:
    image: a PIL.Image object.
    ymin: ymin of bounding box - upper left.
    xmin: xmin of bounding box.
    ymax: ymax of bounding box.
    xmax: xmax of bounding box.
    clss: str, the class of the object in this bounding box - will be cast to an int.
    thickness: line thickness. Default value is 4.
    expansion: number of pixels to expand bounding boxes on each side.  Default is 0.
    display_str_list: list of strings to display in box
        (each to be shown on its own line).
        use_normalized_coordinates: If True (default), treat coordinates
        ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
        coordinates as absolute.
    label_font_size: font size to attempt to load arial.ttf with
    """
    if clss is None:
        color = COLORS[1]
    else:
        color = COLORS[int(clss) % len(COLORS)]

    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size
    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)

    if expansion > 0:
        left -= expansion
        right += expansion
        top -= expansion
        bottom += expansion

    draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)

    try:
        font = ImageFont.truetype('arial.ttf', label_font_size)
    except IOError:
        font = ImageFont.load_default()

    # If the total height of the display strings added to the top of the bounding
    # box exceeds the top of the image, stack the strings below the bounding box
    # instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]

    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height

    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)

        draw.rectangle(
            [(left, text_bottom - text_height - 2 * margin), (left + text_width,
                                                              text_bottom)],
            fill=color)

        draw.text(
            (left + margin, text_bottom - text_height - margin),
            display_str,
            fill='black',
            font=font)

        text_bottom -= (text_height + 2 * margin)
Beispiel #45
0
    def _lcd_print(self, report, txt=None):
        self._lcd.acquire()
        """Print messages to OLED 128x32"""
        dataoled = get_oled_options()

        #define RST pin
        adr = dataoled['adress']
        #configure display settings
        disp = Adafruit_SSD1306.SSD1306_128_32(
            rst=int(adr), gpio=GPIO.get_platform_gpio(mode=RPi.GPIO.BOARD))

        disp.begin()
        disp.clear()
        disp.display()
        width = disp.width
        height = disp.height
        image = Image.new('1', (width, height))
        draw = ImageDraw.Draw(image)
        draw.rectangle((0, 0, width, height), outline=0, fill=0)
        padding = -2
        top = padding
        bottom = height - padding
        x = 0
        font = ImageFont.load_default()

        if report == 'name':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Name: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.sd['name']), font=font, fill=255)
            draw.text((x, top + 16), "Irrigation syst.", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('SIP. / Irrigation syst.')
        elif report == 'd_sw_version':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Software SIP: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.ver_date), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Software SIP: / ' + gv.ver_date)
        elif report == 'd_ip':
            ip = get_ip()
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "My IP is: ", font=font, fill=255)
            draw.text((x, top + 8), str(ip), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('My IP is: / ' + str(ip))
        elif report == 'd_port':
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Port IP: ", font=font, fill=255)
            draw.text((x, top + 8), str(gv.sd['htp']), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Port IP: / {}'.format(gv.sd['htp']))
        elif report == 'd_cpu_temp':
            temp = get_cpu_temp(gv.sd['tu']) + ' ' + gv.sd['tu']
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "CPU temperature: ", font=font, fill=255)
            draw.text((x, top + 8), str(temp), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('CPU temperature: / ' + temp)
        elif report == 'd_date_time':
            da = time.strftime('%d.%m.%Y', time.gmtime(gv.now))
            ti = time.strftime('%H:%M:%S', time.gmtime(gv.now))

            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Date Time: ", font=font, fill=255)
            draw.text((x, top + 8), str(da), font=font, fill=255)
            draw.text((x, top + 16), str(ti), font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status(da + ' ' + ti)
        elif report == 'd_uptime':
            up = uptime()
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "System run Time: ", font=font, fill=255)
            draw.text((x, top + 8), str(up), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('System run time: / ' + up)
        elif report == 'd_rain_sensor':
            if gv.sd['rs']:
                rain_sensor = "Active"
            else:
                rain_sensor = "Inactive"
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Rain sensor: ", font=font, fill=255)
            draw.text((x, top + 8), str(rain_sensor), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('Rain sensor: / ' + rain_sensor)
        elif report == 'd_running_stations':  # Report running Stations
            if gv.pon is None:
                prg = 'Idle'
            elif gv.pon == 98:  # something is running
                prg = 'Run-once'
            elif gv.pon == 99:
                prg = 'Manual Mode'
            else:
                prg = "Prog: {}".format(gv.pon)

            s = ""
            if prg != "Idle":
                # Get Running Stations from gv.ps
                for i in range(len(gv.ps)):
                    p, d = gv.ps[i]
                    if p != 0:
                        s += "S{} ".format(str(i + 1))
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "Running Stations: ", font=font, fill=255)
            draw.text((x, top + 8), str(prg), font=font, fill=255)
            draw.text((x, top + 16), str(s), font=font, fill=255)
            disp.image(image)
            disp.display()
        elif report == 'd_alarm_signal':  # ALARM!!!!
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "ALARM!: ", font=font, fill=255)
            draw.text((x, top + 8), str(txt), font=font, fill=255)
            draw.text((x, top + 16), "", font=font, fill=255)
            disp.image(image)
            disp.display()
        elif report == 'd_stat_schedule_signal':  # A program has been scheduled
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x, top), "New program: ", font=font, fill=255)
            draw.text((x, top + 8), "Running", font=font, fill=255)
            draw.text((x, top + 16), "...", font=font, fill=255)
            disp.image(image)
            disp.display()
            self.add_status('New Program Running / ')
        self._lcd.release()
Beispiel #46
0
    async def draw_text(
            self,
            # Same PIL options
            xy: tuple,
            text: str,
            font=None,
            spacing: int = 4,

            # Parser options
            with_url_check: bool = True,
            clear_cache_after_usage: bool = False,
            *args,
            **kwargs) -> None:
        """
        Draws a text with the emoji.
        clear_cache_after_usage will clear the cache after this method is finished. (defaults to False)
        """

        _parsed_text = await self.__parse_text(text, with_url_check)
        _font = font or ImageFont.load_default()
        _font_size = getattr(_font, "size", 11)
        _, _font_descent = font.getmetrics()
        _current_x, _current_y = xy[0], xy[1]
        _origin_x = xy[0]
        if self.parse_discord_emoji:
            _parsed_text = await parse_custom_emoji(_parsed_text,
                                                    self.__session)

        if not [i for i in _parsed_text if self.__is_emoji_url(i)]:
            self.draw.text(xy,
                           text,
                           font=font,
                           spacing=spacing,
                           *args,
                           **kwargs)
        else:
            for word in _parsed_text:
                if self.__is_emoji_url(word):
                    # check if image is in cache
                    if word in self._image_cache:
                        _emoji_im = self._image_cache[word].copy()
                    else:
                        _emoji_im = await self.__image_from_url(word)
                        _emoji_im = _emoji_im.resize(
                            (_font_size - _font_size // 6,
                             _font_size - _font_size // 6),
                            Image.ANTIALIAS).convert("RGBA")
                        self._image_cache[word] = _emoji_im.copy()

                    self.image.paste(_emoji_im,
                                     (_current_x, _current_y + _font_descent -
                                      _font_descent // 3), _emoji_im)
                    _current_x += _font_size + _font_descent + (
                        spacing - (_font_size // 6 + _font_descent))
                    continue

                _size = _font.getsize(word.replace("\n", ""))
                if word.count("\n") > 0:
                    _current_x = _origin_x - spacing
                    _current_y += (_font_size * word.count("\n"))
                self.draw.text((_current_x, _current_y),
                               word,
                               font=font,
                               *args,
                               **kwargs)
                _current_x += _size[0] + spacing

        if clear_cache_after_usage:
            await self.close(
                delete_all_attributes=bool(kwargs.get("delete_all_attributes"))
            )
Beispiel #47
0
except FileNotFoundError:
   s.HAS_DISPLAY=False
   s.BUS_ERROR=True
   logging.error("[display.py]  : Cannot access /dev/i2c-%d"  % (OLED_BUS))


#Fonts [filepaths in settings.py]
try:
    mono_small = ImageFont.truetype(s.SMALL_MONO,8)
    small_font = ImageFont.truetype(s.SMALL_FONT, 8)
    small_font_bold = ImageFont.truetype(s.SMALL_BOLD, 8)
    medium_font = ImageFont.truetype(s.LARGE_FONT,16)
    large_font = ImageFont.truetype(s.LARGE_FONT,24)
except OSError:
    logging.error("Can't read font files");
    mono_small = ImageFont.load_default()
    small_font = ImageFont.load_default()
    small_font_bold = ImageFont.load_default()
    medium_font = ImageFont.load_default()
    large_font = ImageFont.load_default()


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

# Clear display.
def clear():
    """A function to clear the display"""
    'LightGray', 'LightGrey', 'LightGreen', 'LightPink', 'LightSalmon',
    'LightSeaGreen', 'LightSkyBlue', 'LightSlateGray', 'LightSlateGrey',
    'LightSteelBlue', 'LightYellow', 'Lime', 'LimeGreen', 'Linen', 'Magenta',
    'MediumAquaMarine', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen',
    'MediumSlateBlue', 'MediumSpringGreen', 'MediumTurquoise',
    'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite',
    'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid',
    'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',
    'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',
    'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',
    'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',
    'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue',
    'GreenYellow', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat',
    'White', 'WhiteSmoke', 'Yellow', 'YellowGreen', 'LightBlue', 'LightGreen'
]
FONT = ImageFont.load_default()


def find_head_edge(box, head):
    head_dict = {0: '11', 1: '10', 2: '00', 3: '01'}
    flag = head_dict[int(head)]
    box_eight = forward_convert(np.array([box]), False)[0]
    box_eight = np.reshape(box_eight, [4, 2])
    four_edges = [[box_eight[0], box_eight[1]], [box_eight[1], box_eight[2]],
                  [box_eight[2], box_eight[3]], [box_eight[3], box_eight[0]]]
    for i in range(4):
        center_x = (four_edges[i][0][0] + four_edges[i][1][0]) / 2.
        center_y = (four_edges[i][0][1] + four_edges[i][1][1]) / 2.
        if (center_x - box[0]) >= 0 and (center_y - box[1]) >= 0:
            res = '11'
            if res == flag:
Beispiel #49
0
    def __init__(self):
        # Raspberry Pi pin configuration:
        self.RST = None  # on the PiOLED this pin isnt used
        # Note the following are only used with SPI:
        self.DC = 23
        self.SPI_PORT = 0
        self.SPI_DEVICE = 0

        # Beaglebone Black pin configuration:
        # RST = 'P9_12'
        # Note the following are only used with SPI:
        # DC = 'P9_15'
        # SPI_PORT = 1
        # SPI_DEVICE = 0

        # 128x32 display with hardware I2C:
        self.disp = Adafruit_SSD1306.SSD1306_128_32(rst=self.RST)

        # 128x64 display with hardware I2C:
        # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

        # Note you can change the I2C address by passing an i2c_address parameter like:
        # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)

        # Alternatively you can specify an explicit I2C bus number, for example
        # with the 128x32 display you would use:
        # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)

        # 128x32 display with hardware SPI:
        # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

        # 128x64 display with hardware SPI:
        # disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, dc=DC, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=8000000))

        # Alternatively you can specify a software SPI implementation by providing
        # digital GPIO pin numbers for all the required display pins.  For example
        # on a Raspberry Pi with the 128x32 display you might use:
        # disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, dc=DC, sclk=18, din=25, cs=22)

        # Initialize library.
        self.disp.begin()

        # Clear display.
        self.disp.clear()
        self.disp.display()

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

        # Get drawing object to draw on image.
        self.draw = ImageDraw.Draw(self.image)

        # Draw a black filled box to clear the image.
        self.draw.rectangle((0, 0, self.width, self.height), outline=0, fill=0)

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

        # Load default font.
        self.fontE = ImageFont.load_default()
        self.fontJ = ImageFont.truetype('fonts-japanese-gothic.ttf', 12)

        # Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
        # Some other nice fonts to try: http://www.dafont.com/bitmap.php
        # font = ImageFont.truetype('Minecraftia.ttf', 8)
        self.cmd = "hostname -I | cut -d\' \' -f1"
        self.IP = subprocess.check_output(self.cmd, shell=True)
        self.draw.text((self.x, self.top),
                       "IP: " + str(self.IP),
                       font=self.fontE,
                       fill=255)
        self.disp.image(self.image)
        self.disp.display()
Beispiel #50
0
def draw_bounding_boxes(
    image: torch.Tensor,
    boxes: torch.Tensor,
    labels: Optional[List[str]] = None,
    colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str,
                           Tuple[int, int, int]]] = None,
    fill: Optional[bool] = False,
    width: int = 1,
    font: Optional[str] = None,
    font_size: int = 10,
) -> torch.Tensor:
    """
    Draws bounding boxes on given image.
    The values of the input image should be uint8 between 0 and 255.
    If fill is True, Resulting Tensor should be saved as PNG image.

    Args:
        image (Tensor): Tensor of shape (C x H x W) and dtype uint8.
        boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
            the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
            `0 <= ymin < ymax < H`.
        labels (List[str]): List containing the labels of bounding boxes.
        colors (color or list of colors, optional): List containing the colors
            of the boxes or single color for all boxes. The color can be represented as
            PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
            By default, random colors are generated for boxes.
        fill (bool): If `True` fills the bounding box with specified color.
        width (int): Width of bounding box.
        font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
            also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
            `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
        font_size (int): The requested font size in points.

    Returns:
        img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
    """

    if not torch.jit.is_scripting() and not torch.jit.is_tracing():
        _log_api_usage_once(draw_bounding_boxes)
    if not isinstance(image, torch.Tensor):
        raise TypeError(f"Tensor expected, got {type(image)}")
    elif image.dtype != torch.uint8:
        raise ValueError(f"Tensor uint8 expected, got {image.dtype}")
    elif image.dim() != 3:
        raise ValueError("Pass individual images, not batches")
    elif image.size(0) not in {1, 3}:
        raise ValueError("Only grayscale and RGB images are supported")

    num_boxes = boxes.shape[0]

    if labels is None:
        labels: Union[List[str],
                      List[None]] = [None
                                     ] * num_boxes  # type: ignore[no-redef]
    elif len(labels) != num_boxes:
        raise ValueError(
            f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box."
        )

    if colors is None:
        colors = _generate_color_palette(num_boxes)
    elif isinstance(colors, list):
        if len(colors) < num_boxes:
            raise ValueError(
                f"Number of colors ({len(colors)}) is less than number of boxes ({num_boxes}). "
            )
    else:  # colors specifies a single color for all boxes
        colors = [colors] * num_boxes

    colors = [(ImageColor.getrgb(color) if isinstance(color, str) else color)
              for color in colors]

    # Handle Grayscale images
    if image.size(0) == 1:
        image = torch.tile(image, (3, 1, 1))

    ndarr = image.permute(1, 2, 0).cpu().numpy()
    img_to_draw = Image.fromarray(ndarr)
    img_boxes = boxes.to(torch.int64).tolist()

    if fill:
        draw = ImageDraw.Draw(img_to_draw, "RGBA")
    else:
        draw = ImageDraw.Draw(img_to_draw)

    txt_font = ImageFont.load_default(
    ) if font is None else ImageFont.truetype(font=font, size=font_size)

    for bbox, color, label in zip(img_boxes, colors,
                                  labels):  # type: ignore[arg-type]
        if fill:
            fill_color = color + (100, )
            draw.rectangle(bbox, width=width, outline=color, fill=fill_color)
        else:
            draw.rectangle(bbox, width=width, outline=color)

        if label is not None:
            margin = width + 1
            draw.text((bbox[0] + margin, bbox[1] + margin),
                      label,
                      fill=color,
                      font=txt_font)

    return torch.from_numpy(np.array(img_to_draw)).permute(
        2, 0, 1).to(dtype=torch.uint8)
Beispiel #51
0
    def __init__(self):
        # ----
        EdgeService.__init__(self)
        # ----
        self.RST = None  # on the PiOLED this pin isnt used
        self.display_connected = False
        self.interligne = 8
        self.line_one = "Starting ..."
        self.line_two = ""
        self.line_three = ""
        self.line_four = ""
        self.line_five = ""
        self.line_six = ""
        self.line_seven = ""
        self.line_eight = ""

        self.power_on = True
        # 128x64 display with hardware I2C:
        self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=self.RST)

        try:
            # Initialize library.
            self.disp.begin()

            # Clear display.
            self.disp.clear()
            self.disp.display()

            # Create blank image for drawing.
            # Make sure to create image with mode '1' for 1-bit color.
            self.width = self.disp.width
            self.height = self.disp.height

            self.image = Image.new('1', (self.width, self.height))

            # Get drawing object to draw on image.
            self.draw = ImageDraw.Draw(self.image)

            # Draw a black filled box to clear the image.
            self.draw.rectangle((0, 0, self.width, self.height),
                                outline=0,
                                fill=0)

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

            # Load default font.
            self.font = ImageFont.load_default()

            # Alternatively load a TTF font.  Make sure the .ttf font file is in the same directory as the python script!
            # Some other nice fonts to try: http://www.dafont.com/bitmap.php
            # font = ImageFont.truetype('Minecraftia.ttf', 8)

            self.display_connected = True

        except OSError:
            self.display_connected = False
            print("no display")
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               clss=None,
                               thickness=4,
                               expansion=0,
                               display_str_list=(),
                               use_normalized_coordinates=True,
                               label_font_size=16):
    """
    Adds a bounding box to an image.

    Bounding box coordinates can be specified in either absolute (pixel) or
    normalized coordinates by setting the use_normalized_coordinates argument.

    Each string in display_str_list is displayed on a separate line above the
    bounding box in black text on a rectangle filled with the input 'color'.
    If the top of the bounding box extends to the edge of the image, the strings
    are displayed below the bounding box.

    Args:
    image: a PIL.Image object.
    ymin: ymin of bounding box - upper left.
    xmin: xmin of bounding box.
    ymax: ymax of bounding box.
    xmax: xmax of bounding box.
    clss: str, the class of the object in this bounding box - will be cast to an int.
    thickness: line thickness. Default value is 4.
    expansion: number of pixels to expand bounding boxes on each side.  Default is 0.
    display_str_list: list of strings to display in box
        (each to be shown on its own line).
        use_normalized_coordinates: If True (default), treat coordinates
        ymin, xmin, ymax, xmax as relative to the image.  Otherwise treat
        coordinates as absolute.
    label_font_size: font size to attempt to load arial.ttf with
    """
    if clss is None:
        color = COLORS[1]
    else:
        color = COLORS[int(clss) % len(COLORS)]

    draw = ImageDraw.Draw(image)
    im_width, im_height = image.size
    if use_normalized_coordinates:
        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                                      ymin * im_height, ymax * im_height)
    else:
        (left, right, top, bottom) = (xmin, xmax, ymin, ymax)

    if expansion > 0:
        left -= expansion
        right += expansion
        top -= expansion
        bottom += expansion

        # Deliberately trimming to the width of the image only in the case where
        # box expansion is turned on.  There's not an obvious correct behavior here,
        # but the thinking is that if the caller provided an out-of-range bounding
        # box, they meant to do that, but at least in the eyes of the person writing
        # this comment, if you expand a box for visualization reasons, you don't want
        # to end up with part of a box.
        #
        # A slightly more sophisticated might check whether it was in fact the expansion
        # that made this box larger than the image, but this is the case 99.999% of the time
        # here, so that doesn't seem necessary.
        left = max(left,0); right = max(right,0)
        top = max(top,0); bottom = max(bottom,0)

        left = min(left,im_width-1); right = min(right,im_width-1)
        top = min(top,im_height-1); bottom = min(bottom,im_height-1)

    draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)

    try:
        font = ImageFont.truetype('arial.ttf', label_font_size)
    except IOError:
        font = ImageFont.load_default()

    # If the total height of the display strings added to the top of the bounding
    # box exceeds the top of the image, stack the strings below the bounding box
    # instead of above.
    display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]

    # Each display_str has a top and bottom margin of 0.05x.
    total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)

    if top > total_display_str_height:
        text_bottom = top
    else:
        text_bottom = bottom + total_display_str_height

    # Reverse list and print from bottom to top.
    for display_str in display_str_list[::-1]:
        text_width, text_height = font.getsize(display_str)
        margin = np.ceil(0.05 * text_height)

        draw.rectangle(
            [(left, text_bottom - text_height - 2 * margin), (left + text_width,
                                                              text_bottom)],
            fill=color)

        draw.text(
            (left + margin, text_bottom - text_height - margin),
            display_str,
            fill='black',
            font=font)

        text_bottom -= (text_height + 2 * margin)