Exemple #1
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
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
Exemple #3
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"]))
Exemple #4
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)
Exemple #5
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')
Exemple #6
0
def getcolor(image, color):
    if image.getbands() == ('R', 'G', 'B', 'A'):
        return IC.getcolor(color, 'RGBA')
    elif image.getbands() == ('1',):
        return IC.getcolor(color, 'L')
    else:
        raise exceptions.NotImplementedError('Only RGBA or L format!')
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
Exemple #8
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)
Exemple #9
0
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()
Exemple #10
0
def to_colors(which):
    strs = config.get('settings', which).split()
    return {
        'norm': ImageColor.getcolor(strs[0], 'RGBA'),
        'hover': ImageColor.getcolor(strs[1], 'RGBA'),
        'barred': ImageColor.getcolor(strs[2], 'RGBA'),
    }
Exemple #11
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
Exemple #12
0
    def _setup_ui(self):
        """
        Sets up the UI
        """

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

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

        number = ui.LabelWidget("",
                                name=NAME_GET_STARTED,
                                parent=interface_frame,
                                align="center",
                                font_color=(0, 0, 0, 255))
        number.dimensions = (
            5, 5,
            interface_frame.width - 10,
            interface_frame.height - 10
        )
Exemple #13
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)
Exemple #14
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())
Exemple #15
0
 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()
Exemple #16
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))
Exemple #17
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
 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"))
Exemple #19
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())
Exemple #20
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"))
Exemple #21
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"))
Exemple #22
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")
Exemple #23
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)
Exemple #24
0
def brightness(image, amount=50):
    """Adjust brightness from black to white
    - amount: -1(black) 0 (unchanged) 1(white)
    - repeat: how many times it should be repeated"""
    if amount == 0:
        return image

    image = imtools.convert_safe_mode(image)

    if amount < 0:
        #fade to black
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size, 0),
                -amount / 100.0)
    else:
        #fade to white
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size,
                    ImageColor.getcolor('white', image.mode)),
                amount / 100.0)
    #fix image transparency mask
    if imtools.has_alpha(image):
        im.putalpha(imtools.get_alpha(image))
    return im
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')))
	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
    def process_four_images(self, photo_bundle):
        images = map(lambda image: Image.open(image), photo_bundle.raw)
        new_size = map(lambda x: int(x * 0.5), images[0].size)
        map(lambda x: x.thumbnail(new_size, Image.ANTIALIAS), images)
        im = images[0]
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1]*2 + self.banner.size[1]) * 1.10)
        new_width = int((new_height / 1.45) * 2)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        banner_x_start = int(new_width / 2 - self.banner.size[0] / 2)
        new_im.paste(self.banner, (banner_x_start, top_border + im.size[1]))
        left_x_start = int(new_width / 4 - im.size[0] / 2)
        right_x_start = int(new_width / 2 + left_x_start)
        new_im.paste(images[0], (left_x_start, top_border))
        new_im.paste(images[1], (right_x_start, top_border))
        new_im.paste(images[2], (left_x_start, top_border + im.size[1] + self.banner.size[1]))
        new_im.paste(images[3], (right_x_start, top_border + im.size[1] + self.banner.size[1]))
        esif_logo_x_start = int(new_width - left_x_start - self.esif_logo.size[0])
        esif_logo_y_start = int((new_height - self.esif_logo.size[1])/2)
        new_im.paste(self.esif_logo, (esif_logo_x_start, esif_logo_y_start), mask=self.esif_logo)
        return new_im
Exemple #28
0
def image_compare(path_origin,path_current,perc=100):
    '''image_compare function
    args - path_to origin screenshot,path_to screenshot for compare, type "str"
    compare percent (default = 100%, no difference between screenshot), type "int")
    '''
    original_image = Image.open(path_origin)
    width,height = origin_size = original_image.size
    device_image = Image.open(path_current)
    im_diff=original_image.copy()
    pixel_count = 0

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

    for x in xrange(width):
        for y in xrange(0,height):
            cur_pixel = original_image.getpixel((x,y))
            if cur_pixel!=device_image.getpixel((x,y)):
                pixel_count+=1
                if pixel_count==1:
                    im_diff=original_image.copy()
                im_diff.putpixel((x, y), ImageColor.getcolor('darkred', 'RGBA'))
                
    diff_percent = round(float(pixel_count)*100/(width*height),2)
    print "Image compare: {0}% difference from original screenshot".format(diff_percent)
    im_diff.save("C:/{0}_diff.png".format(test_name))
    if perc>100-diff_percent:
        return False
    else:
        return True
Exemple #29
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
    def process_dual_image(self, photo_bundle):
        im = Image.open(photo_bundle.raw[0])
        im.thumbnail(map(lambda x: int(x * 0.5), im.size), Image.ANTIALIAS)
        self.resize_additions(im)
        print("image", im.format, im.size, im.mode)
        new_height = int((im.size[1] + self.banner.size[1]) * 1.15) * 2
        new_width = int(new_height / 1.45)
        top_border = int(new_height / 20)
        print("new", new_width, new_height, top_border)

        new_im = Image.new('RGBA', (new_width, new_height), ImageColor.getcolor('WHITE', 'RGBA'))
        draw = ImageDraw.Draw(new_im)
        line_y = top_border + im.size[1] + self.banner.size[1]
        draw.line((0, line_y, new_width, line_y), fill=128, width=0)
        banner_x_start = int(new_width / 2 - self.banner.size[0] / 2)
        new_im.paste(self.banner, (banner_x_start, top_border + im.size[1]))
        new_im.paste(self.banner, (banner_x_start, int(top_border * 1.5) + im.size[1] * 2 + self.banner.size[1]))
        im_x_start = int(new_width / 2 - im.size[0] / 2)
        new_im.paste(im, (im_x_start, top_border))
        new_im.paste(im, (im_x_start, int(top_border * 1.5) + im.size[1] + self.banner.size[1]))
        esif_logo_x_start = int(new_width - im_x_start - self.esif_logo.size[0])
        esif_logo_y_start = int(top_border + im.size[1])
        new_im.paste(self.esif_logo, (esif_logo_x_start, esif_logo_y_start), mask=self.esif_logo)
        new_im.paste(self.esif_logo, (esif_logo_x_start, int(top_border * 1.5) + (im.size[1]*2) + self.banner.size[1]), mask=self.esif_logo)
        return new_im
