def get_colors(src: pathlib.Path, use_palette: Optional[bool] = True) -> Tuple[str, str]: """(main, secondary) HTML color codes from an image path""" def rgb_to_hex(r: int, g: int, b: int) -> str: """hexadecimal HTML-friendly color code for RGB tuple""" return "#{}{}{}".format(*[str(hex(x)[2:]).zfill(2) for x in (r, g, b)]).upper() def solarize(r: int, g: int, b: int) -> Tuple[int, int, int]: # calculate solarized color for main h, l, s = colorsys.rgb_to_hls( float(r) / 256, float(g) / 256, float(b) / 256) r2, g2, b2 = [int(x * 256) for x in colorsys.hls_to_rgb(h, 0.95, s)] return r2, g2, b2 ct = colorthief.ColorThief(src) if use_palette: # extract two main colors from palette, solarizing second as background palette = ct.get_palette(color_count=2, quality=1) # using the first two colors of the palette? mr, mg, mb = palette[0] sr, sg, sb = solarize(*palette[1]) else: # extract main color from image and solarize it as background mr, mg, mb = ct.get_color(quality=1) sr, sg, sb = solarize(mr, mg, mb) return rgb_to_hex(mr, mg, mb), rgb_to_hex(sr, sg, sb)
def test_same_output(): image_path = 'tests/veverka_lidl.jpg' fast_palette = fast_colorthief.get_palette(image_path, 5, 10) colorthief_orig = colorthief.ColorThief(image_path) original_palette = colorthief_orig.get_palette(5, 10) assert (fast_palette == original_palette)
def print_speed(): image = cv2.imread('tests/veverka_lidl.jpg') image = PIL.Image.open('tests/veverka_lidl.jpg') image = image.convert('RGBA') image = np.array(image).astype(np.uint8) iterations = 10 start = time.time() for i in range(iterations): fast_colorthief.get_palette(image) print(f'CPP numpy {(time.time() - start) / iterations}') start = time.time() for i in range(iterations): fast_colorthief.get_palette('tests/veverka_lidl.jpg') print(f'CPP image path {(time.time() - start) / iterations}') start = time.time() for i in range(iterations): colorthief_orig = colorthief.ColorThief('tests/veverka_lidl.jpg') colorthief_orig.get_palette() print(f'Python image path {(time.time() - start) / iterations}')
def __init__(self, image: str, path: str): """ Initialise the palette """ self.thief = colorthief.ColorThief(image) self.path = path self.colours = [self.thief.get_color(1)] + [ *self.thief.get_palette(color_count=50, quality=1) ]
def avgcolor(image): try: if type(image) == str and image.startswith('http'): image = urllib.request.urlopen(image).read() return int( hex( int( '%02x%02x%02x' % colorthief.ColorThief( io.BytesIO(image)).get_color(quality=10), 16)), 0) except: return tt.dcolor
def _get_color_palette(url): import colorthief image_path = core.vector_generator.download_image(url) try: palette = colorthief.ColorThief(image_path).get_palette( color_count=6, quality=1) except Exception as e: # TODO: Probably caused by empty color. Handle case. palette = [] if url != image_path: os.remove(image_path) return json.dumps(palette)
def handle(self, *args, **kwargs): queryset = Playlist.objects.all() for pl in queryset: color_thief = colorthief.ColorThief(pl.photo) # get the dominant color dominant_color = color_thief.get_color(quality=1) print(pl.playlist_uri, pl.name, dominant_color, dominant_color[0], dominant_color[1], dominant_color[2]) pl.photo_red = dominant_color[0] pl.photo_green = dominant_color[1] pl.photo_blue = dominant_color[2] pl.save()
def save(self, *args, **kwargs): print("SAVING!!!!") if not self.pk: super().save(*args, **kwargs) picture_url = sp.playlist(self.playlist_uri)['images'][0]['url'] tracks = sp.playlist_tracks(self.playlist_uri, fields=None, limit=10, offset=0, market=None, additional_types=('track', )) total_dance = 0 total_energy = 0 total_instrumentalness = 0 total_valence = 0 n = len(tracks["items"]) for i in range(n): features = sp.audio_features(tracks["items"][i]['track']['external_urls']['spotify']) if features[0] is not None: dance = features[0]['danceability'] energy = features[0]['energy'] instrumentalness = features[0]['instrumentalness'] valence = features[0]['valence'] else: dance = 0 energy = 0 instrumentalness = 0 valence = 0 total_dance += dance total_energy += energy total_instrumentalness += instrumentalness total_valence += valence avg_energy = round(total_energy / n, 2) avg_dance = round(total_dance / n, 2) avg_instrumentalness = round(total_instrumentalness / n, 2) avg_valence = round(total_valence / n, 2) self.avg_dance = avg_dance self.avg_energy = avg_energy self.avg_instru = avg_instrumentalness self.avg_valence = avg_valence print(picture_url) result = urllib.request.urlretrieve(picture_url) self.photo.save(os.path.basename(self.playlist_uri),File(open(result[0], 'rb'))) color_thief = colorthief.ColorThief(self.photo) dominant_color = color_thief.get_color(quality=1) self.photo_red = dominant_color[0] self.photo_green = dominant_color[1] self.photo_blue = dominant_color[2] return super(Playlist, self).save(*args, **kwargs)
def get_color_code(song): try: img_url = get_lastfm_cover(song) if img_url: logger.info(img_url) resp = requests.get(img_url) file = BytesIO(resp.content) ct = colorthief.ColorThief(file) return '{:02x}{:02x}{:02x}'.format(*ct.get_color()) except Exception as e: logger.error('Failed to get cover {}'.format(str(e))) pass txt = next( (song.get(x) for x in ('album', 'artist', 'title') if x in song)) return hashlib.md5(txt.encode('utf-8')).hexdigest()[:6]
def process_img(image): quality = 1 start = time.time() cimage = colorthief.ColorThief(io.BytesIO(image)) colors = [] try: colors = cimage.get_palette(color_count=10, quality=quality) for color in colors: if not is_grey(color, 25): return color finally: logging.error( "Processed album cover ({} bytes) in {} seconds at quality {}.". format(len(image), time.time() - start, quality))
__version__ = '0.0.1' import math import glob, os from PIL import Image from PIL import ImageDraw import json import colorthief import PIL colors=[] patterns=[] print("start go") for filename in glob.glob("ishihara-elbum/circle/*.jpg"): base=Image.open(filename) # base=base.convert("RGBA") color_o=colorthief.ColorThief(filename) p=color_o.get_palette(6, quality=10) # for x in p: # colors.append((x[0],x[1],x[2])) patterns.append(p) # im_blank=Image.new('RGB', base.size, (255,255,255)) # i=0 # image_=ImageDraw.ImageDraw(im_blank) # for item in p: # image_.polygon([(1,1+i),(1,10+i),(96,10+i),(96,1+i)], fill=item) # i=i+10 # del image_ # im_blank.show() # print(patterns) print("start write")
if False: wrong_original = [] exceptions = [] from os import listdir from os.path import isfile, join path = '/data/logo_detection/dataset_version_10/train/images' for i, image_path in enumerate([join(path, f) for f in listdir(path)]): print(f"{i} {image_path}") try: fast_palette = fast_colorthief.get_palette(image_path, 5, 10) colorthief_orig = colorthief.ColorThief(image_path) original_palette = colorthief_orig.get_palette(5, 10) except RuntimeError: exceptions.append(image_path) continue wrong_original_output = False for rgb in original_palette: if max(rgb) >= 256: # error in original colorthief wrong_original_output = True break if wrong_original_output: wrong_original.append(image_path) continue
async def track(self, ctx, *, query=None): if not query: await ctx.reply(f"**Syntax:** {config.COMMAND_PREFIX}track <query>" ) return try: token = self.get_spotify_auth_token(ctx.author.id) except Exception as e: await ctx.reply('Failed to get auth token: ' + str(e)) return formdata = {'q': query, 'type': 'track'} headers = { 'User-Agent': USER_AGENT, 'Accept': 'application/json', 'Authorization': token } r = requests.get('https://api.spotify.com/v1/search', headers=headers, params=formdata) json = r.json() tracks = json['tracks'] items = tracks['items'] embed = None if len(items) >= 1: top = items[0] track_link = None album_name = None album_link = None album_image = None album_released = None if 'external_urls' in top and 'spotify' in top['external_urls']: track_link = top['external_urls']['spotify'] if 'album' in top: album_name = top['album']['name'] if 'external_urls' in top['album'] and 'spotify' in top[ 'album']['external_urls']: album_link = top['album']['external_urls']['spotify'] if 'images' in top['album'] and len( top['album']['images']) >= 1: album_image = top['album']['images'][0]['url'] album_released = top['album']['release_date'] artist_strings = [] if 'artists' in top: for artist in top['artists']: name = artist['name'] if 'external_urls' in artist and 'spotify' in artist[ 'external_urls']: artist_strings.append( f"[{name}]({artist['external_urls']['spotify']})") else: artist_strings.append(name) embed = discord.Embed(title=top['name'], url=track_link) embed.set_thumbnail(url=album_image) if len(artist_strings) >= 1: name = "Artist" if len(artist_strings) >= 2: name += "s" embed.add_field(name=name, value=', '.join(artist_strings), inline=True) if album_name is not None: if album_link is not None: embed.add_field(name="Album", value=f"[{album_name}]({album_link})", inline=True) else: embed.add_field(name="Album", value=album_name, inline=True) if album_image is not None: try: thief = colorthief.ColorThief( urllib.request.urlopen(album_image)) r, g, b = thief.get_color() embed.colour = discord.Colour.from_rgb(r, g, b) except Exception as e: traceback.print_exc() pass if 'duration_ms' in top: embed.add_field(name='Duration', value=songtime(top['duration_ms']), inline=True) if album_released is not None: embed.add_field(name="Release Date", value=album_released, inline=True) self.last_context[ctx.channel.id] = top['uri'] await ctx.reply( f"The search query `{query}` returned {tracks['total']:,} results.", embed=embed)
async def e621(self, ctx, *, words=None): params = {"tags": "", "limit": 25} if words is not None: params['tags'] = words if not ctx.channel.is_nsfw(): params['tags'] += " rating:safe" if config.E621_USERNAME and config.E621_API_KEY: params['login'] = config.E621_USERNAME params['api_key'] = config.E621_API_KEY headers = {"User-Agent": "TOHELLANDBOT (csnxs)"} r = requests.get("https://e621.net/posts.json", params=params, headers=headers) j = r.json() posts = j['posts'] if len(j['posts']) < 1: await ctx.reply( f"No results for that query: `{words}`\nConsult the e621 cheatsheet for help with searching: <https://e621.net/help/cheatsheet>" ) return post = random.choice(posts) if not ctx.channel.is_nsfw() and post['rating'] != 's': await ctx.reply("Sinful post detected...") return scores = post['score'] authors = "unknown" desc = post['description'] if 'tags' in post and 'artist' in post['tags'] and post['tags'][ 'artist']: authors = ', '.join(post['tags']['artist']) upload_date = dateutil.parser.parse(post['created_at']) if len(desc) > 256: desc = desc[:253] + "..." embed = discord.Embed(title=authors, url=f"https://e621.net/posts/{post['id']}", timestamp=upload_date) embed.set_image(url=post['file']['url']) if post['description']: embed.add_field(name="Description", value=post['description'][:250], inline=False) embed.set_footer( text= f"Post #{post['id']} • Rating: {RATINGS_MAP[post['rating']]} • Score: ↑ {scores['up']} ↓ {scores['down']} = {scores['total']} • Favs: {post['fav_count']} • Comments: {post['comment_count']}" ) try: thief = colorthief.ColorThief( urllib.request.urlopen(post['preview']['url'])) r, g, b = thief.get_color() embed.colour = discord.Colour.from_rgb(r, g, b) except Exception as e: traceback.print_exc() pass await ctx.reply(embed=embed)
def get_colors(data): try: return colorthief.ColorThief(data).get_palette(color_count=5) except Exception: return None
# Get some juicy info user = network.get_user(config["USER"]["Username"]) tracks = user.get_top_tracks(cacheable=True) for track in tracks: album = track.item.get_album() color = None if album: picture_page = album.get_cover_image() if picture_page: filename = os.path.join("cache", picture_page.split('/')[-1]) if not os.path.exists("cache"): os.makedirs("cache") if not os.path.isfile(filename): urllib.request.urlretrieve(picture_page, filename) print(picture_page, filename) color = colorthief.ColorThief(filename).get_color() else: color = (255, 255, 255) else: color = (255, 255, 255) for tag in track.item.get_top_tags(): tags[tag.item.name] = tags.get(tag.item.name, 0) + 1 if tag.item.name not in tag_albums or random.random() < 0.1: tag_albums[tag.item.name] = color print(tags) print(tag_albums) cloud = wordcloud.WordCloud(width=800, height=600, color_func=single_color_func) cloud.generate_from_frequencies(tags)
async def googlebooks(self, ctx, *, query=None): if not query: await ctx.reply( '**Syntax: `%sgooglebooks <query>`**\n' 'This command returns the top result for the given search query on Google Books.\n\n' 'You can use certain keywords in your query, e.g.:\n' '`isbn:9780943151168` - search by ISBN, similarly `lccn:` and `oclc:` are supported\n' '`intitle:JTHM` - search by title\n' '`inauthor:"Jhonen Vasquez"` - search by author\n' '`inpublisher:SLG` - search by publisher\n\n' 'See also: <https://developers.google.com/books/docs/v1/using#PerformingSearch>' % (config.COMMAND_PREFIX)) return url = 'https://www.googleapis.com/books/v1/volumes?q=' + urllib.parse.quote(query) try: r = requests.get(url) json = r.json() totalItems = json['totalItems'] if totalItems < 1: await ctx.reply('There were no results for that query.') else: volume = json['items'][0] volumeInfo = volume['volumeInfo'] link = 'https://books.google.co.uk/books?id=' + volume['id'] title = volumeInfo['title'] if 'subtitle' in volumeInfo: title += ': ' + volumeInfo['subtitle'] embed = discord.Embed(title=title, url=link) if 'imageLinks' in volumeInfo: imageLinks = volumeInfo['imageLinks'] if 'thumbnail' in imageLinks: embed.set_thumbnail(url=imageLinks['thumbnail']) elif 'smallThumbnail' in imageLinks: embed.set_thumbnail(url=imageLinks['smallThumbnail']) if 'authors' in volumeInfo: name = 'Author' if len(volumeInfo['authors']) == 1 else 'Authors' embed.add_field(name=name, value=', '.join(volumeInfo['authors']), inline=True) if 'pageCount' in volumeInfo: embed.add_field(name='Pages', value=str(volumeInfo['pageCount']), inline=True) if 'publisher' in volumeInfo: embed.add_field(name='Published by', value=volumeInfo['publisher'], inline=True) if 'publishedDate' in volumeInfo: embed.add_field(name='Publication date', value=volumeInfo['publishedDate'], inline=True) if 'averageRating' in volumeInfo and 'ratingsCount' in volumeInfo: embed.add_field(name='Rating', value=f"{volumeInfo['averageRating']}/5 stars (from {volumeInfo['ratingsCount']} ratings)", inline=True) isbns = self.get_isbns(volumeInfo) if len(isbns) > 0: embed.add_field(name='ISBN', value=isbns, inline=True) if 'description' in volumeInfo: text = volumeInfo['description'] if len(text) > 500: text = text[:500] + '...' embed.add_field(name='Description', value=text, inline=False) try: thief = colorthief.ColorThief(urllib.request.urlopen(embed.thumbnail.url)) r, g, b = thief.get_color() embed.colour = discord.Colour.from_rgb(r, g, b) except Exception as e: traceback.print_exc() pass await ctx.reply(f'Your query returned {totalItems} result{"" if totalItems == 1 else "s"}.', embed=embed) except Exception as e: await ctx.reply("Failed to look up `" + query + "`: " + str(e))