def validate_color(color: str) -> bool: if not color: return False try: getrgb(color) except ValueError: return False return True
def get_color(color): """ Interpret some string as a color represented as a integer three tuple """ if len(color) == 32 and all(c in hexdigits for c in color): return hash_to_color(color) try: return getrgb(color) except: return getrgb("#" + color)
def __bobo_traverse__(self, REQUEST, name): if not hasattr(self, 'color'): getrgb(name) # as a side effect it validates or throws an exception self.color = name self.__doc__ = "An accessible traversable view" # Make the Zope publisher happy return self elif not hasattr(self, 'filename'): self.filename = name self.__doc__ = "An accessible traversable view" return self else: raise AttributeError
def __bobo_traverse__(self, REQUEST, name): if not hasattr(self, 'color'): getrgb( name) # as a side effect it validates or throws an exception self.color = name self.__doc__ = "An accessible traversable view" # Make the Zope publisher happy return self elif not hasattr(self, 'filename'): self.filename = name self.__doc__ = "An accessible traversable view" return self else: raise AttributeError
def is_valid_color(self, color): """ Test if param color is a valid color that is compatible with Pillow getrgb() Valid colors include names like red, blue, green that are recognised by getrgb(), and hex values like #44FC313. For full details on supported color formats, see https://pillow.readthedocs.io/en/latest/reference/ImageColor.html#module-PIL.ImageColor """ try: getrgb(color) return True except ValueError: return False
def parse_value(value: Any): """ Parses the input string returning rgb int-tuple. Supported formats: * RGB ('r,g,b', 'r, g, b') * HEX ('00ff00') * Arcade colors ('BLUE', 'DARK_BLUE') """ import arcade if value in (None, '', 'None'): return None if type(value) in (int, float, list): return value # if a string, then try parsing if isinstance(value, str): try: return int(value) except ValueError: pass # arcade color if isinstance(value, str) and hasattr(arcade.color, value.upper()): return getattr(arcade.color, value) # hex if len(value) in (3, 6) and ',' not in value: try: return getrgb(f'#{value}') except ValueError: pass # rgb try: return getrgb(f'rgb({value})') except ValueError: pass # last chance some Path if os.path.exists(value): return Path(value) warn(f'Could not parse style value: {value}') return value
def curve(color='#5C87B2', width=4, number=6): """验证码添加干扰线""" from .bezier import make_bezier if not callable(color): c = getrgb(color) def color(): return c def drawer(image_, text_): dx, height = image_.size dx = dx / number path = [(dx * i, random.randint(0, height)) for i in range(1, number)] bcoefs = make_bezier(number - 1) points = [] for coefs in bcoefs: points.append( tuple( sum([coef * p for coef, p in zip(coefs, ps)]) for ps in zip(*path))) draw = Draw(image_) draw.line(points, fill=color(), width=width) return image_ return drawer
def mapdraw(args,colorbar): img = Image.new('RGB',(args['xlen'],args['ylen']),'white') draw = Draw(img) for key,value in args['datamap'].iteritems(): draw.point(value,getrgb(str(key))) img2 = img.resize((args['y'],args['y']), Image.BILINEAR) imgclr = colorbar.resize((args['colorbar'],img2.size[1]), Image.BILINEAR) # ===== ENTIRE IMAGE CREATION W/ TEXT===== imgbox = Image.new('RGB',((300+args['y']+args['colorbar']),(img2.size[1]+200)),args['background']) imgbox.paste(img2,(100,100)) imgbox.paste(imgclr,((200+img2.size[0]),100)) drawbox = Draw(imgbox) title = args['title'] titlesize = 50 # future user input font = truetype("/library/fonts/Arial.ttf",titlesize) smfontsize = 30 # future user input smfont = truetype("/library/fonts/Arial.ttf",smfontsize) titlewidth = font.getsize(title)[0] drawbox.text(((imgbox.size[0]/2 - titlewidth/2), titlesize/2),title,(0,0,0),font=font) drawbox.text(((imgbox.size[0] - 95),100),str(args['max']),(0,0,0),font=smfont) drawbox.text(((imgbox.size[0] - 95),(100 + img2.size[1] - smfontsize)),str(args['min']),(0,0,0),font=smfont) imgbox.show() if 'title' in args: title = args['title']+'_'+str(args['min'])+'_'+str(args['max'])+'.png' else: title = 'output_'+str(args['min'])+'_'+str(args['max'])+'.png' imgbox.save(args['save']+'/'+title)
def image_tint(src, tint='#fffab5'): 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 = getrgb(tint) tl = 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 = 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 += tuple(range(256)) # for 1:1 mapping of copied alpha values return Image.merge(*merge_args).point(luts)
def background(image, color): if not isinstance(color, tuple) or len(color) != 4 or color[3] != 0: if image.mode in PALETTE_MODES: if 'transparency' in image.info: if not isinstance(color, tuple): color = getrgb(color) trans = image.info['transparency'] del image.info['transparency'] palette = image.getpalette() palette[trans * 3 + 0] = color[0] palette[trans * 3 + 1] = color[1] palette[trans * 3 + 2] = color[2] image.putpalette(palette) else: bg = Image.new(image.mode, image.size, color) bg.info = image.info if image.mode in ('RGBA', 'LA'): if isinstance(color, tuple) and len(color) == 4: # semitransparent background paste_composite(bg, image) else: # solid background bg = bg.convert(image.mode[:-1]) bg.paste(image.convert(image.mode[:-1]), (0, 0), image) else: bg.paste(image, (0, 0)) image = bg image.info['_filter_background_color'] = color return image
def set_status(text=None, bgcolor='black'): if not text: text = [("Raspberry Pi ", (255, 0, 0))] font = ImageFont.truetype( os.path.dirname(os.path.realpath(__file__)) + '/C&C Red Alert [INET].ttf', 13) all_text = '' for text_color_pair in text: t = text_color_pair[0] all_text += t + ' ' width, ignore = font.getsize(all_text) # img = Image.new('RGB', (max(width, 128), 16), bgcolor) img = Image.new('RGB', (max(width, 128), 16), 'black') draw = ImageDraw.Draw(img) x = 0 for text_color_pair in text: t = text_color_pair[0] # c = text_color_pair[1] c = getrgb(bgcolor) draw.text((x, 2), t, c, font=font) x = x + font.getsize(t)[0] img.save('status.ppm')
def main(): args = parse_argument() length = count_char(args.text) fontsize = args.font_size width_p = int(fontsize / 72. * DPI[0] * length) height_p = int(fontsize / 72. * DPI[1]) color_rgba = getrgb(args.color) + (int( (1. - args.text_transparency) * 255), ) # write text img = Image.new('RGBA', (width_p, height_p), (255, 255, 255, 0)) draw = ImageDraw.Draw(img) font = ImageFont.truetype(font=args.font, size=fontsize) draw.text((0, 0), args.text, font=font, fill=color_rgba) # remove margin crop = img.split()[-1].getbbox() img = img.crop(crop) # make directory dir_path = args.output_dir_path if dir_path: if not os.path.isdir(dir_path): os.makedirs(dir_path) output_path = os.path.join(dir_path, args.text + ".png") img.save(output_path, dpi=DPI)
def hex_to_rgb(self, hex): """ Convert a given color from a hexadecimal value to a rgb tuple. For example a hex value of "C9A814" would get converted to (201, 168, 20). :param hex: the hexadecimal code (string) representing a color value. :return: Returns the tuple value as a string. """ return getrgb('#' + hex) # convert to hex value
def __call__(self): portal_skins = getToolByName(self.context, 'portal_skins') if not hasattr(self, 'filename'): self.filename = self.request.img if not hasattr(self, 'color'): self.color = self.request.color color = self.color img = portal_skins.restrictedTraverse(self.filename) img_data = getattr(img, '_data', False) or getattr(img, 'data', False) image = Image.open(StringIO(img_data)) alpha = None if image.mode == 'RGBA': alpha = image.split()[3] elif image.mode == 'P' and image.format == 'PNG': # PNG images can have transparency and be palette-based. # This is probably not the most clever method but it works alpha = image.convert('RGBA').split()[3] r,g,b = getrgb(color) if image.mode != 'L': grayscale_image = image.convert('L') else: grayscale_image = image newimage = ImageOps.colorize(grayscale_image, (r,g,b),(255,255,255)) output = StringIO() if alpha: newimage.putalpha(alpha) newimage.save(output, format='PNG') self.request.response.setHeader('Content-Type','image/png') return output.getvalue()
def image_tint(src, tint="#ffffff"): # From https://stackoverflow.com/a/12310820 if src.mode not in ["RGB", "RGBA"]: raise TypeError("Unsupported source image mode: {}".format(src.mode)) src.load() tr, tg, tb = getrgb(tint) tl = getcolor(tint, "L") if not tl: tl = 1 tl = float(tl) sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb)) 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 = grayscale(src) if Image.getmodebands(src.mode) < 4: merge_args = (src.mode, (l, l, l)) else: a = Image.new("L", src.size) a.putdata(src.getdata(3)) luts += tuple(range(256)) return Image.merge(*merge_args).point(luts)
def heatmap(area_num, pic, area_colors): for index, row in enumerate(area_num): heat_color = getrgb(area_colors[index]) floodFill(pic, None, (row[2] * 10, row[3] * 10), newVal=heat_color) imwrite('test.png', cvtColor(pic, COLOR_BGR2RGB)) return heatmap
def hl_code(code, name, user_data): style: Style = user_data.get('style') or default_style formatter = find_formatter_class(style.format) css_style = ('pre.code{{ font-family: {}; }}'.format(style.font) + 'td.linenos{ ' 'background-color: rgba(240, 240, 240, 0.11); }') scheme:pygments.style.Style = get_style_by_name(style.color_scheme) rgb = getrgb(scheme.background_color)[:3] lineno_bg = (*rgb, 20) highlighted = highlight(code, PythonLexer(), formatter(style=style.color_scheme, linenos = True, font_name=style.font, fontfamily=style.font, full=True, line_number_bg=lineno_bg, cssstyles=css_style)) if style.format == 'html': highlighted = highlighted.replace( 'background-color: #f0f0f0;', 'background-color: rgba(240, 240, 240, 0.06);' ) if isinstance(highlighted, str): highlighted = highlighted.encode() img = BytesIO(highlighted) img.name = 'code_{}.{}'.format(name, style.format) return img
def image_tint(path: str, tint: str) -> Image: src = Image.open(path) if src.mode not in ("RGB", "RGBA"): raise TypeError(f"Unsupported source image mode: {src.mode}") src.load() tr, tg, tb = getrgb(tint) tl = 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 = grayscale(src) # 8-bit luminosity version of whole image if Image.getmodebands(src.mode) < 4: merge_args: tuple = (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 += tuple(range(256)) # for 1:1 mapping of copied alpha values image = Image.merge(*merge_args).point(luts) new_image = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background new_image.paste(image, (0, 0), image) return new_image
def background(color='#EEEECC'): color = getrgb(color) def drawer(image, text): Draw(image).rectangle([(0, 0), image.size], fill=color) return image return drawer
def __call__(self): portal_skins = getToolByName(self.context, 'portal_skins') if not hasattr(self, 'filename'): self.filename = self.request.img if not hasattr(self, 'color'): self.color = self.request.color color = self.color img = portal_skins.restrictedTraverse(self.filename) img_data = getattr(img, '_data', False) or getattr(img, 'data', False) image = Image.open(StringIO(img_data)) alpha = None if image.mode == 'RGBA': alpha = image.split()[3] elif image.mode == 'P' and image.format == 'PNG': # PNG images can have transparency and be palette-based. # This is probably not the most clever method but it works alpha = image.convert('RGBA').split()[3] r, g, b = getrgb(color) if image.mode != 'L': grayscale_image = image.convert('L') else: grayscale_image = image newimage = ImageOps.colorize(grayscale_image, (r, g, b), (255, 255, 255)) output = StringIO() if alpha: newimage.putalpha(alpha) newimage.save(output, format='PNG') self.request.response.setHeader('Content-Type', 'image/png') return output.getvalue()
def image_tint(im, tint='#ff0000'): src = Image.new('RGB', im.size) src.paste(im) tr, tg, tb = getrgb(tint) tl = 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 = (list(map(lambda lr: int(lr * sr + 0.5), range(256))) + list(map(lambda lg: int(lg * sg + 0.5), range(256))) + list(map(lambda lb: int(lb * sb + 0.5), range(256)))) l = 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)
def image_tint(src, tint='#ffffff'): 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 = getrgb(tint) tl = 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 = 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 += tuple(range(256)) # for 1:1 mapping of copied alpha values return Image.merge(*merge_args).point(luts)
def image_tint(self, source_path, tint='#ffffff'): ''' Take an image from a path and convert it to a tinted string for sprite coloration. :param source_path: sting path to image :param tint: string color code in hex :return: string of modified image ''' img_source = Image.open(source_path) # Get the image from specified path tint_red, tint_green, tint_blue = getrgb(tint) # Get color tint of each color tint_lum = getcolor(tint, "L") # Tint color luminosity if tint_lum == 0: # Avoid division by 0 tint_lum = 1 tint_lum = float(tint_lum) # Compute luminosity preserving tint factors sr, sg, sb = map(lambda tv: tv / tint_lum, (tint_red, tint_green, tint_blue)) # per component adjustments # create look-up tables to map luminosity to adjusted tint # (using floating-point math only to compute table) luts = (list(map(lambda lr: int(lr * sr + 0.5), range(256))) + list(map(lambda lg: int(lg * sg + 0.5), range(256))) + list(map(lambda lb: int(lb * sb + 0.5), range(256)))) l = grayscale(img_source) # 8-bit luminosity version of whole image if Image.getmodebands(img_source.mode) < 4: merge_args = (img_source.mode, (l, l, l)) # for RGB verion of grayscale else: # include copy of img_source image's alpha layer a = Image.new("L", img_source.size) a.putdata(img_source.getdata(3)) merge_args = (img_source.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) # Return string of image
def save(self, *args, **kwargs): if not self.avatar: self.avatar = "avatar/image_" + self.name[0].lower() + ".png" colors = [ "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#f1c40f", "#e67e22", "#e74c3c", "#f39c12", "#d35400", "#c0392b", ] img = Image.new('RGB', (64, 64), getrgb(colors[ord(self.name[0].upper()) % 15])) img_io = BytesIO() font = ImageFont.truetype('../../arial.ttf', 35) draw = ImageDraw.Draw(img) w, h = draw.textsize(self.name[0].upper(), font=font) draw.text(((64 - w) / 2, (54 - h) / 2), self.name[0].upper(), font=font, fill=(255, 255, 255)) img.save(img_io, format='PNG', quality=100) self.avatar = ContentFile(img_io.getvalue(), 'image_' + self.name[0].upper() + '.png') super(ClientProfile, self).save(*args, **kwargs)
def text(fonts, font_sizes=None, drawings=None, color: Union[str, Callable] = '#5C87B2', squeeze_factor=0.8): """ 向验证码上写文字 :param fonts: ttf 字体文件,Iterable :param font_sizes: 字体大小,Iterable 真正的字体是 fonts 和 font_sizes 的笛卡尔积 :param drawings: 文字变换(混淆)方法,每生成一个字母,所有 drawings 都会变换这个字母 :param color: 文字颜色,或者是一个返回颜色的函数 (例如随机颜色) :param squeeze_factor: 挤压的比例,这个值越低,验证码重叠程度越高 """ fonts = tuple( truetype(name, size) for name in fonts for size in font_sizes or (65, 70, 75)) if not callable(color): c = getrgb(color) def color(): return c def drawer(image_, text_): draw = Draw(image_) char_images = [] for c_ in text_: font = random.choice(fonts) c_width, c_height = draw.textsize(c_, font=font) # char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) o_width, o_height = font.getoffset(c_) char_image = Image.new(mode='RGB', size=(c_width + o_width, c_height + o_height), color=(0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), c_, font=font, fill=color()) char_image = char_image.crop(char_image.getbbox()) for drawing in drawings: char_image = drawing(char_image) char_images.append(char_image) width, height = image_.size offset_ = int( (width - sum(int(i.size[0] * squeeze_factor) for i in char_images[:-1]) - char_images[-1].size[0]) / 2) # 将单个字符图像画在验证码上 for char_image in char_images: c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) image_.paste(char_image, (offset_, int((height - c_height) / 2)), mask) offset_ += int(c_width * squeeze_factor) return image_ return drawer
def hex_to_rgb(self, hex): """ Convert a given color from a hexadecimal value to a rgb tuple. For example a hex value of "C9A814" would get converted to (201, 168, 20). Returns the tuple value as a string. Parameters: [In] hex - the hexidecimal code (string) representing a color value. """ # print '#' + hex, " ", getrgb('#' + hex) return getrgb('#' + hex) # convert to hex value
def colour(self, value=None): if value is not None: self._colour = value colour = np.uint8(getrgb(value)[::-1]).reshape((1, 1, 3)) hsv = cv2.cvtColor(colour, cv2.COLOR_BGR2HSV).reshape((3)) self.low = np.array([hsv[0] - 10, 50, 50]) self.high = np.array([hsv[0] + 10, 255, 255]) else: return self._colour
def __init__(self, text: str, font: FreeTypeFont = None, color: Union[str, Sequence] = (0, 0, 0)): self.text = text self.font = font if type(color) is str: self.color = getrgb(color) else: self.color = color
def set_color(color): # (3) """ Set REG LED Color. """ rgb = getrgb(color) # (4) print("LED is {} ({})".format(color, rgb)) pi.set_PWM_dutycycle(GPIO_RED, 255 - rgb[0]) # (5) <<<< DIFFERENCE pi.set_PWM_dutycycle(GPIO_GREEN, 255 - rgb[1]) # <<<< DIFFERENCE pi.set_PWM_dutycycle(GPIO_BLUE, 255 - rgb[2]) # <<<< DIFFERENCE
def background(color='#EEEECC'): """ 验证码底色 必须第一个调用,因为底色上色方法是画了一个矩形 """ color = getrgb(color) def drawer(image_, text_): Draw(image_).rectangle([(0, 0), image_.size], fill=color) return image_ return drawer
def recolor_image(image, old_color_range, color): new_color = getrgb(color) img = image.convert('RGBA') data = img.getdata() new_data = [] for item in data: if (item[-1] != 0) and (item[0] in old_color_range): new_data.append(new_color) else: new_data.append(item) img.putdata(new_data) return img
def colormap(args): rangelen = args['max'] - args['min'] rangemid = args['min'] + (rangelen / 2) rangemax = args['max'] rangemin = args['min'] cr2 = rgb2hex.linear_gradient(args['colors'][1],args['colors'][2],(int(rangelen/2*1000))+1)['hex'] cr1 = rgb2hex.linear_gradient(args['colors'][0],args['colors'][1],(int(rangelen/2*1000))+1)['hex'] dictlist = {} # === PAIR DATA WITH COLOR MAP === for y,sl in enumerate(args['data']): # for each sublist within dataset (row) for x,i in enumerate(sl): # for each point in sublist (column) val = args['colors'][1] #top half of data range if i > rangemid: if i <= rangemax: val = cr2[int((i - (rangemin + rangelen/2)) * 1000)] else: val = args['colors'][2] #bottom half of data range elif i < rangemid: if i >= rangemin: val = cr1[int((i - rangemin) * 1000)] else: val = args['colors'][0] # mask if 'mask' in args: if i <= args['mask'][0]: val = args['mask'][1] # add to dict if val in dictlist: dictlist[val].append((x,y)) else: dictlist[val] = [(x,y)] args['datamap'] = dictlist # ===== COLORBAR CREATION ===== clr = (cr1 + cr2) clr = clr[::-1000] widthclr = args['colorbar'] heightclr = len(clr) imgclr = Image.new("RGB",(widthclr,heightclr),"white") drawclr = Draw(imgclr) for y,val in enumerate(clr): for x in range(widthclr): drawclr.point((x,y),getrgb(str(val))) return args, imgclr
def convertColor(color): color = RGBtoLab(getrgb(color)) colorIds = { '#7986cb': 1, '#33b679': 2, '#8e24aa': 3, '#e67c73': 4, '#f6c026': 5, '#f5511d': 6, '#039be5': 7, '#616161': 8, '#3f51b5': 9, '#0b8043': 10, '#d60000': 11 } distances = [] for colorId, id in colorIds.items(): colorIdLab = RGBtoLab(getrgb(colorId)) distances.append((sqrt((color[0] - colorIdLab[0])**2 + (color[1] - colorIdLab[1])**2 + (color[2] - colorIdLab[2])**2), id)) return min(distances)[1]
def rainbow_example(loops=1, delay_secs=0.01): # (7) """ Cycle RGB LED through a range of colors. """ saturation = 100 # 0 (grayer) to 100 (full color) brightness = 100 # 0 (darker) to 100 (brighter) for i in range(0, loops): for hue in tuple(range(0, 360)) + tuple(range(360, -1, -1)): # 0..360..0 color_str = "hsb({}, {}%, {}%)".format(hue, saturation, brightness) rgb = getrgb(color_str) pi.set_PWM_dutycycle(GPIO_RED, 255 - rgb[0]) # <<<< DIFFERENCE pi.set_PWM_dutycycle(GPIO_GREEN, 255 - rgb[1]) # <<<< DIFFERENCE pi.set_PWM_dutycycle(GPIO_BLUE, 255 - rgb[2]) # <<<< DIFFERENCE sleep(delay_secs)
def make_installer_image(logo_file): from PIL import Image from PIL.ImageColor import getrgb color = getrgb("#77216F") logo = Image.open(logo_file).convert("RGB").resize((164, 164)) newdata = [] for item in logo.getdata(): if item == (0, 0, 0): newdata.append(color) else: newdata.append(item) logo.putdata(newdata) region = logo.crop((0, 0, 164, 164)) img = Image.new("RGB", (164, 314), color) img.paste(region, (0, 75)) return img
def parse_args(): parser = argparse.ArgumentParser( description="Finds the nearest colorname for the given color.") parser.add_argument("color", metavar="COLOR", type=str, help="The color to search for") parser.add_argument("-c", "--concise", action='store_true', help="If to be short and concise without link") args = parser.parse_args() try: rgb = getrgb(args.color) except ValueError: print("Unable to parse color", file=sys.stdout) sys.exit(1) return rgb, args.concise
def noise(number=40, color='#EEEECC', level=2): if not callable(color): c = getrgb(color) color = lambda: c def drawer(image, text): width, height = image.size dx = width / 10 width = width - dx dy = height / 10 height = height - dy draw = Draw(image) for i in xrange(number): x = int(random.uniform(dx, width)) y = int(random.uniform(dy, height)) draw.line(((x, y), (x + level, y)), fill=color(), width=level) return image return drawer
def picture(dic=None): """ラスターデータ""" from cv2 import imread, floodFill from PIL.ImageColor import getrgb pos = [ eval(s) for s in ( '0 15,15 52,6 57,9 54,19 52,9 52,19 52,24 ' '52,34 49,31 47,31 47,34 52,36 47,36 47,37 47,24 37,31 34,32 ' '32,34 44,36 42,34 37,34 42,39 37,39 34,43 32,39 29,39 29,41 ' '27,39 31,44 29,44 19,38 12,42 22,39 17,41 11,44 22,46 22,44 ' '17,46 19,48 7,48 3,50 2,52 7,54 8,49 9,54 5,59 54,56').split() ] p = imread(path.join(path.dirname(__file__), 'japan.png')) if dic: for k, v in dic.items(): i = k if isinstance(k, int) else pref_code(k) if 1 <= i <= 47: c = v if isinstance(v, tuple) else getrgb(v) floodFill(p, None, (pos[i][0] * 10, pos[i][1] * 10), c) return p
def curve(color='#5C87B2', width=1, number=10): from wheezy.captcha.bezier import make_bezier if not callable(color): c = getrgb(color) color = lambda: c def drawer(image, text): dx, height = image.size dx = dx / number path = [(dx * i, random.randint(0, height)) for i in range(1, number)] bcoefs = make_bezier(number - 1) points = [] for coefs in bcoefs: points.append(tuple(sum([coef * p for coef, p in zip(coefs, ps)]) for ps in zip(*path))) draw = Draw(image) draw.line(points, fill=color(), width=width) return image return drawer
def MatchColour(colour, low_l=0.2, high_l=0.65, s_factor=1): """Determine a colour that contrasts with a given colour. The resulting colour pair can be used as foreground and background, guaranteeing readable text. The match colour is determined by flipping the luminisoty to 10% or 90%, while keeping the hue and saturation stable. The only exception are yellowish colours, for those the luminosity is always set to 10%. """ (r, g, b) = getrgb(colour) (h, l, s) = colorsys.rgb_to_hls(r / 255.0, g / 255.0, b / 255.0) if 0.16 < h < 0.33: l = low_l elif l > 0.49: l = low_l else: l = high_l s *= s_factor (r, g, b) = colorsys.hls_to_rgb(h, l, s) return '#%02x%02x%02x' % (r * 255, g * 255, b * 255)
def str2color(string: str) -> Tuple[int]: color = string if re.fullmatch('\\((\\d+), *(\\d+), *(\\d+)\\)', color): # rgb color result = re.fullmatch('\\((\\d+), *(\\d+), *(\\d+)\\)', color) c = [] for i in range(1, 4): c.append(int(result.group(i))) return tuple(c) elif re.fullmatch('#([0-9a-fA-F]+)', color): # Hex color result = re.fullmatch('#([0-9a-fA-F]+)', color) h = '{:0>6}'.format(result.group(1)) c = [] for i in range(3): a = h[i * 2:i * 2 + 2] c.append(int(a, 16)) return tuple(c) else: # name color return getrgb(color)
def captcha_text(fonts, font_sizes=None, drawings=None, color='#5C87B2', squeeze_factor=0.8): fonts = tuple([truetype(name, size) for name in fonts for size in font_sizes or (65, 70, 75)]) if not callable(color): c = getrgb(color) color = lambda: c def drawer(image, text): draw = Draw(image) char_images = [] for c in text: font = random.choice(fonts) c_width, c_height = draw.textsize(c, font=font) c_height *= 2 char_image = Image.new('RGB', (c_width, c_height), (0, 0, 0)) char_draw = Draw(char_image) char_draw.text((0, 0), c, font=font, fill=color()) char_image = char_image.crop(char_image.getbbox()) for drawing in drawings: char_image = drawing(char_image) char_images.append(char_image) width, height = image.size offset = int((width - sum(int(i.size[0] * squeeze_factor) for i in char_images[:-1]) - char_images[-1].size[0]) / 2) for char_image in char_images: c_width, c_height = char_image.size mask = char_image.convert('L').point(lambda i: i * 1.97) image.paste(char_image, (offset, int((height - c_height) / 2)), mask) offset += int(c_width * squeeze_factor) return image return drawer
def set_status(text=None, bgcolor='black'): if not text: text = [("Raspberry Pi ", (255, 0, 0))] font = ImageFont.truetype(os.path.dirname(os.path.realpath(__file__)) + '/C&C Red Alert [INET].ttf', 13) all_text = '' for text_color_pair in text: t = text_color_pair[0] all_text += t + ' ' width, ignore = font.getsize(all_text) # img = Image.new('RGB', (max(width, 128), 16), bgcolor) img = Image.new('RGB', (max(width, 128), 16), 'black') draw = ImageDraw.Draw(img) x = 0 for text_color_pair in text: t = text_color_pair[0] # c = text_color_pair[1] c = getrgb(bgcolor) draw.text((x, 2), t, c, font=font) x = x + font.getsize(t)[0] img.save('status.ppm')
def to_hls(self, colour): import colorsys from PIL.ImageColor import getrgb (r, g, b) = getrgb(colour) return colorsys.rgb_to_hls(r / 255.0, g / 255.0, b / 255.0)
def black(self, colorstring, percent): factor = int(percent)/100.0 r,g,b = getrgb(colorstring) colors = map(lambda x: int((x+1)*factor), (r,g,b) ) return get_colorstring(*colors)
def white(self, colorstring, percent): factor = (100-int(percent))/100.0 r,g,b = getrgb(colorstring) colors = map(lambda x: int(256 - (255-x+1)*factor), (r,g,b) ) return get_colorstring(*colors)
def main(): # Assumed that watermark has transparent background wm = raw_input("Provide Watermark: ") wm = validate(wm, 'watermark') p = raw_input("Provide Photo: ") p = validate(p, 'photo') wm_size = raw_input("Width of Watermark (As % of Photo Width): ") try: assert float(wm_size) >= 0.0 and float(wm_size) <= 100.0 except: sys.exit("Invalid watermark percentage.") color = raw_input("Provide Hex Color Code: #") check_color(color) rgbcolor = hex_to_rgb(color) uw = raw_input("Provide Border Width (max 100px): ") try: assert uw.strip().isdigit() assert int(uw) > 0 and int(uw) <= 100 except: sys.exit("Invalid border value.") width = int(uw) img = Image.open(p) w, h = img.size # Create border in desired color bh = w+width*2 bw = h+width*2 border = Image.new('RGB', (bh, bw)) for x in range(0, border.size[0]): for y in range(0, border.size[1]): border.putpixel((x,y), rgbcolor) # Paste the image on the border border.paste(img, (width, width)) # Save copy of image without watermark borderpic = os.path.basename(os.path.normpath(p)) borderpic = borderpic.split('.', 1)[0] picname = borderpic + "-border.png" print "Saving bordered picture as " + str(picname) border.save(picname) wmark = Image.open(wm).convert('RGBA') wmarkpix = wmark.load() ww, wh = wmark.size wwmark = Image.new('RGBA', (ww, wh)) # Make all non-transparent pixels into the color of choice hexcolor = '#' + str(color).lower() red, green, blue = getrgb(hexcolor) for x in range(ww): for y in range(wh): r, g, b, a = wmarkpix[x, y] if (a == 255): wwmark.putpixel((x,y), (red, green, blue)) else: wwmark.putpixel((x,y), (255, 255, 255, 0)) waterpic = os.path.basename(os.path.normpath(wm)) waterpic = waterpic.split('.', 1)[0] wname = waterpic + "-recolor.png" print "Saving recolored watermark as " + str(wname) wwmark.save(wname) # Alter watermark size, maintaining aspect ratio size = int(w*(float(wm_size)/100)), int(h*(float(wm_size)/100)) wwmark.thumbnail(size, Image.ANTIALIAS) sname = waterpic + "-small.png" wwmark.save(sname) # Load in the final watermark, image wmarkpic = Image.open(os.path.abspath(picname)) wwidth, wheight = wmarkpic.size wmarksm = Image.open(os.path.abspath(sname)) wtwidth, wtheight = wmarksm.size # Place the watermark in the right corner r, g, b, a = wmarksm.split() top = Image.merge("RGB", (r, g, b)) mask = Image.merge("L", (a,)) wmarkpic.paste(top, (wwidth-wtwidth-width, wheight-wtheight-width), mask) print "Saving watermarked picture as " + str(borderpic) + "-wm.png." wmarkpic.save(borderpic + "-wm.png")
def IsBright(colour): """Check if a (RGB) colour is a bright colour.""" (r, g, b) = getrgb(colour) (h, l, s) = colorsys.rgb_to_hls(r / 255.0, g / 255.0, b / 255.0) return l > 0.50
def __setitem__(self, key, value): ''' Auto-convert CSS/HTML color hashes (e.g. #112233) ''' if isinstance(value, str): value = getrgb(value) dict.__setitem__(self, key, value)