Exemple #31
0
def color_from_value(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))
Exemple #32
0
    def test_functions(self):
        # rgb numbers
        self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
        self.assertEqual((0, 255, 0), ImageColor.getrgb("rgb(0,255,0)"))
        self.assertEqual((0, 0, 255), ImageColor.getrgb("rgb(0,0,255)"))

        # percents
        self.assertEqual((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
        self.assertEqual((0, 255, 0), ImageColor.getrgb("rgb(0%,100%,0%)"))
        self.assertEqual((0, 0, 255), ImageColor.getrgb("rgb(0%,0%,100%)"))

        # rgba numbers
        self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
        self.assertEqual((0, 255, 0, 0), ImageColor.getrgb("rgba(0,255,0,0)"))
        self.assertEqual((0, 0, 255, 0), ImageColor.getrgb("rgba(0,0,255,0)"))
        self.assertEqual((0, 0, 0, 255), ImageColor.getrgb("rgba(0,0,0,255)"))

        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(0,100%,50%)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360,100%,50%)"))
        self.assertEqual((0, 255, 255), ImageColor.getrgb("hsl(180,100%,50%)"))

        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(0,100%,100%)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(360,100%,100%)"))
        self.assertEqual((0, 255, 255), ImageColor.getrgb("hsv(180,100%,100%)"))

        # alternate format
        self.assertEqual(
            ImageColor.getrgb("hsb(0,100%,50%)"), ImageColor.getrgb("hsv(0,100%,50%)")
        )

        # floats
        self.assertEqual((254, 3, 3), ImageColor.getrgb("hsl(0.1,99.2%,50.3%)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(360.,100.0%,50%)"))

        self.assertEqual((253, 2, 2), ImageColor.getrgb("hsv(0.1,99.2%,99.3%)"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(360.,100.0%,100%)"))

        # case insensitivity
        self.assertEqual(
            ImageColor.getrgb("RGB(255,0,0)"), ImageColor.getrgb("rgb(255,0,0)")
        )
        self.assertEqual(
            ImageColor.getrgb("RGB(100%,0%,0%)"), ImageColor.getrgb("rgb(100%,0%,0%)")
        )
        self.assertEqual(
            ImageColor.getrgb("RGBA(255,0,0,0)"), ImageColor.getrgb("rgba(255,0,0,0)")
        )
        self.assertEqual(
            ImageColor.getrgb("HSL(0,100%,50%)"), ImageColor.getrgb("hsl(0,100%,50%)")
        )
        self.assertEqual(
            ImageColor.getrgb("HSV(0,100%,50%)"), ImageColor.getrgb("hsv(0,100%,50%)")
        )
        self.assertEqual(
            ImageColor.getrgb("HSB(0,100%,50%)"), ImageColor.getrgb("hsb(0,100%,50%)")
        )

        # space agnosticism
        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, 0), ImageColor.getrgb("rgba(  255  ,  0  ,  0  ,  0  )")
        )
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsl(  0  ,  100%  ,  50%  )"))
        self.assertEqual((255, 0, 0), ImageColor.getrgb("hsv(  0  ,  100%  ,  100%  )"))

        # wrong number of components
        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(255,0)")
        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(255,0,0,0)")

        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(100%,0%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(100%,0%,0)")
        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(100%,0%,0 %)")
        self.assertRaises(ValueError, ImageColor.getrgb, "rgb(100%,0%,0%,0%)")

        self.assertRaises(ValueError, ImageColor.getrgb, "rgba(255,0,0)")
        self.assertRaises(ValueError, ImageColor.getrgb, "rgba(255,0,0,0,0)")

        self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100%,0%,0%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0%,100%,50%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100,50%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsl(0,100%,50)")

        self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%,0%,0%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0%,100%,50%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100,50%)")
        self.assertRaises(ValueError, ImageColor.getrgb, "hsv(0,100%,50)")
Exemple #33
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 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)
Exemple #34
0
precincts_reporting = len([
    precinct for precinct in votes_dict
    if sum(votes_dict[precinct].values()) > 0
])
precincts = len(votes_dict)

im = Image.open("./data_files/GA06_BW_runoff.png")
xsize = im.size[0]
ysize = im.size[1]
img_all = im.copy()  # Top individual vote getters
img_comp_primary = im.copy()  # Compared to April primary
img_comp_pres = im.copy()  # Compared to 2016 presidential results

mode = "RGB"
#img=img.convert(mode)
red = ImageColor.getcolor('red', mode)
black = ImageColor.getcolor('black', mode)
gray = ImageColor.getcolor('gray', mode)

for precinct in votes_dict:
    if (precinct in precinct_xy):
        all_votes = sum([
            votes_dict[precinct][candidate]
            for candidate in votes_dict[precinct]
        ])
        order = sorted(votes_dict[precinct],
                       key=votes_dict[precinct].get,
                       reverse=True)

        best = order[0]
        next_best = order[1]
sector_xmin = -1500 / 16
sector_xmax = 1500 / 16
sector_zmin = -1500 / 16
sector_zmax = 1500 / 16

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("-i", "--input"):
        path = a
    elif o in ("-o", "--output"):
        output = a
    elif o == "--bgcolor":
        bgcolor = ImageColor.getrgb(a)
    elif o == "--scalecolor":
        scalecolor = ImageColor.getrgb(a)
    elif o == "--playercolor":
        playercolor = ImageColor.getrgb(a)
    elif o == "--origincolor":
        origincolor = ImageColor.getrgb(a)
    elif o == "--drawscale":
        drawscale = True
        border = 40
    elif o == "--drawplayers":
        drawplayers = True
    elif o == "--draworigin":
        draworigin = True
    elif o == "--drawunderground":
        drawunderground = True
Exemple #36
0
def get_level_data():
    if req.method == 'GET':
        return custom_redirect('/')
    result = 'None'

    shape_size = req.form.get('shape_size').strip().replace(' ', '').split('x')
    shape_size_x, shape_size_y = 0, 0
    try:
        shape_size_x, shape_size_y = int(shape_size[0]), int(shape_size[1])
    except:
        return render_result('Error shape size')

    downgrade = req.form.get('downgrade').strip().replace(' ', '').split('x')
    downgrade_x, downgrade_y = 0, 0
    try:
        downgrade_x, downgrade_y = int(downgrade[0]), int(downgrade[1])
    except:
        return render_result('Error downgrage')

    chromakey_text = req.form.get('chromakey').strip().replace(' ',
                                                               '').replace(
                                                                   ';', '')
    chromakey_text = chromakey_text.replace('(', '').replace(')', '')
    chromakey_type = None
    chromakey = None
    if chromakey_text[0] == '#':
        chromakey_type = 'hex'
        chromakey = chromakey_text[1:]
    elif chromakey_text[:3] == 'rgb':
        chromakey_type = 'rgb'
        chromakey = chromakey_text[3:].split(',')
    elif chromakey_text[:5] == 'rgb10':
        chromakey_type = 'rgb10'
        chromakey = chromakey_text[5:]
    print(chromakey)
    print(chromakey_type)
    if 'sam_file' not in req.files:
        return render_result('File Not Selected!')

    if downgrade_x < 1 or downgrade_y < 1:
        render_result('Minimal downgrade - 1!')

    image = NewImage.open(req.files['sam_file'])
    width, height = image.size

    result = '''<levelXML>
<info v="1.87" x="121.35000038146973" y="67.7249984741211" c="11" f="t" h="f" bg="0" bgc="16777215" e="1"/>
<groups>
    <g x="165" y="61" r="0" ox="-165" oy="-61" s="f" f="f" o="100" im="f" fr="f">
    '''

    i = 0
    while i < width:
        j = 0
        while j < height:
            r, g, b = tuple(image.getpixel((i, j))[:3])
            rgb10 = (r * 65536) + (g * 256) + b
            can_pass_c = True
            if chromakey_type:
                if chromakey_type == 'hex':
                    to_rgb = NewImageColor.getcolor(f'#{chromakey}', "RGB")
                    if r == to_rgb[0] and g == to_rgb[1] and b == to_rgb[2]:
                        can_pass_c = False
                elif chromakey_type == 'rgb':
                    if r == int(chromakey[0]) and g == int(
                            chromakey[1]) and b == int(chromakey[2]):
                        can_pass_c = False
                elif chromakey_type == 'rgb10' and rgb10 == chromakey:
                    can_pass_c = False
            if can_pass_c:
                result += '\n'
                result += \
                    f'<sh t="0" i="f" p0="{i}" p1="{j}" p2="{shape_size_x}" p3="{shape_size_y}" p4="0" p5="f"' \
                    f' p6="f" p7="1" p8="{rgb10}" p9="-1" p10="100" p11="1"/>'
            j += downgrade_y
        i += downgrade_x

    result += '''
        </g>
    </groups>
</levelXML>'''

    return render_result(result)
