def update_track(self): logger.debug("Updating...") self.palette = None self.current_track = self.core.playback.get_current_track().get() if not self.current_track: logger.debug("No current track") return images = self.core.library.get_images([self.current_track.uri]).get() if not images: logger.debug("Image not found") return logger.info(images) image_uri = images[self.current_track.uri][0].uri if image_uri.startswith("http://") or image_uri.startswith("https://"): image = ColorThief(request.urlopen(image_uri)) else: image = ColorThief(image_uri) self.palette = image.get_palette(color_count=2, quality=1) self.update_volume() self.pixels.fill(self.palette[0]) logger.debug("Updated: %s", self.palette)
async def danbooru(self, ctx, *, tags=None): """Searches for NSFW images. NSFW means not safe for work. Basically it is just nudity and sex.""" if not ctx.channel.is_nsfw(): return await ctx.send( f'{ctx.tick(False)} This command can only be used at nsfw marked channels. You little pervert :smile:' ) embd = discord.Embed(description=f"**Searching** for **\"{tags}\"**..") embd = await ctx.send(embed=embd) if not tags: try: page = random.randint(1, 50) async with aiohttp.ClientSession() as cs: async with cs.get( f"https://yande.re/post.json?limit=1&page={page}" ) as r: r = await r.json() async with aiohttp.ClientSession() as cs: async with cs.get(r[0]['file_url']) as response: img = await response.read() colour_thief = ColorThief(BytesIO(img)) colour = colour_thief.get_color(quality=15) link = 'https://danbooru.donmai.us/posts/' + str(r[0]['id']) embed = discord.Embed(colour=discord.Color.from_rgb(*colour), title=f"Random Post", url=link) embed.set_image(url=r[0]['file_url']) embed.set_footer(text=f"♥ {r[0]['score']}") return await embd.edit(embed=embed) except Exception as e: return await embd.edit( content=f'An error occured!\n```\n{e}```') try: tags = tags.replace(" ", "+") page = random.randint(1, 10) async with aiohttp.ClientSession() as cs: async with cs.get( f"https://yande.re/post.json?tags={tags}&limit=1&page={page}" ) as r: r = await r.json() async with aiohttp.ClientSession() as cs: async with cs.get(r[0]['file_url']) as response: img = await response.read() colour_thief = ColorThief(BytesIO(img)) colour = colour_thief.get_color(quality=15) link = 'https://danbooru.donmai.us/posts/' + str(r[0]['id']) embed = discord.Embed(colour=discord.Color.from_rgb(*colour), title=f"\"{tags}\"", url=link) embed.set_image(url=r[0]['file_url']) embed.set_footer(text=f"♥ {r[0]['score']}") await embd.edit(embed=embed) except Exception as e: em = discord.Embed(title="No results found!") await embd.edit(embed=em)
def getColourPalette(self, path): """ Gets a list of the four most dominant colours in the image. """ image = ColorThief(path) try: image = ColorThief(path) palette = image.get_palette(color_count=4) del image return palette except: del image return [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]]
def checkBluePixel(inputPath): """ docstring """ im = cv2.imread(inputPath, 1) # Convert BGR to HSV hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110, 50, 50]) upper_blue = np.array([130, 255, 255]) # Threshold the HSV image to get only blue colors mask = cv2.inRange(hsv, lower_blue, upper_blue) # Bitwise-AND mask and original image res = cv2.bitwise_and(im, im, mask=mask) # save temp image cv2.imwrite(os.path.join(TEMP, 'temp.png'), res) ct = ColorThief(os.path.join(TEMP, 'temp.png')) palette = ct.get_palette(color_count=5) for p in palette: r = p[0] g = p[1] b = p[2] bgr = np.uint8([[[p[2], p[1], p[0]]]]) hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV) h = hsv[0][0][0] s = hsv[0][0][1] v = hsv[0][0][2] if ((h >= 110 and h <= 130) and (s >= 50 and s <= 255) and (v >= 50 and v <= 255)): return True break
def get_pallete_colors(imagePath): color_thief = ColorThief(imagePath) palette = color_thief.get_palette(color_count=9) colorList = [] for pal in palette: colorList.append(closest_color(pal)) return colorList
def dominant_colors(img, img_path, colors=2): temp_file = os.path.join( os.getcwd(), '.temps', '.temp_{0}'.format(img_path.split('/')[-1]) ) io.imsave(temp_file, img) #palette = ColorThief(temp_file).get_palette(color_count=colors) #os.remove(temp_file) palette = ColorThief(temp_file).get_palette(color_count=colors) os.remove(temp_file) colors = () for color in palette: r, g, b = color hex_ = '#{:02x}{:02x}{:02x}'.format(r, g, b) int_ = int(hex_[1:], 16) colors = colors + (interpolate(int_, place=0.000000001),) return colors
def get_colors_alt(image): """ Alternative color extractor. This only works with a modified version of colorthief which takes an PIL.Image object as a parameter instead of a file. :param image: PIL.Image object """ logger.debug("Extracting colors") width, height = image.size slices = int(width / 10) saved_colors = [] for i in range(10): box = (i * slices, 0, slices + (i * slices), height) cropped = image.crop(box) thief = ColorThief(cropped, ) if i == 0: principal = thief.get_color() saved_colors.append(principal) else: new_colors = thief.get_palette(color_count=100) new_color = get_most_diff(saved_colors, new_colors) if new_color is not None: saved_colors.append(new_color["color"]) return saved_colors
def generate_colors(image_bytes, font_path): image_ct = ColorThief(image_bytes) image_pil = Image.open(image_bytes).resize((500, 500)).convert("RGBA") colors = ColorThief.get_palette(image_ct, color_count=5) blank = Image.new("RGBA", (200, 500), (255, 255, 255, 0)) holder = Image.new("RGBA", (720, 500)) draw = ImageDraw.Draw(blank) start = 0 font = ImageFont.truetype(font_path, 15) for color in colors: draw.ellipse((0, start, 100, start + 100), fill=color) draw.text((120, start + 40), "#%02x%02x%02x" % color, (255, 255, 255), font=font) start += 100 holder.paste(image_pil, (220, 0)) holder.paste(blank, (0, 0)) final_bytes = get_bytes(holder) return final_bytes
def feature_color(pic_path): color_thief = ColorThief(pic_path) feature_color = color_thief.get_palette(3, 1) hex_rgb_list = [] for rgb in feature_color: hex_rgb_list.append(rgb_to_hex(rgb)) return hex_rgb_list, feature_color
def domcoll(request,var_c): log = [] jsob = {"clusters": 5,"path": 0} if request.method == "POST": try: data = request.POST["data"] print(data) received = json.loads(str(data)) jsob.update(received) path = jsob.get("path") clusters = jsob.get("clusters") tmp_file = 'tmp.jpg' urllib.request.urlretrieve(path,filename=tmp_file) color_thief = ColorThief(tmp_file) dominant_color = color_thief.get_color(quality=1) #one colour palette = color_thief.get_palette(color_count=int(clusters)) #multiple print(dominant_color) print(palette) results = {"colors":palette} return JsonResponse(results) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() other = sys.exc_info()[0].__name__ fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] errorType = str(exc_type) return JsonResponse({"isError": True, "error":str(e), "errorType":errorType, "function":fname, "line":exc_tb.tb_lineno, "log":log}) else: return HttpResponse("やっとできた、めっちゃ信じられない")
def word_to_color_thief(word): links = duckduckgo_search_urls(word) colors = [] for link in links: try: response = requests.get(link) im = Image.open(BytesIO(response.content)) color_thief = ColorThief(BytesIO(response.content)) peak = color_thief.get_color(quality=1) # im = im.convert('RGB') # im = im.resize((100, 100)) # ar = np.array(im) # shape = ar.shape # # if shape[-1]!=3: # # continue # ar = ar.reshape(np.product(shape[:2]), shape[2]).astype(float) # peak = median_centroid(ar,NUM_CLUSTERS=5) colors.append(peak) except: pass md = median_centroid(np.array(list(colors)).astype(float),NUM_CLUSTERS=3) # md = median_centroid(np.array(colors),NUM_CLUSTERS=3) color = binascii.hexlify(bytearray(int(c) for c in md)).decode('ascii') return color
def create_avatar_embed(message, user): """ Creates an embed object that will contain the avatar of the user and will 'mention' the author of the original message. Paramters --------- message : discord.Message Message that triggered the event. user : discord.Member User from which it's avatar is going to be retrieved. Returns ------- embed : discord.Embed embed containing the avatar of the user. """ requestor = message.author name = user.name avatarImage = user.avatar_url os.system(f'curl -o .img.png {avatarImage}') color_thief = ColorThief('.img.png') dominant_color = color_thief.get_color(quality=1) os.system('rm .img.png') clr = '0x' + '%02X%02X%02X' % dominant_color clr = int(clr, base=16) embed = discord.Embed(title=f"Avatar of {name}", value=requestor, color=clr) embed.set_image(url=avatarImage) return embed
def __init__(self, size: int, target_class: int, image_dir: str): super().__init__(size=size) color_distribution = defaultdict(int) directory = os.fsencode( os.path.join(image_dir, str(target_class).zfill(5))) for index, file in enumerate(os.listdir(directory)): filename = os.fsdecode(file) if not filename.endswith('.ppm'): continue thief = ColorThief(os.path.join(directory, file)) thief.image = ImageOps.posterize( Image.open(os.path.join(directory, file)), 6) for color in thief.get_palette(color_count=5, quality=1): color_distribution[color] += 1 if index >= TrainColorPopulationGeneratorConfiguration.MAX_IMAGE_COUNT: break self._colors, self._probabilities = zip(*color_distribution.items()) total = sum(self._probabilities) self._probabilities = [x / total for x in self._probabilities]
def update_output(n_clicks, value): dominant_colors = [] if value != None: res = None try: res = requests.get( "https://www.instagram.com/explore/tags/{}/?__a=1".format( re.sub(r'[^\w\s]', '', value)), headers={ 'User-agent': 'ig_hashtag_to_top_posts_0.1' }).json() except Exception as e: return "Error. The Instagram API limit has been reached; please wait a few hours or switch your internet network." nodes = res["graphql"]["hashtag"]["edge_hashtag_to_media"]["edges"] for n in nodes: color_thief = ColorThief(urlopen(n["node"]["thumbnail_src"])) palette = color_thief.get_palette(color_count=3) dominant_colors.extend(palette) random.shuffle(dominant_colors) divs = [] for color in dominant_colors: divs.append( make_color("rgb({}, {}, {})".format(color[0], color[1], color[2]))) return divs
def getColors(self): color_thief = ColorThief(self.image.path) dominant_colors = color_thief.get_palette(6, 20) # strip off the opening and closing parens from get_palette output # return a list of the 3 most dominant colors return [str(dominant_colors[i])[1:-1] for i in range(3)]
def _detect_dominant_colors(): """ :return: """ color_thief = ColorThief(CROPPED_IMAGE) return color_thief.get_palette(color_count=2)
def is_black_square(url): response = requests.get(url) img = Image.open(BytesIO(response.content)) color_thief = ColorThief(img) # check dominant color dominant_color = color_thief.get_color(quality=1) black_vals = [c for c in dominant_color if c < 12] is_dark = len(black_vals) == len(dominant_color) # check palette palette = color_thief.get_palette(quality=1) black_palette = [] # to distinguish "dark" images from truly all black images, make sure # all the colors in the palette are also dark if is_dark: for color in palette: black_vals = [c for c in color if c < 12] is_black_color = len(black_vals) == len(color) if is_black_color: black_palette.append(color) is_black_palette = len(black_palette) == len(palette) return is_dark and is_black_palette
def getColor(request): id = request.POST["id"] image_url = os.path.join(settings.MEDIA_ROOT, request.POST["img_url"]) print(image_url) color_thief = ColorThief(image_url) # print(img_root) # Image.open(img_root) # fd = urlopen('http://lokeshdhakar.com/projects/color-thief/img/photo1.jpg') # fd = img_url # f = io.BytesIO(fd.read()) # color_thief = ColorThief('/Users/ming/OOTD/OOTDweb/media/스크린샷_2019-03-29_오후_6.01.51_t3qhWj3.png') # color_thief = ColorThief(img_url) # /Users/ming/OOTD/OOTDweb/media/스크린샷_2019-03-29_오후_6.01.51_t3qhWj3.png # OOTDweb/media/스크린샷_2019-03-29_오후_6.01.51_t3qhWj3.png # color_thief = ColorThief(img_root) dominant_color = color_thief.get_color(quality=1) print(dominant_color) # build a color palette palette = color_thief.get_palette(color_count=4) palettes = [] for p in palette: print(p) palettes.append(p) # print(palette) context = { 'dominant_color': dominant_color, 'palettes': palettes } return HttpResponse(json.dumps(context), status=200, content_type='application/json')
def colorDetect(image): """Detect the colors in the image, format them to human names, and output them with descriptions.""" # Flag: Read the URL into an image if FLAGS.link: fd = urlopen(image) f = io.BytesIO(fd.read()) # Flag: Use screenshot for spectrum analysis elif FLAGS.ss: f = "static/screenshot.png" # Give the package an image to analyze color_thief = ColorThief(f) # Get the dominant color, saved in RGB color sequence as a tuple dominant_color = color_thief.get_color(quality=1) dc_name = get_colour_name(dominant_color) # Build a color palette, and run get_colour_name on each palette_list = [] palette = color_thief.get_palette(color_count=2, quality=5) for tup in palette: palette_list.append(get_colour_name(tup)) # Print out the colors and descriptions for them print("Dominant color: \n {}\n".format(colorCase(dc_name))) print("Color palette: ") for name in palette_list: color_description = colorCase(name) print(" Color name: {}\n".format(color_description))
def test_get_palette_sunset_quality_10_count_5(): imgpath = 'images/sunset.jpg' color_thief = ColorThief(imgpath) palette = color_thief.get_palette(quality=10, color_count=5) expected = [(163, 143, 178), (9, 6, 5), (99, 36, 32), (246, 222, 171), (153, 83, 63)] assert palette == expected
async def get_dominant_color(gh, url=None, quality=10): '''Devuelve el color dominante de una imagen desde una url''' maybe_col = os.environ.get('COLOR') url = url or gh.author.avatar_url if maybe_col: raw = int(maybe_col.strip('#'), 16) return discord.Color(value=raw) if not gh.is_valid_image_url(url): raise ValueError('La URL de la imagen no es válida.') try: async with gh.session.get(url) as resp: image = await resp.read() except: return discord.Color.default() with io.BytesIO(image) as f: try: color = ColorThief(f).get_color(quality=quality) except: return discord.Color.dark_grey() return discord.Color.from_rgb(*color)
def colorCode(): global prop_color color_thief = ColorThief('image.jpg') dominant_color = color_thief.get_color(quality=1) prop_color = colorsys.rgb_to_hsv(dominant_color[0], dominant_color[1], dominant_color[2]) return prop_color
async def get_dominant_color(self, url=None, quality=10): '''Returns the dominant color of an image from a url''' maybe_col = os.environ.get('COLOR') url = url or self.author.avatar_url if maybe_col: raw = int(maybe_col.strip('#'), 16) return discord.Color(value=raw) if not self.is_valid_image_url(url): raise ValueError('Invalid image url passed.') try: async with self.session.get(url) as resp: image = await resp.read() except: return discord.Color.default() with io.BytesIO(image) as f: try: color = ColorThief(f).get_color(quality=quality) except: return discord.Color.dark_grey() return discord.Color.from_rgb(*color)
def get_color(img_url): with urllib.request.urlopen(img_url) as url: f = io.BytesIO(url.read()) color_thief = ColorThief(f) # get the dominant color rgb_tuples = color_thief.get_palette(color_count=6, quality=1) return ['#%02x%02x%02x' % rgb_tuple for rgb_tuple in rgb_tuples]
async def _dominant_color_from_url(url): """Returns an rgb tuple consisting the dominant color given a image url.""" with BytesIO(await _read_image_from_url(url)) as f: # TODO: Make my own color-grabber module. This is ugly as hell. loop = asyncio.get_event_loop() get_colour = functools.partial(ColorThief(f).get_color, quality=1) return await loop.run_in_executor(None, get_colour)
def ajax_submitwallpaper(request): response_data = {} if request.method == 'POST': form = ModelWallpaperForm(request.POST) if form.is_valid(): f = form.save() filename = f.link.split("/")[-1] ext = filename.split('.')[-1] old_path = 'media/sucker/' + request.POST[ 'keywords'] + '/' + filename new_path = 'media/wallpaper/' + str(f.id_wallpaper) + '.' + ext shutil.copyfile(old_path, new_path) loc = new_path.replace('media/', '') f.wallpaper = loc f.save() color_thief = ColorThief('media/' + f.wallpaper.name) pale = '' pallet = color_thief.get_palette(color_count=6) for x, colo in enumerate(pallet): c = ('#%02x%02x%02x' % (colo[0], colo[1], colo[2])) pale = pale + c + ';' f.colors = pale f.save() post_tags = request.POST['tags'] for t in filter(None, post_tags.split(',')): tags = Tag.objects.filter(tag=t) if not tags: newtag = Tag(tag=t) newtag.save() tag = Tag.objects.get(tag=t) wallpaper_tag = Wallpaper_tag(tag=tag, wallpaper=f) wallpaper_tag.save() resizeall(f) response_data = {'is_valid': True, 'id': f.id_wallpaper} return JsonResponse(response_data)
def getDominantColor(self, imagePath, resType=str): """ 获取指定图片的主色调\n Parameters ---------- imagePath : 图片路径\n reType : 返回类型,str返回十六进制字符串,否则为rgb元组 """ self.imagePath = imagePath colorThief = ColorThief(imagePath) palette = colorThief.get_palette(quality=9) # 调整调色板明度 palette = self.__adjustPaletteValue(palette) for rgb in palette[:]: h, s, v = self.rgb2hsv(rgb) if h < 0.02: palette.remove(rgb) if len(palette) <= 2: break palette = palette[:3] palette.sort(key=lambda rgb: self.rgb2hsv(rgb)[1], reverse=True) self.rgb = palette[0] # 根据指定的返回类型决定返回十六进制颜色代码还是元组 if resType is str: rgb = "".join([hex(i)[2:].rjust(2, "0") for i in self.rgb]) return rgb return self.rgb
def generate_hex_info(self, long_way: bool = False) -> None: if long_way: # This method is much more computationally intensive and much more # difficult to debug, but it's generally more accurate and doesn't # fail as much as colorthief does. We can optionally trigger this # method through the admin panel if colorthief returns a result that # is wildly wrong. # lovingly ripped from https://stackoverflow.com/a/43111221 self.card_img.file.seek(0) img = io.imread(self.card_img.file) pixels = np.float32(img.reshape(-1, 3)) n_colors = 5 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, 0.1) flags = cv2.KMEANS_RANDOM_CENTERS # this line is super painful in computation time. We kind of get # around that by only having it parse the resized small card image; # if it runs on the full-size image, it could take a minute or two # to complete. _, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags) _, counts = np.unique(labels, return_counts=True) dominant = palette[np.argmax(counts)] self.hex_color = self.get_hex(dominant) else: ct_image = ColorThief(self.card_img.path) self.hex_color = self.get_hex(ct_image.get_color(quality=1)) self.complement_hex = self.get_complement(self.hex_color)
def dominant_color_from_url(url, tmp_file='tmp.jpg'): '''Downloads ths image file and analyzes the dominant color''' urllib.urlretrieve(url, tmp_file) color_thief = ColorThief(tmp_file) dominant_color = color_thief.get_color(quality=1) os.remove(tmp_file) return dominant_color
def readStatesMeasured(file, leds_dict, measures): # Get a photo # Check state of leds # put it into dict from detect leds for key in leds_dict.keys(): image_rgb = file cropped = image_rgb[leds_dict[key]["top"]:leds_dict[key]["bottom"], leds_dict[key]["left"]:leds_dict[key]["right"]] skimage.io.imsave("temp/" + str(str(key)) + ".jpg", cropped, check_contrast=False) color_thief = ColorThief("temp/" + str(str(key)) + ".jpg") dominant_color = color_thief.get_color(quality=1) ## TBD: Set color boundaries for better recognition for init_state in measures[key].keys(): # image_rgb = io.imread(file) state = "not recognized" # print(measures[key][init_state]["brightness_low"], int(sum(dominant_color)/3)) # print(measures[key][init_state]["r_low"], measures[key][init_state]["r_high"]) # print(measures[key][init_state]["g_low"], measures[key][init_state]["g_high"]) # print(measures[key][init_state]["b_low"], measures[key][init_state]["b_high"]) if int(sum(dominant_color) ) / 3 > measures[key][init_state]["brightness_low"]: if dominant_color[0] in range(measures[key][init_state]["r_low"], measures[key][init_state]["r_high"]) and \ dominant_color[1] in range(measures[key][init_state]["g_low"], measures[key][init_state]["g_high"]) and \ dominant_color[2] in range(measures[key][init_state]["b_low"], measures[key][init_state]["b_high"]): state = init_state else: state = "off" leds[key]["dominant_color"] = dominant_color leds[key]["led_state"] = state return leds