Esempio n. 1
0
def main():
    parser = argparse.ArgumentParser(description='Generate random Arch wallpaper')
    parser.add_argument('-o','--output', help='Output file name', required=True)
    parser.add_argument('-t','--theme', default=get_random_theme(),
            help='The theme to use, else random. \'black\', \'solarized\', \'standart\' or \'inverted\'', required=False)
    parser.add_argument('--text', default=get_random_text(), help='Text on the picture, or random', required=False)
    parser.add_argument('-r', '--resolution', default=(1920,1080), help='Sets the resolution of the image. Example: 1920x1080', required=False)
    parser.add_argument('-ts', '--text-scale', default=(1.0), help='Sets scale for the text. Example: 1.75', required=False)
    parser.add_argument('-ls', '--logo-scale', default=(1.0), help='Sets scale for the logo. Example: 3.0', required=False)
    parser.add_argument('-fg', '--foreground-color', type=str, help='Color for the text and the logo.', required=False)
    parser.add_argument('-bg', '--background-color', type=str, help='Color for the background.', required=False)
    args = vars(parser.parse_args())

    output = args["output"]

    if isinstance(args["theme"], str):
        args["theme"] = themes[args["theme"]]

    if isinstance(args["resolution"], str):
        x,y = args["resolution"].split("x")
        args["resolution"] = (int(x),int(y))

    if args.get("foreground_color"):
        try:
            args["theme"]["text"] = ImageColor.getrgb(args["foreground_color"])
        except: pass

    if args.get("background_color"):
        try:
            args["theme"]["background"] = ImageColor.getrgb(args["background_color"])
        except: pass


    generate_img(output=output, theme=args["theme"], text=args["text"], resolution=args["resolution"],
        text_scale=float(args["text_scale"]), logo_scale=float(args["logo_scale"]))
Esempio n. 2
0
File: data.py Progetto: lhang/TDOA
def make_check_code_image(image=''):

	color = ImageColor.getrgb('white')
	#im = Image.open(image)
	im = Image.new('RGB',(60,20), color) 
	draw = ImageDraw.Draw(im)
	import hashlib
	mp = hashlib.md5()
	mp_src = mp.update(str(datetime.datetime.now())) 
	mp_src = mp.hexdigest()

	rand_str = mp_src[0:4] 
	#print rand_str
	color = ImageColor.getrgb('LightGray')
	for i in range(200):
		x = random.randrange(1,60)
		y = random.randrange(1,20)
		draw.point((x, y), fill=color)
    
	draw.text((5,1), rand_str[0], fill=get_color(), font=get_font())
	draw.text((15,1), rand_str[1], fill=get_color(), font=get_font())
	draw.text((30,1), rand_str[2], fill=get_color(), font=get_font())
	draw.text((45,1), rand_str[3], fill=get_color(), font=get_font())
	
	draw.line((0,10,60,15), fill=get_color())
	
	del draw 
	
	# session['checkcode'] = rand_str 
	#print request.session['checkcode'] 
	buf = StringIO.StringIO()   
	im.save(buf, 'gif')
	buf.closed
	if image: im.save(image) 
	return rand_str, buf.getvalue()
def image_placeholder(param):
    fontfile = '/usr/share/fonts/X11/TTF/arialbd.ttf'
    minsize = 5
    maxsize = 500

    try:
        param['width'] = int(param['width'])
    except:
        param['width'] = 640

    try:
        param['height'] = int(param['height'])
    except:
        param['height'] = 480

    try:
        ImageColor.getrgb(param['front'])
    except:
        param['front'] = '#666'

    try:
        ImageColor.getrgb(param['back'])
    except:
        param['back'] = '#999'

    if not param.get('text'):
        param['text'] = '%(width)s x %(height)s'

    try:
        param['text'] = param['text'] % param
    except:
        param['text'] = 'placeholder'

    img = Image.new('RGB', (param['width'], param['height']))
    draw = ImageDraw.Draw(img)
    draw.rectangle(((0, 0), (param['width'], param['height'])), fill=param['back'])

    size = (maxsize + minsize) / 2
    while size != minsize and size != maxsize:
        font = ImageFont.truetype(fontfile, size)
        textsize = draw.textsize(param['text'], font=font)

        if (textsize[0] == param['width'] and textsize[1] <= param['height']) \
        or (textsize[0] <= param['width'] and textsize[1] == param['height']):
            break

        if textsize[0] > param['width'] or textsize[1] > param['height']:
            maxsize = size
        else:
            minsize = size

        size = (maxsize + minsize) / 2

    if size:
        font = ImageFont.truetype(fontfile, size)
        textsize = draw.textsize(param['text'], font=font)

        draw.text((param['width'] / 2 - textsize[0] / 2, param['height'] / 2 - textsize[1] / 2), param['text'], fill=param['front'], font=font)

    return img
Esempio n. 4
0
def rainbodl(api):
    try:
        conf = expect_conf("rainbodl", {"path": None, "change_profile_color": True})
    except ConfNotValid:
        print("Please fill in the location of the image(s) in %s" % (conf_file,), file=sys.stderr)
        exit(1)

    sourcefile = os.path.expanduser(conf['path'])
    if(stat.S_ISDIR(os.stat(sourcefile).st_mode)):
        sourcefile += os.sep + random.choice(os.listdir(sourcefile))

    _, filename = tempfile.mkstemp(suffix='.png')

    im = Image.open(sourcefile)
    im = im.convert(mode="RGBA")

    size = im.size
    hue = random.randint(0, 360);
    avcolor = ImageColor.getrgb("hsl(%s,100%%,70%%)" % (hue,))
    linkcolor = ImageColor.getrgb("hsl(%s,100%%,40%%)" % (hue,))

    background = Image.new("RGBA", size, avcolor)

    final = Image.alpha_composite(background, im)

    final.save(filename)

    set_avatar(api, filename)

    if conf['change_profile_color']:
        api.update_profile(profile_link_color=rgb_tuple_to_hex(linkcolor))

    os.unlink(filename)
Esempio n. 5
0
    def get_top(self, *, x=0, y=0, z=0):
        config = state.get_config()
        tex_base = config.resource_path / self.namespace / "textures"

        side, rotation = _resolve_side_rotation(x, y, z)
        if side is None or rotation is None:
            raise ArithmeticError("Invalid block rotation")

        blank = Image.new("RGBA", (config.block_size, config.block_size), Color.getrgb("white"))
        out = Image.new("RGBA", (config.block_size, config.block_size), Color.getrgb("white"))
        for element in self.elements:
            face = element.get_face(side)
            if face is None:
                continue
            axis = side.axis
            factor = _resolve_darken(element, axis)
            tex = self.get_texture(face.texture)
            if tex is None:
                print(f"Resolved texture for model {self.namespace}:{self.name} is invalid: {face.texture}")
                return None
            img = Image.open(tex_base / (tex + ".png"))
            img.crop(_resolve_uv(element, face, side))
            img = Enhance.Brightness(img).enhance(factor)
            # Add the correct portion of the texture based on cube and depth
            mask = None
            if img.mode == "RGBA":
                mask = img.split()[3]
            out.paste(img, mask=mask)
        if out == blank:
            return None

        out = out.rotate(rotation)
        return out
Esempio n. 6
0
    def draw_baselines(self, img_in):
        img_out = img_in.copy()
        draw = ImageDraw.Draw(img_out)
    
        prev_floor = 0
        w, h = img_out.size
    
        gap_color = ImageColor.getrgb('#ccccFF')
    
        lines = scrape.calc_lines(scrape.font_metrics(), 7)

        for i, (ceiling, base, floor) in enumerate(lines):

            # draw the baseline
            color = ImageColor.getrgb("#ffdddd")
            if not base:
                base = floor -2
                color = ImageColor.getrgb("red")
    
            draw.line([(0, base), (w, base)], fill=color)
            
            # shade gap between the lines
            draw.rectangle((0, prev_floor, w, ceiling), fill=gap_color)
            prev_floor = floor +1
                
        # shade final gap:
        draw.rectangle((0, prev_floor, w, h), fill=gap_color)
    
        # now draw the text back over the baselines:
        img_out = ImageChops.darker(img_in, img_out)

        # uncomment to zoom in for debugging
        # img_out = img_out.resize((w *2 , h* 2))

        return img_out
Esempio n. 7
0
 def __init__(self, font_path, background='#000000', foreground='#ffffff'):
     self.font = ImageFont.load(font_path)
     self.background = ImageColor.getrgb(background)
     self.foreground = ImageColor.getrgb(foreground)
     self.line_space = 2
     self.border = 10
     _, self.line_height = self.font.getsize('Mj')