Exemple #37
0
def get_bgr(color):
    rgb = ImageColor.getrgb(color)
    return rgb[::-1]
Exemple #38
0
#!/usr/bin/python
from PIL import Image, ImageChops, ImageColor
import json, re

TILE = 8

PALETTE = {
    "black": ImageColor.getrgb("#000000"),
    "black_bright": ImageColor.getrgb("#000000"),
    "blue": ImageColor.getrgb("#0088bb"),
    "blue_bright": ImageColor.getrgb("#0055dd"),
    "red": ImageColor.getrgb("#bb0000"),
    "red_bright": ImageColor.getrgb("#ff0000"),
    "purple": ImageColor.getrgb("#bb00bb"),
    "purple_bright": ImageColor.getrgb("#ff00ff"),
    "green": ImageColor.getrgb("#00bb00"),
    "green_bright": ImageColor.getrgb("#00ff00"),
    "turquoise": ImageColor.getrgb("#00bbbb"),
    "turquoise_bright": ImageColor.getrgb("#00ffff"),
    "yellow": ImageColor.getrgb("#bbbb00"),
    "yellow_bright": ImageColor.getrgb("#ffff00"),
    "white": ImageColor.getrgb("#bbbbbb"),
    "white_bright": ImageColor.getrgb("#ffffff"),
    "orange": ImageColor.getrgb("#bb9900"),
    "orange_bright": ImageColor.getrgb("#ffcc00")
}


class MapMaker():
    def __init__(self):
        self.tex_img = Image.open("../data/tex.png")
Exemple #39
0
    def test_colormap(self):
        self.assertEqual((0, 0, 0), ImageColor.getrgb("black"))
        self.assertEqual((255, 255, 255), ImageColor.getrgb("white"))
        self.assertEqual((255, 255, 255), ImageColor.getrgb("WHITE"))

        self.assertRaises(ValueError, ImageColor.getrgb, "black ")
Exemple #40
0
    direccion = randint(0, 3)
    if direccion == 0: # vertical abajo -> arriba
        return (0, randint(0, n - 1))
    elif direccion == 1: # izq. -> der
        return (randint(0, n - 1), 0)
    elif direccion == 2: # der. -> izq.
        return (randint(0, n - 1), n - 1)
    else:
        return (n - 1, randint(0, n - 1))
 
