def gerar_paleta(self): furta_cor = ColorThief(self.caminho) # Pegar cor dominante self.cor_dominante = furta_cor.get_color(quality=1) # Pegar paleta de 5 cores, em qualidade 5 (vem como padrao 10) self.paleta = furta_cor.get_palette(color_count=5, quality=5)
def _get_colorthief_palette(cls, image_path, color_count) -> List[HexColor]: from colorthief import ColorThief # pylint: disable=import-error,useless-suppression color_thief = ColorThief(image_path) palette = color_thief.get_palette(color_count=color_count) hex_palette = [color_hex_from_list(color) for color in palette] return hex_palette
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
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 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 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 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 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 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 _detect_dominant_colors(): """ :return: """ color_thief = ColorThief(CROPPED_IMAGE) return color_thief.get_palette(color_count=2)
def get_image_color(self, img_name, additional_color=2, delete_temp=True): """ This method is aim to to find the main_color and additional color of an image The parameter of input is the URL of an image delete_temp default is False, if True then the temp image will be removed after get the colors """ color_list = {} # img_name = "temp.jpg" # if the given image is URL then it will download image from url to local: # urllib.request.urlretrieve(img_url, img_name) img2_name = self.remove_image_bg(img_name) color_thief = ColorThief(img2_name) # dominant_color to only get 1 main color of image: # dominant_color = color_thief.get_color(quality=1) # dominant_color = self.get_similar_colors(dominant_color, k=1) # palette color will get multiple colors from image palette_colors = color_thief.get_palette(color_count=additional_color, quality=10) additional_colors = [] for color in palette_colors: additional = self.get_similar_colors(color, k=1) additional_colors.append(additional) # color_list['main_color'] = dominant_color[0] # color_list['additional_colors'] = additional_colors if delete_temp: # os.remove("temp.jpg") os.remove("%s_removed.png" % img_name) return sum(additional_colors, [])
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]
def ambient(): with mss() as sct: filename = sct.shot(mon=-1, output='screen.png') color_thief = ColorThief('screen.png') palette = color_thief.get_palette(color_count=2, quality=3) #print(palette) return(palette[1])
def album_art_color(): if token: sp = spotipy.Spotify(auth=token) current_song = sp.current_user_playing_track() global curr if curr['item']['name'] == current_song['item']['name']: threading.Timer(2, album_art_color).start() return album = current_song['item']['album'] image_url = album['images'][0]['url'] curr = current_song fd = urlopen(image_url) f = io.BytesIO(fd.read()) cf = ColorThief(f) palette = cf.get_palette(color_count=9, quality=1) print(palette) for i in range(8): r = palette[i][0] g = palette[i][1] b = palette[i][2] for x in range(4): strip.set_color(index=(i * 4) + x, red=r, green=g, blue=b) time.sleep(.02) else: print("Can't get token for", username) threading.Timer(2, album_art_color).start()
def return_palette(self, im): from colorthief import ColorThief color_thief = ColorThief(im) # get the dominant color dominant_color = color_thief.get_color(quality=6) res = (color_thief.get_palette(color_count=6)) return res
def generate_pattern(self, n_palette=5): color_thief = ColorThief(self.path + "original/" + self.file) palette = color_thief.get_palette(color_count=n_palette) palette.sort(key=lambda rgb: self.sort_luminance(rgb, 16)) self.palette = palette w = 500 h = w // n_palette list_colors = [Image.new("RGB", (w, h), color=i) for i in palette] min_shape = sorted([(np.sum(i.size), i.size) for i in list_colors])[0][1] palettes = np.vstack( (np.asarray(i.resize(min_shape)) for i in list_colors)) palettes = Image.fromarray(palettes) file = self.file.replace('_original', '_palette') try: palettes.save(self.path + 'palette/' + file) except FileNotFoundError as e: print(f"{e}, Creating the folder and save it") os.makedirs(self.path + 'palette') palettes.save(self.path + 'palette/' + file)
def handle(self, *args, **options): # response = urllib2.urlopen(str('static/img/artworks-000261133514-g8rmw0-t500x500.jpg')) # soup = BeautifulSoup(response.read(), "lxml") # # for link in soup.find_all('script'): # script_info = link.string #Fix your shitty API soundcloud!! # soundcloud_avatar = re.findall(r'https?://[^\s<>"]+|www\.[^\s<>"]+', # str(script_info.encode('utf-8')))[0].replace('large', 't500x500') file_path = 'DreamEasyApp/static/sass/_colors.scss' src = open( file_path ).read() # Create parser object p = parser.Stylesheet( options=dict( compress=True ) ) print p.loads( src ) color_thief = ColorThief('DreamEasyApp/static/img/dreameasy.jpg') # get the dominant color dominant_color = color_thief.get_color(quality=10) # build a color palette palette = color_thief.get_palette(color_count=6, quality=10) print dominant_color, palette
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 get_dominant_colors(company, location, company_type): company = company.lower() headers = {'Content-Type': 'image/png; charset=utf-8'} request = Request( 'https://api.ritekit.com/v1/images/logo?domain=' + company + '.com&client_id=c3a8350984d9f9547d0e438a7668a78ffc5f26b4b5f2', headers=headers) response_body = urlopen(request).read() im = Image.open(BytesIO(response_body)) rgb_im = im.convert('RGB') rgb_im.save('company_img.png') image = 'company_img.png' rec_dict = LocationRecommendation.location_similarity( location, company_type) # print(rec_dict) color_thief = ColorThief(image) palette = color_thief.get_palette(color_count=2, quality=1) colors = [] for color in palette[:2]: colors.append('#%02x%02x%02x' % color) final_dict = { "primary_color": colors[0], "secondary_color": colors[1], "recommendations": rec_dict } return final_dict
def get_dominant_colors(img_path): color_thief = ColorThief(img_path) # get the dominant color dominant_color = color_thief.get_color(quality=1) palette = color_thief.get_palette(color_count=5) print(palette)
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 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)
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 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 __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 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 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 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 filter(image_path): root = "djangoProject" path = root + image_path color_thief = ColorThief(path) palette = color_thief.get_palette(color_count=6) # get the lowest value -> black background min_value = min(palette) result = [] for i in palette: if i > min_value: result.append(i) # dominant colour dominant = result[0] dominant1 = dominant dominant2 = dominant dominant_add_5 = list(dominant1) dominant_sub_5 = list(dominant2) count_add = 0 count_sub = 0 # increase the value of 5 for i in dominant_add_5: dominant_add_5[count_add] = i + 5 count_add += 1 dominant_add_5 = (dominant_add_5) # decrease the value of 5 for j in dominant_sub_5: dominant_sub_5[count_sub] = j - 5 count_sub += 1 dominant_sub_5 = (dominant_sub_5) print("add", dominant_add_5) print("sub", dominant_sub_5) tag = [] for key, value in flower_tag.items(): for item in value: item = list(item) # print(type(item)) # if the value is in the range of dominant within -/+ 5 if item[0] > dominant_sub_5[0] and item[1] > dominant_sub_5[ 1] and item[2] > dominant_sub_5[2]: if item[0] < dominant_add_5[0] and item[1] < dominant_add_5[ 1] and item[2] < dominant_add_5[2]: print(key) tag.append(key) # remove dulicates tag_name = list(dict.fromkeys(tag)) tag_int = [] for i in tag_name: tag_int.append(int(i)) return tag_int
def classify_color(self, direccion): color_thief = ColorThief(direccion) # build a color palette palette = color_thief.get_palette(color_count=6) print palette #print palette color_rgb = palette[1] return self.etiquetado(color_rgb)
def determine_color_codes_for_image(image): """ Gets the most prominent colors in the image. """ color_thief = ColorThief(image.image_name) try: return color_thief.get_palette() except: pass return []
def GetAlbumColor(albumName): albumImage = GetAlbum(albumName) if(albumImage != False): color_theif = ColorThief(albumImage) dominant_color = color_theif.get_palette(color_count=6,quality=3) webbrowser.open_new_tab('http://www.wolframalpha.com/input/?i=RGB+' + str(dominant_color[0])) #get rid of this line to get rid of launching wolframalpha return dominant_color else: print("No Album Found") return False
def getShade(request): from colorthief import ColorThief color_thief = ColorThief('images.jpg') dominant_color = color_thief.get_color(quality=1) palette=color_thief.get_palette(color_count=6) comp_color={'green':'magenta','white':'black','blue':'red','red':'blue','black':'white'} img1=cv2.imread(request.POST["image"],0) ref=ColorThief(request.POST["image"])#ref image is the image being checked dominant_color=ref.get_color(quality=1) #print img1.shape refR,refG,refB=dominant_color #print refR,refG,refB compR=255-refR compG=255-refG compB=255-refB return dominant_color;
for p in Photo.select(): n += 1 if n % 100 == 0: print 'processed: ' + str(n) if p.avg_color == None: try: img = Image.open(img_path % p.insta_id) img.thumbnail((1, 1)) p.avg_color = '%d,%d,%d' % img.getpixel((0, 0)) p.save() except IOError: print 'CANNOT OPEN ' + p.insta_id #p.delete_instance() if p.main_color == None: color_thief = ColorThief(img_path % p.insta_id) mc = color_thief.get_color(quality=1) p.main_color = '%d,%d,%d' % mc p.save() if p.colors == None: color_thief = ColorThief(img_path % p.insta_id) clrs = color_thief.get_palette(color_count=2, quality=1) # 3 colors! p.colors = ' '.join('%d,%d,%d' % c for c in clrs) p.save()
#!/usr/bin/python # simple color palette generator # good for themeing/color schemes # make sure you have the 'colorthief' module installed # save this as /usr/bin/colorpal # make script executable # usage: colorpal <path/to/image> import sys from colorthief import ColorThief cf = ColorThief(sys.argv[1]) p = cf.get_palette() for c in p: print('#%02x%02x%02x' % c)
# -*- coding: utf-8 -*- import sys if sys.version_info < (3, 0): from urllib2 import urlopen else: from urllib.request import urlopen import io from colorthief import ColorThief fd = urlopen('http://lokeshdhakar.com/projects/color-thief/img/photo1.jpg') f = io.BytesIO(fd.read()) color_thief = ColorThief(f) print(color_thief.get_color(quality=1)) print(color_thief.get_palette(quality=1))
from colorthief import ColorThief import numpy as np import cv2 color_thief = ColorThief('patterns/1.jpg') # get the dominant color dominant_color = color_thief.get_color(quality=1) # build a color palette palette = color_thief.get_palette(color_count=4) print(dominant_color) print(palette) bar = np.zeros((50, 300, 3), dtype="uint8") startX = 0 for color in zip(palette): endX = startX + (0.25 * 300) cv2.rectangle(bar, (int(startX), 0), (int(endX), 50), color.astype("uint8").tolist(), -1) startX = endX plt.imshow(bar) plt.show()
#!/usr/bin/env python2 import sys from colorthief import ColorThief from PIL import Image, ImageDraw OFFSET = 10 OUTLINE = 'black' color_thief = ColorThief(sys.argv[1]) dominant_color = color_thief.get_color(quality=1) palette = color_thief.get_palette(color_count=int(sys.argv[2])) im = Image.open(sys.argv[1]) draw = ImageDraw.Draw(im, 'RGBA') palette.insert(0, dominant_color) for index, p in enumerate(palette): _outline = OUTLINE if index is 0: _outline = 'red' dot = (100 * index) + OFFSET dot2 = 100 * (index + 1) dim = [(dot, 10), (dot2, 10), (dot2, 100), (dot, 100)] draw.polygon(dim, fill=p, outline=_outline) print(index, dot, dot2) print(dominant_color) print(palette) print(len(palette))
def run(self): self.ocr_areas = None self.min_contrast = 0.0 self.max_contrast = 255.0 self.settings = Settings() self.bestlist = [] self.image_data = [] for file in self.imglist: print file #print file image = cv2.imread(unicode(file).encode(sys.getfilesystemencoding())) h, w, c = image.shape #if h > 1080: # width = int(w*(900.0/h)) # image = cv2.resize(image, (width, 900)) self.calculate(image) clean = {} total = len(self.bestlist) for i in xrange(int(self.min_contrast), int(self.max_contrast)): count = 0 temp = 0 for item in self.bestlist: if float(i) in item: count+=1 temp+=item[float(i)] if count == total: clean[i] = temp #print clean cleanlist = sorted(clean.items(), key=lambda x: x[1]) tolerance = cleanlist[0][1] + 2 tolerated = [] for j in range(len(cleanlist)): if cleanlist[j][1] < tolerance: tolerated.append(cleanlist[j][0]) #print tolerated self.bestcontrast = reduce(lambda x, y: x + y, tolerated) / len(tolerated) self.error = cleanlist[0][1] #print self.bestcontrast """ hist = [] for i in xrange(256): if i in clean: hist.append(clean[i]) else: hist.append(0) hist = np.asarray(hist) cv2.normalize(hist,hist,0,1000,cv2.NORM_MINMAX) h = np.zeros((1000,256,3)) for x in xrange(len(hist)): cv2.line(h,(x,hist[x]),(x,hist[x]),(255,255,255)) y=np.flipud(h) cv2.imshow('histogram',y) cv2.waitKey(0) """ #self.emit(SIGNAL("update(int,int)"), counter, toprocess) #self.result = "Success: "+unicode(len(outcomeok))+" Fail: "+unicode(len(outcomefail)) ct = ColorThief(image) palette = ct.get_palette() for i in xrange(1,6): self.settings.reg.setValue('color'+str(i), QColor(*(palette[i-1])).name()) self.emit(SIGNAL("finished(float, int, PyQt_PyObject)"), self.bestcontrast, self.error, self.image_data)
def _get_colorthief_palette(cls, image_path, color_count): from colorthief import ColorThief # pylint: disable=import-error color_thief = ColorThief(image_path) palette = color_thief.get_palette(color_count=color_count) hex_palette = [color_hex_from_list(color) for color in palette] return hex_palette