def mask_num_circle(image_s, num=0):
    """
    为头像图片添加未读信息提示
    :param image_s: 头像图片PIL.Image对象
    :param num: 未读信息条数
    :return: PIL.Image对象,添加未读信息标示的头像图片
    """
    # 底层背景
    size_x, size_y = image_s.size
    padding_x, padding_y = size_x//15, size_y//15  # 预留padding
    im_size_x, im_size_y = size_x+padding_x, size_y+padding_y  # 背景的大小
    image_t = Image.new("RGBA", (im_size_x, im_size_y), color=(0, 0, 0, 0))  # 0才是透明

    # 贴入原图
    image_t.paste(image_s, (0, padding_y, size_x, im_size_y))

    # 画圆
    diameter = min(size_x, size_y)//3  # 圆的直径
    radius = diameter//2  # 圆的不精确半径
    color_red = ImageColor.getrgb('red')
    draw = ImageDraw.Draw(image_t)
    draw.ellipse([(im_size_x - diameter, 0), (im_size_x, diameter)], fill=color_red, outline=color_red)
    # 在圆上画数字
    num = str(num)
    color_white = ImageColor.getrgb('white')
    font = ImageFont.truetype(font="arial.ttf", size=radius)  # 设置字体大小为半径值
    font_size = font.getsize(num)  # 获取写入内容的大小
    font_x, font_y = font_size[0]//2 + font_size[0]//100, font_size[1]//2 + font_size[1]//10  # 估计margin或padding宽度
    text_position = (im_size_x - radius - font_x, radius - font_y)  # 尽量让文本画在中心
    draw.text(text_position, num, font=font, fill=color_white)
    return image_t
Esempio n. 9
0
File: Drawer.py Progetto: c-math/AI
 def __init__(self, cells, pixel, colormap=None):
     self.cells      = cells
     self.pixel      = pixel
     self.colormap   = colormap
     self.black      = ImageColor.getrgb('black')
     self.white      = ImageColor.getrgb('white')
     self.size       = self.dot((len(cells[0]), len(cells)), pixel)
     self.image      = Image.new('RGB', self.size)
     self.drawer     = ImageDraw.Draw(self.image)
     self.draw()
Esempio n. 10
0
    def __init__(self, fgcolor=DEFAULT_FGCOLOR, bgcolor=DEFAULT_BGCOLOR, *args, **kwargs):
        super(TinyTime, self).__init__(*args, **kwargs)

        self._fgcolor = ImageColor.getrgb(fgcolor)
        self._bgcolor = ImageColor.getrgb(bgcolor)

        width, height = self._buf.size
        self._font = ImageFont.truetype(DEFAULT_FONT, int(height / 2.5))

        self.draw(self._provider.provide())
Esempio n. 11
0
 def __call__(self, parser, namespace, values, option_string=None):
     orig = ImageColor.getrgb(values[0])
     new = None
     if values[1]!='nil':
         new = ImageColor.getrgb(values[1])
     pcolors = [(orig,new)]
     if not getattr(namespace,self.dest):
         setattr(namespace,self.dest,[])
     ogod = getattr(namespace, self.dest)
     ogod += pcolors
     print('%r -> %r' % (values, pcolors))
Esempio n. 12
0
    def __init__(self, width, height, outline, fill=None):
        self.width = width
        self.height = height

        if outline:
            self.outline = ImageColor.getrgb(outline)
        else:
            self.outline = None

        if fill:
            self.fill = ImageColor.getrgb(fill)
        else:
            self.fill = None