celdas = [celda(i) for i in range(n * n)]
voronoi = Image.new('RGB', (n, n))
vor = voronoi.load()
c = sns.color_palette("Set3", k).as_hex()
for i in range(n * n):
    vor[i % n, i // n] = ImageColor.getrgb(c[celdas.pop(0)])
limite, vecinos = n, []
for dx in range(-1, 2):
    for dy in range(-1, 2):
        if dx != 0 or dy != 0:
            vecinos.append((dx, dy))
def man(dist):
    dist = abs(dx) + abs(dy)
    return dist

def propaga(replica):
    prob, dificil = 0.999, 0.9
    grieta = voronoi.copy()
    g = grieta.load()
    (x, y) = inicio()
    largo = 0
Exemple #41
0
    def plot(self, colors={}, scale=1):
        """ Plot the motif.

        The color of individual letters can be defined via the colors dict using RGB values, e.g.
        {'A': '#FF0000', 'C': '#0000FF'} will result in red A's and blue C's. Non-defined characters
        will be plotted black.

        The alphabets 'ACGT', 'ACGU', and 'HIMS' have predefined colors (that can be overwritten):
        
        '"ACGT" -> {'A': '#00CC00', 'C': '#0000CC', 'G': '#FFB300', 'T': '#CC0000'}
        '"ACGU" -> {'A': '#00CC00', 'C': '#0000CC', 'G': '#FFB300', 'U': '#CC0000'}
        '"HIMS" -> {'H': '#CC0000', 'I': '#FFB300', 'M': '#00CC00', 'S': '#CC00FF'}

        Using, for instance, a scale parameter of 0.5 halves both height and width of the plot.

        Parameters
        ----------
        colors : dict of char->str
            A dict with individual alphabet characters as keys and hexadecimal RGB specifiers as values.
        
        scale : float
            Adjust the size of the plot (should be > 0).
        
        Returns
        -------
        image : PIL.image.image
            A Pillow image object.
        """

        # prepare colors
        self.colors = deepcopy(colors)
        if self.colors == {}:
            if self.alphabet == 'ACGT':
                self.colors = {'A': '#00CC00', 'C': '#0000CC', 'G': '#FFB300', 'T': '#CC0000'}
            elif self.alphabet == 'ACGU':
                self.colors = {'A': '#00CC00', 'C': '#0000CC', 'G': '#FFB300', 'U': '#CC0000'}
            elif self.alphabet == 'HIMS':
                self.colors = {'H': '#CC0000', 'I': '#FFB300', 'M': '#00CC00', 'S': '#CC00FF'}
        # translate hex to decimal
        for char in self.colors:
            if len(self.colors[char]) != 7 or not self.colors[char].startswith("#"):
                raise RuntimeError("Error: '{}' is not a valid color specifier.".format(self.colors[char]))
            self.colors[char] = ImageColor.getrgb(self.colors[char])
        # cache all alphabet character images
        img_chars = self._load_characters()
        # prepapre image dimensions
        w_char, h_char = img_chars[self.alphabet[0]].size
        w_col, h_col = w_char, h_char*3
        h_top, h_bottom = 40, 60
        w_total, h_total = w_col + w_col*len(self.pwm) + 40, h_top + h_col + h_bottom
        img_motif = Image.new("RGB", (w_total, h_total), "#ffffff")
        img_draw = ImageDraw.Draw(img_motif)
        # plot axes
        self._add_y_axis(img_motif, img_draw, w_col, h_col, h_top)
        self._add_x_axis(img_motif, img_draw, w_col, h_col, h_top)
        # plot sequence motif
        self._add_motif(img_motif, w_col, h_col, h_top, img_chars)
        # default height is 754 pixels
        if scale != 1:
            w_scaled, h_scaled = int(w_total*scale), int(h_total*scale)
            img_motif = img_motif.resize((w_scaled, h_scaled), Image.BICUBIC)
        for x in img_chars:
            img_chars[x].close()
        return img_motif
Exemple #42
0
    def execute_on(self, *args, **kwargs):
        super(TransformationDrawRectanglePercent,
              self).execute_on(*args, **kwargs)

        try:
            left = float(self.left or '0')
        except ValueError:
            left = 0

        try:
            top = float(self.top or '0')
        except ValueError:
            top = 0

        try:
            right = float(self.right or '0')
        except ValueError:
            right = 0

        try:
            bottom = float(self.bottom or '0')
        except ValueError:
            bottom = 0

        if left < 0:
            left = 0

        if left > 100:
            left = 100

        if top < 0:
            top = 0

        if top > 100:
            top = 100

        if right < 0:
            right = 0

        if right > 100:
            right = 100

        if bottom < 0:
            bottom = 0

        if bottom > 100:
            bottom = 100

        logger.debug('left: %f, top: %f, right: %f, bottom: %f', left, top,
                     right, bottom)

        fillcolor_value = getattr(self, 'fillcolor', None)
        if fillcolor_value:
            fill_color = ImageColor.getrgb(fillcolor_value)
        else:
            fill_color = 0

        outlinecolor_value = getattr(self, 'outlinecolor', None)
        if outlinecolor_value:
            outline_color = ImageColor.getrgb(outlinecolor_value)
        else:
            outline_color = None

        outlinewidth_value = getattr(self, 'outlinewidth', None)
        if outlinewidth_value:
            outline_width = int(outlinewidth_value)
        else:
            outline_width = 0

        left = left / 100.0 * self.image.size[0]
        top = top / 100.0 * self.image.size[1]

        # Invert right value
        # Pillow uses left, top, right, bottom to define a viewport
        # of real coordinates
        # We invert the right and bottom to define a viewport
        # that can crop from the right and bottom borders without
        # having to know the real dimensions of an image

        right = self.image.size[0] - (right / 100.0 * self.image.size[0])
        bottom = self.image.size[1] - (bottom / 100.0 * self.image.size[1])

        draw = ImageDraw.Draw(self.image)
        draw.rectangle((left, top, right, bottom),
                       fill=fill_color,
                       outline=outline_color,
                       width=outline_width)

        return self.image
def processImage(inputImg):
    img = Image.open(my_path+"/"+inputImg).convert('LA').filter(ImageFilter.GaussianBlur(BLUR_AMMOUNT)).convert('L')
    
    ## ACCOUNT FOR AND REMOVE EXIF ORIENTATION DATA 
    ### JESUS CHRIST F**K THIS PART
    if "exif" in img.info:
        exif_dict = piexif.load(img.info["exif"])
        if piexif.ImageIFD.Orientation in exif_dict["0th"]:
            orientation = exif_dict["0th"].pop(piexif.ImageIFD.Orientation)
            #exif_bytes = piexif.dump(exif_dict)

            if orientation == 2:
                img = img.transpose(Image.FLIP_LEFT_RIGHT)
            elif orientation == 3:
                img = img.rotate(180)
            elif orientation == 4:
                img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
            elif orientation == 5:
                img = img.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
            elif orientation == 6:
                img = img.rotate(-90, expand=True)
            elif orientation == 7:
                img = img.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
            elif orientation == 8:
                img = img.rotate(90, expand=True)
    ################################################
    
    widthOld, heightOld = img.size

    print("ORIGINAL DIMENSIONS: ", widthOld, ", ", heightOld)
    
    width = widthOld
    height = heightOld
    ratio = 0

    ## Resize based on maximum size
    if widthOld > heightOld:
        ratio = IMAGE_SIZE_MAX/widthOld
        width = IMAGE_SIZE_MAX
        height = heightOld * ratio

    elif widthOld < heightOld:
        ratio = IMAGE_SIZE_MAX/heightOld
        height = IMAGE_SIZE_MAX
        width = widthOld * ratio

    width = width * IMAGE_SCALE
    height = height * IMAGE_SCALE
    print("RESIZING TO ", int(width), ", ", int(height))

    canvas = Image.new('1',(int(width),int(height)),'white')
    sample = img.resize((int(width),int(height)),resample=Image.BICUBIC) ## Resize the original without interpolation data loss
    painter = ImageDraw.Draw(canvas)

    numDots = (width / SPACING) * (height / SPACING)
    print("DRAWING ", int(numDots), " dots")

    flipTable = 0
    stack = []
    for i in range(1, round(width / SPACING)):
        for k in range(1,round(height / SPACING)):
            x = math.floor(i*SPACING)
            y = math.floor(k*SPACING)
            pixel = sample.getpixel((x,y))
            if pixel < THRESHOLD:
                BRUSH_SIZE = ((sample.getpixel((x,y)) - 1) / (255 - 1)) * (MAX_BRUSH - MIN_BRUSH) + MIN_BRUSH
                BRUSH_SIZE = math.ceil(MAX_BRUSH-BRUSH_SIZE) 
                stack.append((x,y,BRUSH_SIZE))
            else:
                 BRUSH_SIZE = 0
            BL = round(BRUSH_SIZE / 2)
            painter.ellipse((x-BL,y-BL,x+BL,y+BL),ImageColor.getcolor('black','1'))
        
        if flipTable == 0:
            stack.reverse()
        outPoints.append(stack.copy())
        flipTable = 1 - flipTable
        stack.clear()

    canvas.save(my_path+"/output.png")
    #canvas.filter(ImageFilter.BLUR()).resize((widthOld,heightOld),resample=Image.BICUBIC).save(my_path+"/outputSCALE.png")
    print("FINISHED. Saved to ", my_path, "/output.png")

    return None
box = (x,y,x+200,y+200)
im.paste(Tri1.crop(box), (x,y))
x = 200
y = 400
box = (x,y,x+200,y+200)
im.paste(Ach2.crop(box), (x,y))
x = 400
y = 400
box = (x,y,x+200,y+200)
im.paste(Tri2.crop(box), (x,y))

## Draw border line
x = 200
y = 0
box = (x,y,x+1,y+600)
im.paste(ImageColor.getrgb('black'), box)
x = 400
y = 0
box = (x,y,x+2,y+600) ## Cannot draw line on 400
im.paste(ImageColor.getrgb('black'), box)
x = 0
y = 200
box = (x,y,x+600,y+1)
im.paste(ImageColor.getrgb('black'), box)
x = 0
y = 400
box = (x,y,x+600,y+2) ## Cannot draw line on 400
im.paste(ImageColor.getrgb('black'), box)

plt.figure(), plt.xticks([]), plt.yticks([])
plt.imshow(im)
Exemple #45
0
    def test_rounding_errors(self):

        for color in ImageColor.colormap:
            expected = Image.new("RGB", (1, 1), color).convert("L").getpixel((0, 0))
            actual = ImageColor.getcolor(color, "L")
            self.assertEqual(expected, actual)

        self.assertEqual(
            (0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB")
        )
        Image.new("RGB", (1, 1), "white")

        self.assertEqual((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
        self.assertEqual((255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
        self.assertEqual(
            (0, 255, 115, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA")
        )
        Image.new("RGBA", (1, 1), "white")

        self.assertEqual(0, ImageColor.getcolor("black", "L"))
        self.assertEqual(255, ImageColor.getcolor("white", "L"))
        self.assertEqual(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
        Image.new("L", (1, 1), "white")

        self.assertEqual(0, ImageColor.getcolor("black", "1"))
        self.assertEqual(255, ImageColor.getcolor("white", "1"))
        # The following test is wrong, but is current behavior
        # The correct result should be 255 due to the mode 1
        self.assertEqual(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
        # Correct behavior
        # self.assertEqual(
        #     255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
        Image.new("1", (1, 1), "white")

        self.assertEqual((0, 255), ImageColor.getcolor("black", "LA"))
        self.assertEqual((255, 255), ImageColor.getcolor("white", "LA"))
        self.assertEqual((162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
        Image.new("LA", (1, 1), "white")
Exemple #46
0
def create_labeled_video(
    data_dir,
    out_dir=None,
    dlc_online=True,
    save_images=False,
    cut=(0, np.Inf),
    crop=None,
    cmap="bmy",
    radius=3,
    lik_thresh=0.5,
    write_ts=False,
    write_scale=2,
    write_pos="bottom-left",
    write_ts_offset=0,
    display=False,
    progress=True,
    label=True,
):
    """ Create a labeled video from DeepLabCut-live-GUI recording

    Parameters
    ----------
    data_dir : str
        path to data directory
    dlc_online : bool, optional
        flag indicating dlc keypoints from online tracking, using DeepLabCut-live-GUI, or offline tracking, using :func:`dlclive.benchmark_videos`
    out_file : str, optional
        path for output file. If None, output file will be "'video_file'_LABELED.avi". by default None. If NOn
    save_images : bool, optional
        boolean flag to save still images in a folder
    cut : tuple, optional
        time of video to use. Will only save labeled video for time after cut[0] and before cut[1], by default (0, np.Inf)
    cmap : str, optional
        a :package:`colorcet` colormap, by default 'bmy'
    radius : int, optional
        radius for keypoints, by default 3
    lik_thresh : float, optional
        likelihood threshold to plot keypoints, by default 0.5
    display : bool, optional
        boolean flag to display images as video is written, by default False
    progress : bool, optional
        boolean flag to display progress bar

    Raises
    ------
    Exception
        if frames cannot be read from the video file
    """

    base_dir = os.path.basename(data_dir)
    video_file = os.path.normpath(f"{data_dir}/{base_dir}_VIDEO.avi")
    ts_file = os.path.normpath(f"{data_dir}/{base_dir}_TS.npy")
    dlc_file = (
        os.path.normpath(f"{data_dir}/{base_dir}_DLC.hdf5") if dlc_online else
        os.path.normpath(f"{data_dir}/{base_dir}_VIDEO_DLCLIVE_POSES.h5"))

    cap = cv2.VideoCapture(video_file)
    cam_frame_times = np.load(ts_file)
    n_frames = cam_frame_times.size

    lab = "LABELED" if label else "UNLABELED"
    if out_dir:
        out_file = (
            f"{out_dir}/{os.path.splitext(os.path.basename(video_file))[0]}_{lab}.avi"
        )
        out_times_file = (
            f"{out_dir}/{os.path.splitext(os.path.basename(ts_file))[0]}_{lab}.npy"
        )
    else:
        out_file = f"{os.path.splitext(video_file)[0]}_{lab}.avi"
        out_times_file = f"{os.path.splitext(ts_file)[0]}_{lab}.npy"

    os.makedirs(os.path.normpath(os.path.dirname(out_file)), exist_ok=True)

    if save_images:
        im_dir = os.path.splitext(out_file)[0]
        os.makedirs(im_dir, exist_ok=True)

    im_size = (
        int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
    )
    if crop is not None:
        crop[0] = crop[0] if crop[0] > 0 else 0
        crop[1] = crop[1] if crop[1] > 0 else im_size[1]
        crop[2] = crop[2] if crop[2] > 0 else 0
        crop[3] = crop[3] if crop[3] > 0 else im_size[0]
        im_size = (crop[3] - crop[2], crop[1] - crop[0])

    fourcc = cv2.VideoWriter_fourcc(*"DIVX")
    fps = cap.get(cv2.CAP_PROP_FPS)
    vwriter = cv2.VideoWriter(out_file, fourcc, fps, im_size)
    label_times = []

    if write_ts:
        ts_font = cv2.FONT_HERSHEY_PLAIN

        if "left" in write_pos:
            ts_w = 0
        else:
            ts_w = (im_size[0] if crop is None else
                    (crop[3] - crop[2]) - (55 * write_scale))

        if "bottom" in write_pos:
            ts_h = im_size[1] if crop is None else (crop[1] - crop[0])
        else:
            ts_h = 0 if crop is None else crop[0] + (12 * write_scale)

        ts_coord = (ts_w, ts_h)
        ts_color = (255, 255, 255)
        ts_size = 2

    poses = pd.read_hdf(dlc_file)
    if dlc_online:
        pose_times = poses["pose_time"]
    else:
        poses["frame_time"] = cam_frame_times
        poses["pose_time"] = cam_frame_times
    poses = poses.melt(id_vars=["frame_time", "pose_time"])
    bodyparts = poses["bodyparts"].unique()

    all_colors = getattr(cc, cmap)
    colors = [
        ImageColor.getcolor(c, "RGB")[::-1]
        for c in all_colors[::int(len(all_colors) / bodyparts.size)]
    ]

    ind = 0
    vid_time = 0
    while vid_time < cut[0]:

        cur_time = cam_frame_times[ind]
        vid_time = cur_time - cam_frame_times[0]
        ret, frame = cap.read()
        ind += 1

        if not ret:
            raise Exception(
                f"Could not read frame = {ind+1} at time = {cur_time-cam_frame_times[0]}."
            )

    frame_times_sub = cam_frame_times[
        (cam_frame_times - cam_frame_times[0] > cut[0])
        & (cam_frame_times - cam_frame_times[0] < cut[1])]
    iterator = (tqdm(range(ind, ind + frame_times_sub.size))
                if progress else range(ind, ind + frame_times_sub.size))
    this_pose = np.zeros((bodyparts.size, 3))

    for i in iterator:

        cur_time = cam_frame_times[i]
        vid_time = cur_time - cam_frame_times[0]
        ret, frame = cap.read()

        if not ret:
            raise Exception(
                f"Could not read frame = {i+1} at time = {cur_time-cam_frame_times[0]}."
            )

        if dlc_online:
            poses_before_index = np.where(pose_times < cur_time)[0]
            if poses_before_index.size > 0:
                cur_pose_time = pose_times[poses_before_index[-1]]
                this_pose = poses[poses["pose_time"] == cur_pose_time]
        else:
            this_pose = poses[poses["frame_time"] == cur_time]

        if label:
            for j in range(bodyparts.size):
                this_bp = this_pose[this_pose["bodyparts"] ==
                                    bodyparts[j]]["value"].values
                if this_bp[2] > lik_thresh:
                    x = int(this_bp[0])
                    y = int(this_bp[1])
                    frame = cv2.circle(frame, (x, y),
                                       radius,
                                       colors[j],
                                       thickness=-1)

        if crop is not None:
            frame = frame[crop[0]:crop[1], crop[2]:crop[3]]

        if write_ts:
            frame = cv2.putText(
                frame,
                f"{(vid_time-write_ts_offset):0.3f}",
                ts_coord,
                ts_font,
                write_scale,
                ts_color,
                ts_size,
            )

        if display:
            cv2.imshow("DLC Live Labeled Video", frame)
            cv2.waitKey(1)

        vwriter.write(frame)
        label_times.append(cur_time)
        if save_images:
            new_file = f"{im_dir}/frame_{i}.png"
            cv2.imwrite(new_file, frame)

    if display:
        cv2.destroyAllWindows()

    vwriter.release()
    np.save(out_times_file, label_times)
Exemple #47
0
def tree_into_image(tree: Branch, width: int, height: int):
    dest = Image.new('RGBA', (width, height), ImageColor.getrgb('#00000000'))

    traverse_stack = []
    traverse_stack.append(BranchTraverseNode(tree, 0, 0, True))

    while len(traverse_stack) > 0:
        previous_node = traverse_stack[-1]
        parent = previous_node.branch
        offsetx = previous_node.offsetx
        offsety = previous_node.offsety
        is_height = (len(traverse_stack) % 2) == 0

        if parent.left != None and previous_node.goes_left:
            if isinstance(parent.left, Branch):
                # descend into it
                traverse_stack.append(
                    BranchTraverseNode(parent.left, offsetx, offsety, True))
                continue
            elif isinstance(parent.left, Image.Image):
                dest.paste(parent.left, (offsetx, offsety))
                previous_node.goes_left = False  # now check the right
                continue
            else:
                print(
                    "parent.left in bsp traversal is neither a Branch nor an Image, this should never happen"
                )

        if parent.right != None:
            if isinstance(parent.right, Branch):
                # descend into it
                new_offsetx = offsetx if not is_height else (offsetx +
                                                             parent.offset)
                new_offsety = offsety if is_height else (offsety +
                                                         parent.offset)
                traverse_stack.append(
                    BranchTraverseNode(parent.right, new_offsetx, new_offsety,
                                       True))
                continue
            elif isinstance(parent.right, Image.Image):
                new_offsetx = offsetx if not is_height else (offsetx +
                                                             parent.offset)
                new_offsety = offsety if is_height else (offsety +
                                                         parent.offset)
                dest.paste(parent.right, (new_offsetx, new_offsety))
                # we don't continue to fall into the upwards backtracking code
            else:
                print(
                    "parent.right in bsp traversal is neither a Branch nor an Image, this should never happen"
                )

        # we either already went left, or can't got left nor right, so we go up until we find a branch left
        traverse_stack.pop()  # current branch is handled
        while len(traverse_stack) > 0:
            popped_parent = traverse_stack[-1]
            if popped_parent.goes_left:
                # switch the popped_parent from left to right
                popped_parent.goes_left = False
                break
            elif len(traverse_stack) != 0:
                traverse_stack.pop()  # further up
            else:
                break  # both loops exit

    return dest
Exemple #48
0
def higlighted_text(
        input_img,
        text,
        output_img,
        background="black",
        foreground="white",
        transparency=255,
        align="center",
        direction=None,
        text_wrap=2,
        font_name=None,
        font_size=60,
        linespace="+2",
        rad=20,
        position=(0, 0),
):
    templait = Image.open(input_img)
    # resize image
    source_img = templait.convert("RGBA").resize((1024, 1024))
    w, h = source_img.size
    if font_name is None:
        font_name = "userbot/helpers/styles/impact.ttf"
    font = ImageFont.truetype(font_name, font_size)
    ew, eh = position
    # get text size
    tw, th = font.getsize(text)
    width = 50 + ew
    hight = 30 + eh
    # wrap the text & save in a list
    mask_size = int((w / text_wrap) + 50)
    input_text = "\n".join(wrap(text, int((40.0 / w) * mask_size)))
    list_text = input_text.splitlines()
    # create image with correct size and black background
    if direction == "upwards":
        list_text.reverse()
        operator = "-"
        hight = h - (th + int(th / 1.2)) + eh
    else:
        operator = "+"
    for i, items in enumerate(list_text):
        x, y = (font.getsize(list_text[i])[0] + 50, int(th * 2 - (th / 2)))
        # align masks on the image....left,right & center
        if align == "center":
            width_align = "((mask_size-x)/2)"
        elif align == "left":
            width_align = "0"
        elif align == "right":
            width_align = "(mask_size-x)"
        clr = ImageColor.getcolor(background, "RGBA")
        if transparency == 0:
            mask_img = Image.new("RGBA", (x, y),
                                 (clr[0], clr[1], clr[2], 0))  # background
            mask_draw = ImageDraw.Draw(mask_img)
            mask_draw.text((25, 8), list_text[i], foreground, font=font)
        else:
            mask_img = Image.new(
                "RGBA", (x, y),
                (clr[0], clr[1], clr[2], transparency))  # background
            # put text on mask
            mask_draw = ImageDraw.Draw(mask_img)
            mask_draw.text((25, 8), list_text[i], foreground, font=font)
            # remove corner (source- https://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroundtransparent-on-it-using-pi)
            circle = Image.new("L", (rad * 2, rad * 2), 0)
            draw = ImageDraw.Draw(circle)
            draw.ellipse((0, 0, rad * 2, rad * 2), transparency)
            alpha = Image.new("L", mask_img.size, transparency)
            mw, mh = mask_img.size
            alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
            alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, mh - rad))
            alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (mw - rad, 0))
            alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)),
                        (mw - rad, mh - rad))
            mask_img.putalpha(alpha)
        # put mask_img on source image & trans remove the corner white
        trans = Image.new("RGBA", source_img.size)
        trans.paste(
            mask_img,
            (
                (int(width) + int(eval(f"{width_align}"))),
                (eval(f"{hight} {operator}({y*i}+({int(linespace)*i}))")),
            ),
        )
        source_img = Image.alpha_composite(source_img, trans)
    source_img.save(output_img, "png")
Exemple #49
0
def hex_to_rgb(hex_string, opacity=1):
    rgb = ImageColor.getcolor(hex_string, "RGB")
    return f"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {opacity})"
    rl = random.randint(0, l)
    rw = random.randint(0, w)
    point = rl, rw
    pallate.append("#%02x%02x%02x" % im.getpixel(point))

    for i in range(1, int(sys.argv[2])):
        max_dif = -1
        best_seed_pixel = 0, 0, 0
        for x in range(0, l):
            for y in range(0, w):
                min_dif = -1
                min_pixel = 0, 0, 0
                for z in range(0, len(pallate)):
                    point2 = x, y
                    seed_pixel = im.getpixel(point2)
                    previous = ImageColor.getrgb(pallate[z])
                    seed_r = abs(seed_pixel[0] - previous[0])
                    seed_g = abs(seed_pixel[1] - previous[1])
                    seed_b = abs(seed_pixel[2] - previous[2])
                    dif = math.sqrt(seed_r * seed_r + seed_g * seed_g +
                                    seed_b * seed_b)
                    if dif < min_dif or min_dif == -1:
                        min_dif = dif
                        min_pixel = seed_pixel
                if min_dif > max_dif or max_dif == -1:
                    max_dif = min_dif
                    best_seed_pixel = min_pixel
        pixel = "#%02x%02x%02x" % best_seed_pixel
        pallate.append(pixel)

elif sys.argv[3] == "manual":
# 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 = True


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


def pixel_to_point(num):
def project_overview(project,
                     width,
                     height,
                     filename=None,
                     orientation='horizontal',
                     step_offset=0,
                     background_palette_field="",
                     texturing=None,
                     coloring=None,
                     color_key=False,
                     background_color=(155, 155, 155, 255)):
    # the lattice ui uses a sequence broken into
    # blocks of images for the accordion view
    #
    # this returns a single horizontal or vertical
    # color coded strip of categories with an optional
    # key for category names / colors beneath

    # project is dict containing
    # categories: {"name1" : int expected, "name2"} #ordered
    # palette: {"name1":{"fill" : "", "border": ""}, "name2":...}
    if coloring is None:
        try:
            coloring = project['palette']
        except KeyError:
            coloring = {}

    sequence_steps = []
    sequence_order = []

    try:
        sequence_order = [
            k for k, v in sorted(project['order'].items(), key=lambda x: x[1])
        ]
    except KeyError:
        try:
            sequence_order = project['categories'].keys()
        except KeyError:
            pass

    try:
        #for k,v in project['categories'].items():
        for k in sequence_order:
            v = project['categories'][k]
            for step in range(v):
                sequence_steps.append(k)
    except KeyError:
        pass
    # fallback color schemes
    # catch 'None' and '*' for everything else
    if not 'None' in coloring:
        coloring['None'] = {}
        coloring['None']['fill'] = "darkgray"
        coloring['None']['border'] = (135, 135, 135, 1)
    else:
        if not 'fill' in coloring['None']:
            coloring['None']['fill'] = "darkgray"
        if not 'border' in coloring['None']:
            coloring['None']['border'] = (135, 135, 135, 1)

    if not '*' in coloring:
        coloring['*'] = {}
        coloring['*']['fill'] = "lightgray"
        coloring['*']['border'] = (223, 223, 223, 1)
    else:
        if not 'fill' in coloring['*']:
            coloring['*']['fill'] = "lightgray"

        if not 'border' in coloring['*']:
            coloring['*']['border'] = (223, 223, 223, 1)

    if color_key is True:
        color_key_padding = 20
    else:
        color_key_padding = 0

    overview_image = PILImage.new('RGB', (width, height + color_key_padding),
                                  background_color)
    draw = ImageDraw.Draw(overview_image, 'RGBA')

    # print(coloring)
    draw_stack = []
    # use to label start and end of sequences
    last_step = False
    subcount = 0
    text_inset = 25
    color_keys = {}
    for step_num, step in enumerate(sequence_steps):
        if step is None:
            color = coloring['None']['fill']
            border_color = coloring['None']['border']
        else:
            try:
                if sequence_steps[step_num + 1] != step:
                    last_step = True
                else:
                    last_step = False
            except:
                last_step = True
            color = coloring['*']['fill']
            border_color = coloring['*']['border']
            for k, v in coloring.items():
                #for key, value in step.items():
                if k == step:
                    try:
                        if isinstance(coloring[k]['fill'], list):
                            color = tuple(coloring[k]['fill'])
                        else:
                            color = coloring[k]['fill']
                    except Exception as ex:
                        # print(ex)
                        color = coloring['*']['fill']

                    try:
                        if isinstance(coloring[k]['border'], list):
                            border_color = tuple(coloring[k]['border'])
                        else:
                            border_color = coloring[k]['border']
                    except Exception as ex:
                        # print(ex)
                        border_color = coloring['*']['border']

                    if orientation == 'vertical':
                        stepwise = height / len(sequence_steps)
                        x1 = 0
                        y1 = stepwise * step_num
                        x2 = width
                        y2 = (stepwise * step_num) + stepwise
                        separator = functools.partial(draw.line,
                                                      (0, y1, width, y1),
                                                      fill=(255, 255, 255, 55))
                    elif orientation == 'horizontal':
                        stepwise = width / len(sequence_steps)
                        y1 = 0
                        x1 = stepwise * step_num
                        y2 = height
                        x2 = (stepwise * step_num) + stepwise
                        separator = functools.partial(draw.line,
                                                      (x1, 0, x1, height),
                                                      fill=(255, 255, 255, 55))

                    # get rgb of color to modify alpha if needed
                    if isinstance(color, str):
                        color = ImageColor.getrgb(color)

                    color_keys[step] = color
                    draw_call = functools.partial(draw.rectangle,
                                                  (x1, y1, x2, y2),
                                                  outline=border_color,
                                                  fill=color)
                    draw_stack.append(draw_call)
                    draw_stack.append(separator)
                    #draw_stack.append(functools.partial(draw.line, (0, x1, 0, x2), fill=(255,255,255)))
                    subcount += 1

                    if last_step:
                        draw_stack.append(
                            functools.partial(
                                draw.text, (x2 - text_inset, y1),
                                str(step_num + step_offset) + "\n" +
                                str(step_num + step_offset + 1) +
                                "\n{}".format(subcount), (230, 230, 230, 128)))
                        subcount = 0
                    break
        if texturing:
            try:
                if texturing[step_num] == 0:
                    # continuous draw vertical lines
                    draw_stack.append(
                        functools.partial(vertical_texture, draw, 8, y1,
                                          stepwise, width))
                elif texturing[step_num] == -1:
                    # discontinuous
                    pass
            except IndexError:
                pass
        # draw cells
        for dc in draw_stack:
            dc()

    if color_key is True:
        key_offset = 5
        y_start = height + key_offset
        x_start = 0
        color_block_size = 10
        horizontal_padding = 10
        for color_name, color_value in color_keys.items():
            draw.rectangle((x_start, y_start, x_start + color_block_size,
                            y_start + color_block_size),
                           fill=color_value)
            # ensure that color name is string
            # was running into difficulty with lxml
            # that in most cases will be treated as string
            # but not here
            # > print(color_name, type(color_name))
            # > 'bar' <class 'lxml.etree._ElementUnicodeResult'>
            color_name = str(color_name)
            text = draw.text((x_start + color_block_size, y_start), color_name)
            text_width = draw.textsize(color_name)[0]
            # print(y_start, height, color_key_padding)
            key_width = text_width + color_block_size + horizontal_padding
            if x_start + key_width > width:
                y_start += key_offset * 3
                x_start = 0
            else:
                x_start += key_width

    if filename:
        image_filename = '/tmp/{}.jpg'.format(str(uuid.uuid4()))
        overview_image.save(image_filename)
        filename = image_filename

    file = io.BytesIO()
    extension = 'JPEG'
    overview_image.save(file, extension)
    overview_image.close()
    file.seek(0)

    return (filename, file)
Exemple #53
0
    def image(self):
        try:
            if (
                settings.DEBUG or not self.generated_meta_image
            ) and self.get_header_image():
                orig = self.get_header_image()
                img = Image.open(
                    get_storage_class()().open(
                        self.get_header_image().some[1:].partition("/")[2]
                    )
                )
                draw = ImageDraw.Draw(img)
                font = ImageFont.truetype(
                    "juso/static/fonts/Montserrat-ExtraBold.ttf", int(1200 / 30)
                )
                color = ImageColor.getcolor(self.get_color(), "RGB")

                title = textwrap.wrap(self.title.upper(), 35, break_long_words=True)
                line = 0
                line_space = 10
                padding_top = 5
                padding_bottom = 14
                padding_side = 15
                line_height = int(1200 / 30) + line_space + padding_bottom + padding_top
                width = 1200
                height = 600

                text_top = height - len(title) * line_height - line_height / 2

                text_color = color
                fill_color = (255, 255, 255)
                border_color = color

                for text in title:
                    line += 1
                    size = font.getsize_multiline(text)
                    x = 30
                    y = text_top + line * line_height
                    draw.rectangle(
                        [
                            x - padding_side,
                            y - padding_top,
                            x + size[0] + padding_side,
                            y + size[1] + padding_bottom,
                        ],
                        fill=fill_color,
                        outline=border_color,
                        width=3,
                    )
                    draw.text(
                        (x, y), text, text_color, font=font,
                    )

                f = BytesIO()

                img.save(f, format="JPEG", quality=100)

                self.generated_meta_image.save(orig.some.split("/")[-1], files.File(f))
            return self.generated_meta_image
        except:  # Anything could happen, but it's not really a priority
            return None
Exemple #54
0
 def from_hex(cls, value):
     if not value.startswith('#'):
         value = '#' + value
     rgb = ImageColor.getcolor(value, 'RGB')
     return cls.from_rgb(rgb)
Exemple #55
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'
def czmlPoint(request):

    doc1 = czml.CZML()

    packet1 = czml.CZMLPacket(id='document', name="billboards", version='1.0')
    doc1.packets.append(packet1)

    #billboard
    for i in Point.objects.all():

        packet2 = czml.CZMLPacket(id='bb_' + "2021" + str(100 + i.id),
                                  name=i.name,
                                  status=i.lc_phase.name)

        descri = czml.Description()

        for j in Task.objects.all():
            descri.string = "<b>Type: </b> " + i.type.name + "<br/>" + "<b>Description: </b> " + i.description + " <a href='http://geomatik.hacettepe.edu.tr/' target='_blank'>(Web Sitesi)</a>" + "<br/>" + "<b>Status: </b> " + i.lc_phase.name + "<br/>" + "<b>Task: </b> " + str(
                j.description)

        packet2.description = descri

        bb = czml.Billboard(scale=i.markersize, show=True)

        a = (i.symbol).split("/")
        a = a[-1]

        bb.image = "/static/Cesium/Build/Cesium/Assets/Textures/maki/" + a,
        bb.heightReference = "CLAMP_TO_GROUND"
        bb.clampToGround = True

        rgb = ImageColor.getcolor(i.markercolor, "RGB")
        L1 = list(rgb)
        if i.lc_phase.name == "Bakımda":
            L1.append(175)
        else:
            L1.append(255)

        rgb = tuple(L1)

        bb.color = {'rgba': rgb}  #i.markercolor

        packet2.billboard = bb

        poz = czml.Position()
        WGS84 = 6378137, 298.257223563
        poz.cartesian = geodetic_to_geocentric(WGS84, i.lat, i.lon, i.height)

        packet2.position = poz

        rgb2 = ImageColor.getcolor(i.lc_phase.color, "RGBA")

        lab = czml.Label()
        lab.show = True
        #lab.fillColor = {'rgba': rgb2}
        lab.text = i.lc_phase.name
        lab.heightReference = "CLAMP_TO_GROUND"
        lab.clampToGround = True
        lab.pixelOffset = {"cartesian2": [20, -35]}
        lab.horizontalOrigin = "LEFT"
        lab.showBackground = True
        lab.backgroundColor = {'rgba': rgb2}

        packet2.label = lab

        doc1.packets.append(packet2)

        #photo kısmını kaydetmek için
        #img = i.photo
        #img.save('../static/Cesium/Build/Cesium/Assets/Textures/maki/' + str(i.id) +".png" , 'PNG')

    myczml = doc1.dumps()

    return HttpResponse(str(myczml))
Exemple #57
0
                self.viewer = rendering.SimpleImageViewer()
            self.viewer.imshow(img)
            return self.viewer.isopen

    def seed(self, n):
        self.np_random, seed1 = seeding.np_random(n)
        seed2 = seeding.hash_seed(seed1 + 1) % 2**31
        return [seed1, seed2]

    def close(self):
        if self.viewer is not None:
            self.viewer.close()
            self.viewer = None


AGENT_COLOR = ImageColor.getcolor('blue', mode='RGB')
AGENT_NEIGHBORHOOD_COLOR = (186, 238, 247)
PREY_COLOR = 'red'

CELL_SIZE = 35

WALL_COLOR = 'black'

ACTION_MEANING = {
    0: "DOWN",
    1: "LEFT",
    2: "UP",
    3: "RIGHT",
    4: "NOOP",
}
Exemple #58
0
    def test_hash(self):
        # short 3 components
        self.assertEqual((255, 0, 0), ImageColor.getrgb("#f00"))
        self.assertEqual((0, 255, 0), ImageColor.getrgb("#0f0"))
        self.assertEqual((0, 0, 255), ImageColor.getrgb("#00f"))

        # short 4 components
        self.assertEqual((255, 0, 0, 0), ImageColor.getrgb("#f000"))
        self.assertEqual((0, 255, 0, 0), ImageColor.getrgb("#0f00"))
        self.assertEqual((0, 0, 255, 0), ImageColor.getrgb("#00f0"))
        self.assertEqual((0, 0, 0, 255), ImageColor.getrgb("#000f"))

        # long 3 components
        self.assertEqual((222, 0, 0), ImageColor.getrgb("#de0000"))
        self.assertEqual((0, 222, 0), ImageColor.getrgb("#00de00"))
        self.assertEqual((0, 0, 222), ImageColor.getrgb("#0000de"))

        # long 4 components
        self.assertEqual((222, 0, 0, 0), ImageColor.getrgb("#de000000"))
        self.assertEqual((0, 222, 0, 0), ImageColor.getrgb("#00de0000"))
        self.assertEqual((0, 0, 222, 0), ImageColor.getrgb("#0000de00"))
        self.assertEqual((0, 0, 0, 222), ImageColor.getrgb("#000000de"))

        # case insensitivity
        self.assertEqual(ImageColor.getrgb("#DEF"), ImageColor.getrgb("#def"))
        self.assertEqual(ImageColor.getrgb("#CDEF"), ImageColor.getrgb("#cdef"))
        self.assertEqual(ImageColor.getrgb("#DEFDEF"), ImageColor.getrgb("#defdef"))
        self.assertEqual(ImageColor.getrgb("#CDEFCDEF"), ImageColor.getrgb("#cdefcdef"))

        # not a number
        self.assertRaises(ValueError, ImageColor.getrgb, "#fo0")
        self.assertRaises(ValueError, ImageColor.getrgb, "#fo00")
        self.assertRaises(ValueError, ImageColor.getrgb, "#fo0000")
        self.assertRaises(ValueError, ImageColor.getrgb, "#fo000000")

        # wrong number of components
        self.assertRaises(ValueError, ImageColor.getrgb, "#f0000")
        self.assertRaises(ValueError, ImageColor.getrgb, "#f000000")
        self.assertRaises(ValueError, ImageColor.getrgb, "#f00000000")
        self.assertRaises(ValueError, ImageColor.getrgb, "#f000000000")
        self.assertRaises(ValueError, ImageColor.getrgb, "#f00000 ")
def _generate_horizontal_text(text, font, text_color, font_size, space_width,
                              character_spacing, fit, word_split):
    image_font = ImageFont.truetype(font=font, size=font_size)

    space_width = int(image_font.getsize(" ")[0] * space_width)

    if word_split:
        splitted_text = []
        for w in text.split(" "):
            splitted_text.append(w)
            splitted_text.append(" ")
        splitted_text.pop()
    else:
        splitted_text = text

    piece_widths = [
        image_font.getsize(p)[0] if p != " " else space_width * 2
        for p in splitted_text
    ]
    text_width = sum(piece_widths)
    if not word_split:
        text_width += character_spacing * (len(text) - 1)

    text_height = max([image_font.getsize(p)[1] for p in splitted_text])

    txt_img = Image.new("RGBA", (text_width, text_height), (0, 0, 0, 0))
    txt_mask = Image.new("RGB", (text_width, text_height), (0, 0, 0))

    txt_img_draw = ImageDraw.Draw(txt_img)
    txt_mask_draw = ImageDraw.Draw(txt_mask, mode="RGB")
    txt_mask_draw.fontmode = "1"

    colors = [ImageColor.getrgb(c) for c in text_color.split(",")]
    c1, c2 = colors[0], colors[-1]

    fill = (
        rnd.randint(min(c1[0], c2[0]), max(c1[0], c2[0])),
        rnd.randint(min(c1[1], c2[1]), max(c1[1], c2[1])),
        rnd.randint(min(c1[2], c2[2]), max(c1[2], c2[2])),
    )

    for i, p in enumerate(splitted_text):
        txt_img_draw.text(
            (sum(piece_widths[0:i]) +
             i * character_spacing * int(not word_split), 0),
            p,
            fill=fill,
            font=image_font,
        )
        txt_mask_draw.text(
            (sum(piece_widths[0:i]) +
             i * character_spacing * int(not word_split), 0),
            p,
            fill=((i + 1) // (255 * 255), (i + 1) // 255, (i + 1) % 255),
            font=image_font,
        )

    if fit:
        return txt_img.crop(txt_img.getbbox()), txt_mask.crop(
            txt_img.getbbox())
    else:
        return txt_img, txt_mask, piece_widths
Exemple #60
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)