Esempio n. 13
0
 def test_sanity(self):
     self.assertEqual((255, 0, 0), ImageColor.getrgb("#f00"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("#ff0000"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
     self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
     self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
     self.assertEqual((255, 0, 0), ImageColor.getrgb("red"))
Esempio n. 14
0
    def test_sanity(self):
        self.assertEqual((255, 0, 0), ImageColor.getrgb("#f00"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("#ff0000"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
        self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
        self.assertEqual(
            (255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("red"))

        self.assertRaises(ValueError,
                          lambda: ImageColor.getrgb("invalid color"))
Esempio n. 15
0
    def __init__(self,
            fgcolor=DEFAULT_FGCOLOR,
            bgcolor=DEFAULT_BGCOLOR,
            *args, **kwargs):
        super(TinyWeather, self).__init__(*args, **kwargs)

        self._bgcolor = ImageColor.getrgb(bgcolor)
        self._fgcolor = ImageColor.getrgb(fgcolor)

        width, height = self._buf.size
        self._tempfont = ImageFont.truetype(DEFAULT_FONT, size=width/2)
        self._titlefont = ImageFont.truetype(DEFAULT_FONT, size=24)

        self.draw(self._provider.provide())
Esempio n. 16
0
def test_floodfill_border():
    # Arrange
    im = Image.new("RGB", (w, h))
    draw = ImageDraw.Draw(im)
    draw.rectangle(bbox2, outline="yellow", fill="green")
    centre_point = (int(w/2), int(h/2))

    # Act
    ImageDraw.floodfill(
        im, centre_point, ImageColor.getrgb("red"),
        border=ImageColor.getrgb("black"))
    del draw

    # Assert
    assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
Esempio n. 17
0
def _pillow_render_png(figure, output_file, scale_x=8, scale_y=8,
                       bg_rgb="#ffffff", fg_rgb="#000000",
                       bg_opacity=0.0, fg_opacity=1.0):
    rescale_factor = 8
    scale_x *= rescale_factor
    scale_y *= rescale_factor

    bg_opacity = min(1.0, max(0.0, bg_opacity))
    fg_opacity = min(1.0, max(0.0, fg_opacity))

    bg_alpha = int(round(bg_opacity * 255))
    fg_alpha = int(round(fg_opacity * 255))

    bg_rgba = ImageColor.getrgb(bg_rgb) + (bg_alpha,)
    fg_rgba = ImageColor.getrgb(fg_rgb) + (fg_alpha,)

    image_size = (int(math.ceil(figure.width * scale_x)),
                  int(math.ceil(figure.height * scale_y)))

    image = Image.new("RGBA", image_size, bg_rgba)
    draw = ImageDraw.Draw(image)

    font_filepath = os.path.join(os.path.dirname(__file__), "data",
                                 "DejaVuSansMono.ttf")
    font_size = int(math.ceil(2 * min(scale_x, scale_y)))
    try:
        font = ImageFont.truetype(font_filepath, font_size)
    except IOError:
        font = ImageFont.load_default()

    for line in figure.lines:
        x0, y0, x1, y1 = line
        draw.line((scale_x * x0, scale_y * y0, scale_x * x1, scale_y * y1),
                  fill=fg_rgba, width=rescale_factor)

    for text in figure.texts:
        pos, string = text
        x, y = pos
        draw.text((scale_x * x, scale_y * y), string, font=font, fill=fg_rgba)

    for polygon in figure.polygons:
        draw.polygon([(scale_x * x, scale_y * y) for x, y in polygon],
                     fill=fg_rgba, outline=fg_rgba)

    image_size = [v // rescale_factor for v in image_size]
    image = image.resize(image_size, Image.LANCZOS)

    image.save(output_file, "PNG")
Esempio n. 18
0
    def test_floodfill(self):
        red = ImageColor.getrgb("red")

        for mode, value in [
            ("L", 1),
            ("RGBA", (255, 0, 0, 0)),
            ("RGB", red)
        ]:
            # Arrange
            im = Image.new(mode, (W, H))
            draw = ImageDraw.Draw(im)
            draw.rectangle(BBOX2, outline="yellow", fill="green")
            centre_point = (int(W/2), int(H/2))

            # Act
            ImageDraw.floodfill(im, centre_point, value)

            # Assert
            expected = "Tests/images/imagedraw_floodfill_"+mode+".png"
            im_floodfill = Image.open(expected)
            self.assert_image_equal(im, im_floodfill)

        # Test that using the same colour does not change the image
        ImageDraw.floodfill(im, centre_point, red)
        self.assert_image_equal(im, im_floodfill)

        # Test that filling outside the image does not change the image
        ImageDraw.floodfill(im, (W, H), red)
        self.assert_image_equal(im, im_floodfill)

        # Test filling at the edge of an image
        im = Image.new("RGB", (1, 1))
        ImageDraw.floodfill(im, (0, 0), red)
        self.assert_image_equal(im, Image.new("RGB", (1, 1), red))
Esempio n. 19
0
	def _resize_image(self, filename, size, optimize=1):
		'''
		Resizes the image to specified width, height and force option
		'''
		WIDTH, HEIGHT = 0, 1
		from PIL import Image
		from PIL import ImageOps
		from PIL import ImageDraw
		from PIL import ImageColor
		
		img = Image.open(filename)
		if img.size[WIDTH] != size['width'] or img.size[HEIGHT] != size['height']:
			
			if self.mode[0] == -1:
				im = img
				img = Image.new("RGBA", (size['width'], size['height']))
				dr = ImageDraw.Draw(img)
				
				# if is a jpeg just draw a white rectang
				if 'jfif' in im.info:
					dr.rectangle([(-1, -1), (size['width'] + 1, size['height'] + 1)], ImageColor.getrgb("#fff"))
			
				im.thumbnail((size['width'], size['height']), Image.ANTIALIAS)
			
				x = (size['width']  - im.size[0]) / 2
				y = (size['height'] - im.size[1]) / 2
				
				img.paste(im, (x, y))
			else:
				img = ImageOps.fit(img, (size['width'], size['height']), Image.ANTIALIAS, 0, self.mode)
				
			try:
				img.save(filename, optimize=optimize)
			except IOError:
				img.save(filename)
Esempio n. 20
0
def draw_mask_on_image_array(image, mask, color='red', alpha=0.4):
  """Draws mask on an image.

  Args:
    image: uint8 numpy array with shape (img_height, img_height, 3)
    mask: a uint8 numpy array of shape (img_height, img_height) with
      values between either 0 or 1.
    color: color to draw the keypoints with. Default is red.
    alpha: transparency value between 0 and 1. (default: 0.4)

  Raises:
    ValueError: On incorrect data type for image or masks.
  """
  if image.dtype != np.uint8:
    raise ValueError('`image` not of type np.uint8')
  if mask.dtype != np.uint8:
    raise ValueError('`mask` not of type np.uint8')
  if np.any(np.logical_and(mask != 1, mask != 0)):
    raise ValueError('`mask` elements should be in [0, 1]')
  if image.shape[:2] != mask.shape:
    raise ValueError('The image has spatial dimensions %s but the mask has '
                     'dimensions %s' % (image.shape[:2], mask.shape))
  rgb = ImageColor.getrgb(color)
  pil_image = Image.fromarray(image)

  solid_color = np.expand_dims(
      np.ones_like(mask), axis=2) * np.reshape(list(rgb), [1, 1, 3])
  pil_solid_color = Image.fromarray(np.uint8(solid_color)).convert('RGBA')
  pil_mask = Image.fromarray(np.uint8(255.0*alpha*mask)).convert('L')
  pil_image = Image.composite(pil_solid_color, pil_image, pil_mask)
  np.copyto(image, np.array(pil_image.convert('RGB')))
Esempio n. 21
0
def image(spec):
    """Example URL:

    http://127.0.0.1:5000/image/size=10&angle=65.0&incr=1.05
    """
    spec_uq= urllib.parse.unquote_plus(spec)
    spec_dict = urllib.parse.parse_qs(spec_uq)
    spiral_app.logger.info( 'image spec {0!r}'.format(spec_dict) )
    try:
        angle= float(spec_dict['angle'][0])
        incr= float(spec_dict['incr'][0])
        size= int(spec_dict['size'][0])
    except Exception as e:
        return make_response('URL "{0}" is invalid'.format(spec), 403)

    # Working dir should be under Apache Home
    _, temp_name = tempfile.mkstemp('.png')

    im = Image.new('RGB', (400, 300), color=ImageColor.getrgb('white'))
    pen= Pen(im)
    spiral(pen, angle=angle, incr=incr, size=size)
    im.save(temp_name, format='png')

    # Should redirect so that Apache serves the image.
    spiral_app.logger.debug( 'image file {0!r}'.format(temp_name) )
    with open(temp_name, 'rb' ) as image_file:
        data = image_file.read()
    return (data, 200, {'Content-Type':'image/png'})
Esempio n. 22
0
 def __init__(self, imstr):
     username, d, dominants, matrix = imstr.split('|')
     self.username = username
     self.date = datetime.strptime(d, '%m%y').date()
     self.dominants = [ImageColor.getrgb(x) for x in ('#' + dominants[:6], '#' + dominants[6:])]
     self.matrix = bin(int(matrix, 16))[2+MATRIX_PADDING:]
     self.filename = 'photos/{}_{}.jpg'.format(self.username, self.date.strftime('%Y_%m'))
Esempio n. 23
0
def get_single_color_func(color):
    """Create a color function which returns a single hue and saturation with.
    different values (HSV). Accepted values are color strings as usable by
    PIL/Pillow.

    >>> color_func1 = get_single_color_func('deepskyblue')
    >>> color_func2 = get_single_color_func('#00b4d2')
    """
    old_r, old_g, old_b = ImageColor.getrgb(color)
    rgb_max = 255.
    h, s, v = colorsys.rgb_to_hsv(old_r / rgb_max, old_g / rgb_max,
                                  old_b / rgb_max)

    def single_color_func(word=None, font_size=None, position=None,
                          orientation=None, font_path=None, random_state=None):
        """Random color generation.

        Additional coloring method. It picks a random value with hue and
        saturation based on the color given to the generating function.

        Parameters
        ----------
        word, font_size, position, orientation  : ignored.

        random_state : random.Random object or None, (default=None)
          If a random object is given, this is used for generating random
          numbers.

        """
        if random_state is None:
            random_state = Random()
        r, g, b = colorsys.hsv_to_rgb(h, s, random_state.uniform(0.2, 1))
        return 'rgb({:.0f}, {:.0f}, {:.0f})'.format(r * rgb_max, g * rgb_max,
                                                    b * rgb_max)
    return single_color_func
Esempio n. 24
0
 def begin_train(self):
     if not self.result_dir.get():
         return self.alert('请先进行预处理准备教材图片')
     c=len(os.listdir(self.result_dir.get()))
     if c<3:
         return self.alert('请先进行预处理准备教材图片')
     dim = self.croppixels.get()
     w=dim
     w=int(w)
     h=w
     if(not w or not h):
         self.alert('请输入正确的切块尺寸')
         return
     
     sc = self.colortodetect.get()
     c=None
     try:
         c = ImageColor.getrgb(sc)
     except:
         pass
     
     if not c: 
         self.alert('请设置正确的颜色')
         return
     self.trainbar.start(10)
     from fire.prepare import train_fire_recognition
     Thread(target=train_fire_recognition,
            args=( self.result_dir.get(),w,h,
                  self.on_train)
            ).start()
Esempio n. 25
0
def warmup(image, midtone, brighten, amount=100):
    """Apply a toning filter. Move the midtones to the desired
    color while preserving blacks and whites with optional mixing
    with original image - amount: 0-100%"""

    mode = image.mode
    info = image.info

    if image.mode != "L":
        im = imtools.convert(image, "L")
    else:
        im = image

    if image.mode != "RGBA" and imtools.has_transparency(image):
        image = imtools.convert(image, "RGBA")

    luma = imtools.convert(imtools.split(im)[0], "F")
    o = []
    m = ImageColor.getrgb(midtone)
    b = brighten / 600.0
    # Calculate channels separately
    for l in range(3):
        o.append(ImageMath.eval("m*(255-i)*i+i", i=luma, m=4 * ((m[l] / 255.0) - 0.5 + b) / 255.0).convert("L"))

    colorized = Image.merge("RGB", tuple(o))

    if imtools.has_alpha(image):
        imtools.put_alpha(colorized, imtools.get_alpha(image))

    if amount < 100:
        colorized = imtools.blend(image, colorized, amount / 100.0)

    return colorized
Esempio n. 26
0
def image_tint(image, tint=None):
	if tint is None:
		return image
	if image.mode not in ['RGB', 'RGBA']:
		image = image.convert('RGBA')

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

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

	return Image.merge(*merge_args).point(luts)
Esempio n. 27
0
	def __init__(self,fn):
		self.dictionary=json.load(open(fn,'r'))
		sources=self.dictionary['sources']
		self.tilesize=int(self.dictionary['tilesize'])
		self.tilesources=get_tilesources(sources[0],self.tilesize) #TODO: BUG..sources should be parsed
		self.tilerefs={}
		self.name=os.path.splitext(fn)[0]
		
		for tilekey,tiles in self.tilesources.items():
			tv=[(tilekey,x) for x in range(len(tiles))]
			self.tilerefs[tilekey]=tv
			
		#TODO: verify aliases
		self.aliases=self.dictionary['aliases']
		#TODO: verify palette_aliases
		self.palette_aliases=self.dictionary['palette_aliases']		#http://pillow.readthedocs.org/en/latest/reference/ImageColor.html 
		self.npalette_aliases=dict([(ImageColor.getrgb(cstring),v) for cstring,v in self.palette_aliases.items()])
		self.outputs=self.dictionary['outputs']
		
		for o in self.outputs:
			if('invisible' in o):
				o['invisible_aliased']=alias_string(self.aliases,o['invisible'])
			if('visible' in o):
				ov=o['visible']
				if(isinstance(ov,str) or isinstance(ov,unicode)):
					ov=self.source_map_to_aliastext(ov)

				va=[]
				for v in ov:
					va.append(alias_string(self.aliases,v))
				o['visible_aliased']=va
Esempio n. 28
0
def image_tint(src, tint=None):
    r = lambda: random.randint(0,255)
    tint = tint or '#{:02X}{:02X}{:02X}'.format(r(), r(), r())
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

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

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

    return (Image.merge(*merge_args).point(luts), tint)
Esempio n. 29
0
 def do_recog(self):
     if not self.lastup_file:
         return self.alert('请打开一个要识别的图片')
     
     dim = self.croppixels.get()
     w=dim
     w=int(w)
     h=w
     if(not w or not h):
         self.alert('请输入正确的切块尺寸')
         return
     
     sc = self.colortodetect.get()
     c=None
     try:
         c = ImageColor.getrgb(sc)
     except:
         pass
     
     if not c: 
         self.alert('请设置正确的颜色')
         return
     from fire.prepare import test
     result = test(self.lastup_file,w,h,self.threshold.get(),c)
     self.testret.set('识别结果:%s' % result)
Esempio n. 30
0
 def begin_preprocess(self):
     dim = self.croppixels.get()
     w=dim
     w=int(w)
     h=w
     if(not w or not h):
         self.alert('请输入正确的切块尺寸')
         return
     if(not self.origin_dir.get()):
         self.alert('请设置素材目录')
         return
     sc = self.colortodetect.get()
     c=None
     try:
         c = ImageColor.getrgb(sc)
     except:
         pass
     
     if not c: 
         self.alert('请设置正确的颜色')
         return
     
     self.prebar.start(10)
     from fire.prepare import batch_preprocess
     Thread(target=batch_preprocess,
            args=(self.origin_dir.get(), self.result_dir.get(),w,h,self.threshold.get(),c,
                  self.on_preprocess)
            ).start()
Esempio n. 31
0
File: utils.py Progetto: yisj/wdbs29
def Artboard(size, color):
	artboard = Image.new(mode="RGB", size=size, color=ImageColor.getrgb(color))
	return artboard
Esempio n. 32
0
def getrgb(hexcode, whitening=0):
    rgb = ImageColor.getrgb("#" + hexcode)
    if whitening > 0:
        rgb = (rgb[0] + whitening, rgb[1] + whitening, rgb[2] + whitening)
    return rgb
 def paint(self, draw):
     draw.point((self.x, self.y), fill=ImageColor.getrgb(self.color))
Esempio n. 34
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: Optional[int] = None,
) -> 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")
    elif (boxes[:, 0] > boxes[:, 2]).any() or (boxes[:, 1] > boxes[:,
                                                                   3]).any():
        raise ValueError(
            "Boxes need to be in (xmin, ymin, xmax, ymax) format. Use torchvision.ops.box_convert to convert them"
        )

    num_boxes = boxes.shape[0]

    if num_boxes == 0:
        warnings.warn("boxes doesn't contain any box. No box was drawn")
        return image

    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]

    if font is None:
        if font_size is not None:
            warnings.warn(
                "Argument 'font_size' will be ignored since 'font' is not set."
            )
        txt_font = ImageFont.load_default()
    else:
        txt_font = ImageFont.truetype(font=font, size=font_size or 10)

    # 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)

    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)
Esempio n. 35
0
# 可修改的识别和显示参数
_font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")  # 显示字体
_min_score = 0.9  # 要显示的最低匹配百分比分数
_line_width = 3  # 物体框线大小
_alpha = 0.4  # Mask透明度
for _index in range(_output['num_detections']):
    if _output['detection_scores'][_index] < _min_score:
        # 匹配度低的不显示
        break

    # 颜色
    _color = _colors[(_output['detection_classes'][_index] - 1) % len(_colors)]

    # 添加遮罩
    _mask = _output['detection_masks'][_index]
    _rgb = ImageColor.getrgb(_color)
    _image_array = load_image_into_numpy_array(_image)

    _solid_color = np.expand_dims(
        np.ones_like(_mask), axis=2) * np.reshape(list(_rgb), [1, 1, 3])
    _pil_solid_color = Image.fromarray(np.uint8(_solid_color)).convert('RGBA')
    _pil_mask = Image.fromarray(np.uint8(255.0 * _alpha * _mask)).convert('L')
    _image = Image.composite(_pil_solid_color, _image, _pil_mask)
    np.copyto(_image_array, np.array(_image.convert('RGB')))
    _image = Image.fromarray(_image_array)

    # 画框图
    _draw = ImageDraw.Draw(_image)
    _class_name = category_index[_output['detection_classes'][_index]]['name']
    _box = tuple(_output['detection_boxes'][_index].tolist())
    _ymin, _xmin, _ymax, _xmax = _box
Esempio n. 36
0
n = 40
k = 12
semillas = []
for s in range(k):
    while True:
        x = randint(0, n - 1)
        y = randint(0, n - 1)
        if (x, y) not in semillas:
            semillas.append((x, y))
            break
print('Semillas creadas')
fondo = (255, 0, 0)  # rojo
zona = Image.new('RGB', (n, n), color=fondo)
p = zona.load()
c = sns.color_palette("Set3", k).as_hex()
i = 0
for (x, y) in semillas:
    p[x, y] = ImageColor.getrgb(c[i])
    i += 1
visual = zona.resize((10 * n, 10 * n))
visual.save("p4p.png")
print('Celdas calculadas')
celdas = [celda(i) for i in range(n * n)]
for i in range(n * n):
    s = celdas.pop(0)
    p[i % n, i // n] = ImageColor.getrgb(c[s])
visual = zona.resize((10 * n, 10 * n))
visual.show()
visual.save("p4pc.png")
Esempio n. 37
0
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))
img = cv2.polylines(img, [pts], True, (0, 255, 255))

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV', (10, 500), font, 4, BLACK, 2, cv2.LINE_AA)

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html

cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

from PIL import Image, ImageDraw, ImageColor

print ImageColor.getrgb('white')
mode = 'RGB'  # 'L'

img = Image.new(mode=mode, size=(width, height), color=WHITE)
#ImageDraw.Draw(img).polygon(pts, outline=1, fill=1)
ImageDraw.Draw(img).rectangle([(384, 0), (510, 128)], outline=1, fill=RED)

mask = np.array(img)

cv2.imshow('image', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

# http://pillow.readthedocs.io/en/3.4.x/reference/Image.html
 def _rand_color(self):
     r = random.randint(0, 255)
     g = random.randint(0, 255)
     b = random.randint(0, 255)
     color = 'rgb({R}, {G}, {B})'.format(R=r, G=g, B=b)
     return ImageColor.getrgb(color)
Esempio n. 39
0
def draw_segmentation_masks(
    image: torch.Tensor,
    masks: torch.Tensor,
    alpha: float = 0.8,
    colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str,
                           Tuple[int, int, int]]] = None,
) -> torch.Tensor:
    """
    Draws segmentation masks on given RGB image.
    The values of the input image should be uint8 between 0 and 255.

    Args:
        image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
        masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
        alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
            0 means full transparency, 1 means no transparency.
        colors (color or list of colors, optional): List containing the colors
            of the masks or single color for all masks. 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 each mask.

    Returns:
        img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
    """

    if not torch.jit.is_scripting() and not torch.jit.is_tracing():
        _log_api_usage_once(draw_segmentation_masks)
    if not isinstance(image, torch.Tensor):
        raise TypeError(f"The image must be a tensor, got {type(image)}")
    elif image.dtype != torch.uint8:
        raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
    elif image.dim() != 3:
        raise ValueError("Pass individual images, not batches")
    elif image.size()[0] != 3:
        raise ValueError(
            "Pass an RGB image. Other Image formats are not supported")
    if masks.ndim == 2:
        masks = masks[None, :, :]
    if masks.ndim != 3:
        raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)")
    if masks.dtype != torch.bool:
        raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}")
    if masks.shape[-2:] != image.shape[-2:]:
        raise ValueError(
            "The image and the masks must have the same height and width")

    num_masks = masks.size()[0]
    if colors is not None and num_masks > len(colors):
        raise ValueError(
            f"There are more masks ({num_masks}) than colors ({len(colors)})")

    if num_masks == 0:
        warnings.warn("masks doesn't contain any mask. No mask was drawn")
        return image

    if colors is None:
        colors = _generate_color_palette(num_masks)

    if not isinstance(colors, list):
        colors = [colors]
    if not isinstance(colors[0], (tuple, str)):
        raise ValueError(
            "colors must be a tuple or a string, or a list thereof")
    if isinstance(colors[0], tuple) and len(colors[0]) != 3:
        raise ValueError(
            "It seems that you passed a tuple of colors instead of a list of colors"
        )

    out_dtype = torch.uint8

    colors_ = []
    for color in colors:
        if isinstance(color, str):
            color = ImageColor.getrgb(color)
        colors_.append(torch.tensor(color, dtype=out_dtype))

    img_to_draw = image.detach().clone()
    # TODO: There might be a way to vectorize this
    for mask, color in zip(masks, colors_):
        img_to_draw[:, mask] = color[:, None]

    out = image * (1 - alpha) + img_to_draw * alpha
    return out.to(out_dtype)
Esempio n. 40
0
def draw_bounding_boxes(image: torch.Tensor,
                        boxes: torch.Tensor,
                        labels: Optional[List[str]] = None,
                        colors: Optional[List[Union[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 filled, 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 (List[Union[str, Tuple[int, int, int]]]): List containing the colors of bounding boxes. The colors can
            be represented as `str` or `Tuple[int, int, int]`.
        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.
    """

    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")

    ndarr = image.permute(1, 2, 0).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 i, bbox in enumerate(img_boxes):
        if colors is None:
            color = None
        else:
            color = colors[i]

        if fill:
            if color is None:
                fill_color = (255, 255, 255, 100)
            elif isinstance(color, str):
                # This will automatically raise Error if rgb cannot be parsed.
                fill_color = ImageColor.getrgb(color) + (100, )
            elif isinstance(color, tuple):
                fill_color = color + (100, )
            draw.rectangle(bbox, width=width, outline=color, fill=fill_color)
        else:
            draw.rectangle(bbox, width=width, outline=color)

        if labels is not None:
            draw.text((bbox[0], bbox[1]), labels[i], fill=color, font=txt_font)

    return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1)
Esempio n. 41
0
 def __init__(self, color=None):
     if color is None:
         color = random_color(0.2, random.random() > 0.5 and 0.3 or 0.7)
     self.color = ImageColor.getrgb(color)
     if colorsys.rgb_to_hls(*[x / 255.0 for x in self.color])[1] > 0.5:
         self.bg = 'light'
Esempio n. 42
0
    def color_from_value(self, value):
        """ given a value between 0 and 1, return an (r,g,b) tuple """

        return ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (int(
            (1.0 - value) * 360), 80, 50))
Esempio n. 43
0
def draw(graph, pos):
    for (x, y), v in graph.items():
        if v['value'] == '.':  # ground
            im.putpixel((x, y), ImageColor.getrgb('gray'))
    im.putpixel(pos, ImageColor.getrgb('yellow'))
    im.save('map.png')
# based on https://github.com/turkeyes/codecharts
# adapted by Pavlo Bazilinskyy <*****@*****.**>
from PIL import Image, ImageDraw, ImageColor, ImageFont
import matplotlib.pyplot as plt
import numpy as np
import string
import random
import json
import os
import math

# DEFINE PARAMATERS
# letters to not use in code charts because can be confused with digits
forbidden_letters = set(["I", "O"])
px_pt_ratio = 20 / 29  # according to our image dimensions, 29 point = 20 px
text_color = ImageColor.getrgb("gray")
font_type = "Arial.ttf"
tojitter = True  # add jitter from a regular grid
# buffer number of pixels to leave from the edges of the image so# codecharts
# are not tangent to image edges
ebuf = 5
# if want to make sure to sample triplets to the very edge of the image
# (downside: triplets may be more crowded)
go_to_image_edges = False


def point_to_pixel(num):
    return int(num * px_pt_ratio)


def pixel_to_point(num):
Esempio n. 45
0
def parse_maps_images(region, version_update):
    logging.debug('Parsing Maps images...')

    ies_path = os.path.join(constants.PATH_INPUT_DATA, 'ies.ipf', 'map.ies')

    with open(ies_path, 'rb') as ies_file:
        for row in csv.DictReader(ies_file, delimiter=',', quotechar='"'):
            image_path = os.path.join(constants.PATH_BUILD_ASSETS_IMAGES_MAPS, row['ClassName'].lower() + '.png')
            tok_path = os.path.join(constants.PATH_INPUT_DATA, 'bg.ipf', row['ClassName'].lower() + '.tok')

            if not os.path.exists(tok_path):
                continue
            if not (region == TOSRegion.kTEST and version_update) and os.path.exists(image_path):
                continue

            # Parse .tok mesh file
            tok_file = open(tok_path, 'rb')
            tok_xml = tokutil.tok2xml(tok_file)

            mesh3D = [elem for elem in tok_xml.getchildren() if elem.tag == 'mesh3D'][0]
            mesh3DVerts = [elem for elem in mesh3D.getchildren() if elem.tag == 'verts'][0]
            mappingTo2D = [elem for elem in tok_xml.getchildren() if elem.tag == 'mappingTo2D'][0]

            polygons = []

            for polygon in mappingTo2D.getchildren():
                points = []

                for edge in polygon.getchildren():
                    vertex = mesh3DVerts.getchildren()[int(edge.attrib['startVert'])]
                    points.append((int(vertex.attrib['x']), -int(vertex.attrib['y'])))

                polygons.append(points)

            # Free some memory before continuing
            tok_file.close()
            tok_xml.clear()

            del mesh3D
            del mesh3DVerts
            del mappingTo2D
            del tok_xml

            # Scale map to save some space
            image_height = int(round(int(row['Height']) * MAP_SCALE))
            image_width = int(round(int(row['Width']) * MAP_SCALE))

            offset_x = image_width / 2.0
            offset_y = image_height / 2.0

            # Render map to image
            image = Image.new("RGBA", (image_width, image_height), (0, 0, 0, 0))
            image_draw = ImageDraw.Draw(image)

            for points in polygons:
                # Make sure coordinates are centered
                points = [(int(offset_x + coords[0] * MAP_SCALE), int(offset_y + coords[1] * MAP_SCALE)) for coords in points]

                image_draw.polygon(points, fill=ImageColor.getrgb('#F2BC65'))

            # Add a shadow
            image_shadow = imageutil.replace_color(image, ImageColor.getcolor('#F2BC65', 'RGBA'), ImageColor.getcolor('#000000', 'RGBA'))
            image_shadow = image_shadow.filter(ImageFilter.GaussianBlur(2))
            image = Image.composite(image, image_shadow, image_shadow)

            # Save image to disk
            image.save(image_path, optimize=True)
            image.close()
            image_shadow.close()
def visualize_panoptic_seg_on_image_array(image,
                                          panoptic_seg,
                                          segments_info,
                                          category_index,
                                          alpha=0.8):
    """Draws masks on an image.

    Args:
        image: uint8 numpy array with shape [img_height, img_height, 3]
        panoptic_seg: a uint8 numpy array of shape [img_height, img_height]
        with values ranging between [0, num_classes).
        category_index:  a dict containing category dictionaries (each holding
            category index `id` and category name `name`) keyed by category indices.
        alpha: transparency value between 0 and 1. (default: 0.4)

    Raises:
        ValueError: On incorrect data type for image or panoptic_seg.
    """
    if image.dtype != np.uint8:
        raise ValueError('`image` not of type np.uint8')
    if image.shape[:2] != panoptic_seg.shape[:2]:
        raise ValueError(
            'The image has spatial dimensions %s but the panoptic_seg has '
            'dimensions %s' % (image.shape[:2], panoptic_seg.shape[:2]))
    pil_image = Image.fromarray(image)
    display_strs_and_colors = []
    for segment_info in segments_info:
        segment_id = segment_info["id"]
        mask = (panoptic_seg == segment_id).astype(np.uint8)
        mask_area = mask.sum().item()
        if mask_area == 0:
            continue

        category_id = segment_info["category_id"]
        color = STANDARD_COLORS[category_id % len(STANDARD_COLORS)]
        rgb = ImageColor.getrgb(color)
        name = category_index[category_id].get("display_name")
        if name is None:
            name = category_index[category_id]["name"]
        display_strs_and_colors.append((name if name else 'UnKnown', rgb))
        solid_color = np.expand_dims(np.ones_like(mask), axis=-1) * np.reshape(
            list(rgb), [1, 1, 3])
        pil_solid_color = Image.fromarray(
            np.uint8(solid_color)).convert('RGBA')
        pil_mask = Image.fromarray(np.uint8(255.0 * alpha * mask)).convert('L')
        pil_image = Image.composite(pil_solid_color, pil_image, pil_mask)

    width, height = pil_image.size
    str_heights = [font.getsize(s)[1] for s, c in display_strs_and_colors]
    total_str_height = int(
        sum([(1 + 2 * 0.25) * str_height
             for str_height in str_heights]) + _TOP_MARGIN * 2)
    image_with_legend = Image.new("RGB", (width, height + total_str_height),
                                  "white")
    image_with_legend.paste(pil_image, (0, 0))
    legend_draw = ImageDraw.Draw(image_with_legend)
    left = _LEFT_MARGIN
    top = height + _TOP_MARGIN
    for display_str, rgb in display_strs_and_colors:
        _, text_height = font.getsize(display_str)
        margin = np.ceil(0.25 * text_height)
        legend_draw.rectangle([(left, top),
                               (left + _LEFT_MARGIN, top + text_height)],
                              fill=rgb)
        legend_draw.text((left + 2 * _LEFT_MARGIN, top),
                         display_str,
                         fill="black",
                         font=font)
        top += margin + text_height

    return np.array(image_with_legend)
Esempio n. 47
0
def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

img = Image.open(FILEPATH)
img = img.convert('RGB')
average_color = compute_average_image_color(img)
average_color_int = tuple([int(i) for i in average_color])

hexcolor = rgb_to_hex(average_color_int)
selected_color_hex = None
selected_color_name = None
selected_distance = 999999

for color_hex, color_name in colornames.colornames.items():
    color_rgb = ImageColor.getrgb(color_hex)
    try:
        distance = math.sqrt(average_color_int[0] - color_rgb[0]) + \
                   math.sqrt(average_color_int[1] - color_rgb[1]) + \
                   math.sqrt(average_color_int[2] - color_rgb[2])
    except ValueError:
        continue

    if distance < selected_distance:
        selected_color_hex = color_hex
        selected_color_name = color_name


print("Avarage Color Original: " + hexcolor)
if selected_color_hex:
    print("Average Color Approximate: {} - {}".format(selected_color_hex, selected_color_name))
Esempio n. 48
0
        return ("", "Missing OWM API key", 0)
    owm = OWM(api_key)
    weather_manager = owm.weather_manager()
    observation = weather_manager.weather_at_coords(lat, long)
    w = observation.weather
    icon_name = w.weather_icon_name
    status = w.status
    temp = w.temperature("celsius")["temp"]
    return (icon_name, status, temp)


weather_last = ""
weather_last_updated = datetime.datetime.fromtimestamp(0)
weather_last_image = None

white = ImageColor.getrgb("white")
icon_map = {
    "01d": "sunny",
    # "01n": "starry",
    "03d": "cloudy",
    "03n": "cloudy",
    "04d": "cloudy",
    "04n": "cloudy",
    "02d": "partly-cloudy",
    # "02n": "partly-cloudy-night",
    "09d": "rain",
    "09n": "rain",
    "10d": "rain",
    "10n": "rain",
    "11d": "rain",
    "11n": "rain",
Esempio n. 49
0
def average_color(fname):
    color = Image.open(fname).resize((1, 1)).getpixel((0, 0))
    hex_color = "#{:02x}{:02x}{:02x}".format(*color)
    rgb_color = ImageColor.getrgb(hex_color)
    return "rgba({}, {}, {}, 0.4)".format(*rgb_color)
def main():
    alpha = 0.75
    colors = []
    path = sys.argv[1]
############### Make Swatch #############################
    with open('column.txt') as color_file:
        raw_colors = color_file.read().splitlines()
        color_file.close()

        for raw_clr in raw_colors:
            if raw_clr:
                colors.append(raw_clr)

    im = Image.new("RGB", (864, 32))

    draw = ImageDraw.Draw(im)
    pos = 0

    for clr in colors:
        parsed_clr = ImageColor.getrgb(clr)
        draw.rectangle([pos, 0, pos+48, 32], parsed_clr)
        pos += 48
    im.save("./swatch.jpg")

################ Make Preview ##########################
    size = 1280, 720
    try:
        wallpaper = Image.open("./wallpaper")
        wallpaper.thumbnail(size, Image.BICUBIC)
        wallpaper.save("./wallpaper-preview.jpg", "JPEG")
    except IOError:
        print( "cannot create thumbnail. Remaking configs?")

################ Termite config ########################

    termite = "" 
    with open(path + '/termite-header') as stub:
        termite = stub.read()

    fore = ImageColor.getrgb(colors[1])
    back = ImageColor.getrgb(colors[0])
    afore = "rgba({}, {}, {}, {})".format(fore[0], fore[1], fore[2], alpha)
    aback = "rgba({}, {}, {}, {})".format(back[0], back[1], back[2], alpha)
    abackt = "rgba({}, {}, {}, {})".format(back[0], back[1], back[2], alpha + 0.15)


    with open('termite-config', 'w') as tconf:
        tconf.write(termite)
        tconf.write("[colors]\n")
        tconf.write("background = {}\n".format(abackt))
        tconf.write("foreground = {}\n".format(colors[1]))        
        tconf.write("cursor = {}\n".format(colors[1]))
        
        for zx in range(0, 16):
            tconf.write("color{} = {}\n".format(zx, colors[zx+2]))
################ Waybar config #########################
    template = ""
    with open(path + '/waybar-base.css') as tm:
        template = tm.read()

    with open('waybar.css', 'w') as css:
        template = template.replace("<alpha-background>", aback)
        template = template.replace("<alpha-foreground>", afore)
        template = template.replace("<background>", colors[0])
        template = template.replace("<foreground>", colors[1])

        tags = ["black", "red", "green", "orange", "blue", "purple", "cyan", "grey"]
        for x in range(0, 16):
            if x < 8:
                template = template.replace("<{}>".format(tags[x]), colors[x+2])
            else:
                template = template.replace("<light-{}>".format(tags[x-8]), colors[x+2])
        css.write(template)

################ Sway config ##########################

    with open('sway-colors', 'w') as sconf:
        sconf.write("# This loads colors based on the theme\n")
        ## class, border, background, text, indicator
        sconf.write("client.focused {} {} {} {} {}\n".format(colors[7], colors[7], colors[17], colors[0], colors[0]))
        sconf.write("client.unfocused {} {} {} {} {}\n".format(colors[9], colors[9], colors[10], colors[17], colors[17]))
        sconf.write("client.focused_inactive {} {} {} {} {}\n".format(colors[8], colors[8], colors[17], colors[17], colors[17]))
        sconf.write("client.urgent {} {} {} {} {}\n".format(colors[5], colors[5], colors[17], colors[0], colors[0]))
Esempio n. 51
0
        product_height = product_height*ratio
        puma = cv2.resize(puma, (int(product_width), int(product_height)))
        total_height_crop = product_height-height
        half_height_crop = total_height_crop/2
        bot_minus_half_crop = int(product_height - half_height_crop)
        puma = puma[int(half_height_crop):int(bot_minus_half_crop), 0:int(product_width)]
        img[top_left[1]:bot_left[1], top_left[0]:bot_right[0]] = puma

    cv2.imwrite(str(i) + ".jpg", img)

height_template = template.shape[0]
width_template = template.shape[1]

shape = st.sidebar.selectbox("Price Text Shape:", ["Circle", "Rectangle"])
shape_color = st.sidebar.color_picker("Pick Shape Colour")
shape_color = ImageColor.getrgb(shape_color)
x_axis = st.sidebar.slider("x co-ordinate: ", 0, int(width_template))
y_axis = st.sidebar.slider("y co-ordinate: ", 0, int(height_template))

radius=0
if shape == "Circle":
    radius = st.sidebar.slider("Radius :", 0, 1000)
    template = cv2.circle(template, (x_axis, height_template-y_axis), radius, (shape_color), cv2.FILLED)

width = 0
height = 0
if shape == "Rectangle":
    width = st.sidebar.slider("Width :", 0, 1000)
    height = st.sidebar.slider("Height :", 0, 1000)
    template = cv2.rectangle(template, (x_axis, height_template-y_axis), ((x_axis+width),((height_template-y_axis)+height)), (shape_color, cv2.FILLED)
Esempio n. 52
0
    '#778899',
    '#000080',
    '#ff0000',
    '#ffa500',
    '#ffff00',
    '#c71585',
    '#00ff00',
    '#00fa9a',
    '#00ffff',
    '#0000ff',
    '#ff00ff',
    '#1e90ff',
    '#eee8aa',
]

base_colors_rgb = {h: ImageColor.getrgb(h) for h in base_colors_hex}
base_colors_lab = {
    h: rgb2lab([[[
        base_colors_rgb[h][0], base_colors_rgb[h][1], base_colors_rgb[h][2]
    ]]])
    for h in base_colors_hex
}

p = Path(r'D:\Interactive Video Retrieval\thumbnails\thumbnails')
res_dict = {}
n_keyframes = 108645
counter = 0
for img_path in p.glob('**/*.png'):
    counter += 1
    print(counter, '/', n_keyframes)
    img = Image.open(img_path)
assert asset, "No SAPIEN asset is loaded"

scene.step()
scene.update_render()
camera.take_picture()

rgba = camera.get_color_rgba()
rgba = (rgba * 255).clip(0, 255).astype("uint8")
rgba = Image.fromarray(rgba)
rgba.save("color.png")

depth = camera.get_depth()
y, x = np.where(depth < 1)
points = camera.get_position_rgba()[depth != 1]
points[..., 3] = 1
points[..., [0, 1, 2]] = points[..., [2, 0, 1]]
points[..., [0, 1]] *= -1
points = (mat44 @ points.T).T[:, :3]

cloud = open3d.geometry.PointCloud()
cloud.points = open3d.utility.Vector3dVector(points)
obj_segmentation = camera.get_obj_segmentation()[y, x]
color_map = (np.array(
    [ImageColor.getrgb(color) for color in ImageColor.colormap.keys()]) / 255)
cloud.colors = open3d.utility.Vector3dVector(color_map[obj_segmentation])

open3d.io.write_point_cloud("cloud.pcd", cloud)
open3d.visualization.draw_geometries([cloud])

scene = None
Esempio n. 54
0
 def add_watermark(self, text, fontsize, ttf, color, alpha, position, imagefile, output_dir):
     
     ttf_path='font/'
     #ttf_path='/app/font/'
     
     ttf_dict={'t1':'wt014.ttf',
               't2':'wt028.ttf',
               't3':'wt040.ttf',
               't4':'wt064.ttf',
               't5':'wt071.ttf',
               't6':'c01W4.ttc',
               't7':'c02W3.ttc',
               'e1':'e1.ttf',
               'e2':'e2.ttf',
               'e3':'e3.ttf',
               'e4':'e4.ttf',
               }
     
     ttf_name = ttf_dict[ttf]
     
     fontname = '%s%s'%(ttf_path,ttf_name)
     #print(fontname)
          
     #set font color
     if color == 'red':
         r=255;g=0;b=0
     elif color == 'green':
         r=0;g=255;b=0
     elif color == 'blue':
         r=0;g=0;b=255
     elif color == 'white':
         r=255;g=255;b=255
     elif color == 'black':
         r=0;g=0;b=0
     elif color == 'yellow':
         r, g, b = ImageColor.getrgb("#ffff00")
     elif color == 'pink':
         r, g, b = ImageColor.getrgb("#ffc0cb")
     elif color == 'gold':
         r, g, b = ImageColor.getrgb("#ffd700")
     else:
         r, g, b = ImageColor.getrgb(color)
         #print(r,g,b)
           
         
     img0 = Image.new("RGBA", (1,1))
     draw0 = ImageDraw.Draw(img0)
     font = ImageFont.truetype(fontname, fontsize)
     t_width, t_height = draw0.textsize(text, font=font)
     #t_width, t_height = draw0.textsize(unicode(text, 'UTF-8'), font=font)
     img = Image.new("RGBA", (t_width, t_height), (255,0,0,0))
     draw = ImageDraw.Draw(img)
     #draw.text((0,0),unicode(text, 'UTF-8'), font=font, fill=(255,255,255,128))
     draw.text((0,0),text,font=font, fill=(r,g,b,alpha))
     img2 = Image.open(imagefile)
     i_width, i_height = img2.size
     
     if position == 'p1':
         px = int(i_width*(1/15))
         py = int(i_height*(1/15))
     elif position == 'p2':
         px = int(i_width*(1/15))
         py = int((i_height-t_height)/2)
     elif position == 'p3':
         px = int(i_width*(1/15))
         py = int((i_height-t_height)*(14/15))
     elif position == 'p4':
         px = int((i_width-t_width)/2)
         py = int(i_height*(1/15))
     elif position == 'p5':
         px = int((i_width-t_width)/2)
         py = int((i_height-t_height)/2)
     elif position == 'p6':
         px = int((i_width-t_width)/2)
         py = int(i_height*(14/15))
     elif position == 'p7':
         px = int((i_width-t_width)*(14/15))
         py = int(i_height*(1/15))
     elif position == 'p8':
         px = int((i_width-t_width)*(14/15))
         py = int((i_height-t_height)/2)
     elif position == 'p9':
         px = int((i_width-t_width)*(14/15))
         py = int((i_height-t_height)*(14/15))
 
     img2.paste(img, (px, py), img)
     imagefile = imagefile.split('/')[-1]
     imagefile = "wm_" + imagefile
     print (imagefile + " saved...")
     img2.save(output_dir + imagefile)
     del draw0, draw
     del img0, img, img2
     
     return 'OK'
Esempio n. 55
0
def sepia(white="#fff0c0"):
    r, g, b = ImageColor.getrgb(white)
    r = _make_linear_lut(0, r)
    g = _make_linear_lut(0, g)
    b = _make_linear_lut(0, b)
    return ImagePalette("RGB", r + g + b)
Esempio n. 56
0

#laoding model
model = load_model()
st.success("Model loaded")

#Code for uploading file
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
    image = np.array(Image.open(uploaded_file))
    st.image(image, caption='Uploaded Image.', use_column_width=True)
    image = image / 255.

#Adding color picker
color = st.beta_color_picker('Pick A Color', '#00f900')
st.write('The current color is', color)

#Covert hex to rgb
color = ImageColor.getrgb(color)

#Prediction
input_image = cv2.resize(image, INPUT_SHAPE)
input_image = np.expand_dims(input_image, axis=0)
prediction = model.predict(input_image)[..., 0:1]

#Applying color
prediction = apply_color(image, prediction[0], list(color))
prediction = (prediction * 255.).astype(np.uint8)

#Displaying output
st.image(prediction, use_column_width=True)
def draw_bounding_box_on_image(image,
                               ymin,
                               xmin,
                               ymax,
                               xmax,
                               color='red',
                               thickness=4,
                               display_str_list=(),
                               use_normalized_coordinates=True,
                               fontsize=12,
                               alpha=127):
    """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, 'RGBA')
    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)
    color = ImageColor.getrgb(color)
    color = (color[0], color[1], color[2], alpha)
    draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
               (left, top)],
              width=thickness,
              fill=color)
    try:
        font = ImageFont.truetype('arial.ttf', fontsize)
    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
Esempio n. 58
0
    def start_battle(self, event, user, shibe, other_user, shibe_index: int):
        if user.user_id == other_user.user.id:
            return event.msg.reply("You can't battle yourself. That defeats the purpose.")

        event.msg.reply("Hey {0}! <@{1}> has challenged you to a duel! Type !accept if you accept,"
                        " or !decline if you decline.".format(other_user.user.mention, user.user_id))
        other_status = None

        def cond(event):
            nonlocal other_status
            if event.content.startswith("!accept"):
                other_status = True
            elif event.content.startswith("!decline"):
                other_status = False
            else:
                return False
            return True

        result = self.wait_for_event("MessageCreate", conditional=cond,
                                     channel__id=event.msg.channel.id, author__id=other_user.user.id)
        try:
            result.get(timeout=30.0)
        except timeout.Timeout:
            return event.msg.reply("Sorry, but your opponent didn't reply in time. Try someone else!")
        if not other_status:
            return event.msg.reply("Well, that's too bad. I bet you're just scared.")
        event.msg.reply("Alright! And what shibe will you be using {0}? (provide an index, see !inv)"
                        .format(other_user.user.mention))

        def cond(event):
            if event.content.isnumeric():
                return True
            return False

        result = self.wait_for_event("MessageCreate", conditional=cond,
                                     channel__id=event.msg.channel.id,  author__id=other_user.user.id)
        try:
            number = int(result.get(timeout=30.0).content)
        except timeout.Timeout:
            return event.msg.reply("Sorry, but your opponent didn't reply in time. Try someone else!")

        other_user_db = self.db.find_user(other_user.user.id)
        if not other_user_db:
            return event.msg.reply("Sorry, that shibe doesn't exist. Why don't you check again another time?")
        try:
            other_shibe = other_user_db.shibes[number - 1]
        except IndexError:
            return event.msg.reply("Sorry, that shibe doesn't exist. Why don't you check again another time?")
        event.msg.reply("Alright, let's DUEL! (This may take a bit, please be patient :wink:)")

        main_shibe_image = self.shibes[shibe[0]]
        other_shibe_image = self.shibes[other_shibe[0]]
        main_resp = requests.get(main_shibe_image)
        main_image = BytesIO(main_resp.content)
        other_resp = requests.get(other_shibe_image)
        other_image = BytesIO(other_resp.content)
        background = Image.open("imgs/background.jpg")
        main_image = Image.open(main_image).resize((240, 200))
        background.paste(main_image, (500, 250))
        other_image = Image.open(other_image).resize((150, 150))
        background.paste(other_image, (1200, 300))

        main_health, other_health, turn, last_msg = 100, 100, random.randint(0, 1), None
        while main_health > 0 and other_health > 0:
            send_background = background.copy()
            draw_background = ImageDraw.Draw(send_background)
            draw_background.rectangle([(500, 150), (500 + (main_health * 3), 175)], fill=ImageColor.getrgb("green"))
            draw_background.rectangle([(1200, 200), (1200 + (other_health * 3), 175)], fill=ImageColor.getrgb("green"))

            upload_file = BytesIO()
            send_background.save(upload_file, format="png")
            upload_file.seek(0)
            if last_msg:
                new_msg = event.msg.reply(battle_msg, attachments=[("battle.png", upload_file)])
                last_msg.delete()
                last_msg = new_msg
            else:
                last_msg = event.msg.reply("Let's BEGIN!", attachments=[("battle.png", upload_file)])

            if turn % 2:
                main_health -= random.randint(20, 60)
                battle_msg = random.choice(BATTLE_MSGS).format(other_user_db.user_id, other_shibe[0], shibe[0])
            else:
                other_health -= random.randint(15, 50)
                battle_msg = random.choice(BATTLE_MSGS)
                battle_msg = battle_msg.format(user.user_id, shibe[0], other_shibe[0])
            turn += 1

            sleep(1)

        if main_health <= 0:
            main_health, msg = 0, other_user.user.mention + " won! You get <@{0}>'s {1}".format(user.user_id, shibe[0])
        else:
            other_health, msg = 0, "<@{0}> won! You get {1}'s {2}"\
                .format(user.user_id, other_user.user.mention, other_shibe[0])

        send_background = background.copy()
        draw_background = ImageDraw.Draw(send_background)
        draw_background.rectangle([(500, 150), (500 + (main_health * 3), 175)], fill=ImageColor.getrgb("green"))
        draw_background.rectangle([(1200, 200), (1200 + (other_health * 3), 175)], fill=ImageColor.getrgb("green"))

        upload_file = BytesIO()
        send_background.save(upload_file, format="png")
        upload_file.seek(0)
        event.msg.reply(msg, attachments=[("battle.png", upload_file)])
        last_msg.delete()

        if not main_health:
            user.remove_shibe(shibe_index - 1)
            other_user_db.add_shibe(shibe[0])
        else:
            other_user_db.remove_shibe(number - 1)
            user.add_shibe(other_shibe[0])
Esempio n. 59
0
    def redrawAll(mode, canvas):
        # drawing logo
        drawing = PhotoImage(file='drawing.png')
        canvas.create_image(0, 0, image=drawing, anchor=NW)

        # instructions
        canvas.create_rectangle(100, 0, mode.width, 100, fill='black')
        canvas.create_rectangle(105, 7, mode.width - 8, 95, fill='white')
        canvas.create_text(120,
                           10,
                           text='press "e" for eraser',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(120,
                           30,
                           text='pick colors on left',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(120,
                           50,
                           text='press "s" to save',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(120,
                           70,
                           text='press "enter" to play',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(290,
                           10,
                           text='click once to place pen down,',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(290,
                           30,
                           text='click again to lift pen up',
                           font='Arial 15',
                           anchor=NW)
        canvas.create_text(290,
                           50,
                           text='fill drawing to edges of canvas!',
                           font='Arial 15',
                           anchor=NW)

        # color picker
        for r in range(len(mode.colors)):
            for c in range(len(mode.colors[0])):
                (x0, y0, x1, y1) = mode.getColorCellBounds(r, c)
                canvas.create_rectangle(x0,
                                        y0,
                                        x1,
                                        y1,
                                        fill=mode.colors[r][c],
                                        width=1)

        # drawing grid
        for row in range(mode.rows):
            for col in range(mode.cols):
                (x0, y0, x1, y1) = mode.getCellBounds(row, col)
                for point in mode.draw:
                    x, y, color = point
                    if mode.checkPoint(x, y, x0, y0, x1, y1):
                        canvas.create_rectangle(x0,
                                                y0,
                                                x1,
                                                y1,
                                                fill=color,
                                                width=0)
                        rgbColor = ImageColor.getrgb(color)
                        mode.startSpriteDrawing.rectangle([(x0, y0), (x1, y1)],
                                                          fill=rgbColor)
Esempio n. 60
0
def make_movie_with_time_stamp(imgname, movname, indexsz='05', framerate=10, imgdir=None, rm_images=True,
               save_into_subdir=False, start_number=0, framestep=1, ext='png', option='normal',
                               start=0, timestep=1.0, timelist=None, unit='s', timestamp_loc='br', color='white',
                               font='Arial', fontsize=15, alpha=0):
    def get_std_pos(width, height, loc='br', npartition=10):
        """
        Returns standard positions of an image (top right, center left, bottom center, etc.)
        ... PIL uses a convention where (0, 0) is the upper left corner.
        Parameters
        ----------
        width: int, width of image in px
        height: int, height of image in px
        loc: str, Location of timestamp. Choose from (bl, bc, br, cl, cc, cr, tl, tc, tr)
        npartition: int, (NOT currently used) Can be used to set extra location options.
                    dx, dy below can be used as increments in x and y.

        Returns
        -------
        pos: tuple, coordinate where a text wi

        """
        left, right = 0.025 * width, 0.75 * width
        bottom, top = 0.90 * height, 0.1 * height
        xcenter, ycenter =  width / 2., height / 2.
        dx, dy = width / npartition, height / npartition
        if loc == 'bl':
            pos = (left, bottom)
        elif loc == 'bc':
            pos = (xcenter, bottom)
        elif loc == 'br':
            pos = (right, bottom)
        elif loc == 'cl':
            pos = (left, ycenter)
        elif loc == 'cc':
            pos = (xcenter, ycenter)
        elif loc == 'cr':
            pos = (right, ycenter)
        elif loc == 'tl':
            pos = (left, top)
        elif loc == 'tc':
            pos = (xcenter, top)
        elif loc == 'tr':
            pos = (right, top)
        else:
            print('Location of timestamp was not understood! Choose from (bl, bc, br, cl, cc, cr, tl, tc, tr)')
            raise RuntimeError
        return pos

    def atoi(text):
        'human sorting'
        return int(text) if text.isdigit() else text
    def natural_keys(text):
        '''
        human sorting
        alist.sort(key=natural_keys) sorts in human order
        http://nedbatchelder.com/blog/200712/human_sorting.html
        (See Toothy's implementation in the comments)
        '''
        return [atoi(c) for c in re.split('(\d+)', text)]

    # Find images
    imgs = glob.glob(imgname + '*.' + ext)
    # print [img[-7:] for img in imgs]

    imgs = sorted(imgs, key=natural_keys)
    # print [img[-7:] for img in imgs]
    if len(imgs)==0:
        print('No images found! Exiting...')
        raise RuntimeError

    # File architecture
    parentdir, imgname= os.path.split(imgs[0])
    tmpdir = os.path.join(parentdir, 'tmp_img')
    # make a tmp dir directory
    if not os.path.exists(tmpdir):
        os.makedirs(tmpdir)


    # time stamp stuff
    # ... make a time list with a constant timestep unless it is given
    if timelist is None:
        timelist = np.arange(start, start + timestep * len(imgs), timestep)
    # ... font of time stamp
    if os.path.exists('/Library/Fonts/' + font +'.ttf'):
        fnt = ImageFont.truetype('/Library/Fonts/' + font +'.ttf', fontsize)
    elif os.path.exists('/Library/Fonts/' + font +'.ttc'):
        fnt = ImageFont.truetype('/Library/Fonts/' + font +'.ttc', fontsize)
    else:
        print('... Specified was not found under /Library/Fonts/')
        print('... Proceed with /Library/Fonts/Arial.ttf')
        fnt = ImageFont.truetype('/Library/Fonts/' + font + '.ttf')

    for i in range(len(imgs)):
        parentdir, imgname = os.path.split(imgs[i])

        img = Image.open(imgs[i])
        img = img.convert('RGB')
        width, height = img.size
        txt_pos = get_std_pos(width, height, loc=timestamp_loc)
        timestamp = 't={0:0.4f}'.format(timelist[i]) + unit

        draw = ImageDraw.Draw(img)
        try:
            red, blue, green = ImageColor.getrgb(color)
        except ValueError:
            print('... Color string was not understood.')
            print('... Use white as a default')
            red, blue, green = ImageColor.getrgb('w')
        draw.text(txt_pos, timestamp, font=fnt, fill=(red, blue, green, int(255*alpha)))
        outputfile = os.path.join(tmpdir, 'tmp' + '_{0:05d}.'.format(i) + ext)
        img.save(outputfile)

    make_movie(os.path.join(tmpdir, 'tmp_'), movname, indexsz='05', framerate=framerate, rm_images=rm_images,
               save_into_subdir=save_into_subdir, start_number=start_number, framestep=framestep, ext=ext, option=option)