Exemple #1
0
    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 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
Exemple #3
0
    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]
Exemple #4
0
 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 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
Exemple #6
0
    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)]
Exemple #7
0
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 _detect_dominant_colors():
        """

        :return:
        """
        color_thief = ColorThief(CROPPED_IMAGE)
        return color_thief.get_palette(color_count=2)
    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)
Exemple #10
0
 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
Exemple #11
0
    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
Exemple #12
0
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
Exemple #13
0
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 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]
Exemple #15
0
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 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 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()
Exemple #18
0
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 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
Exemple #21
0
    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, [])
Exemple #22
0
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
Exemple #23
0
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
Exemple #24
0
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
Exemple #25
0
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("やっとできた、めっちゃ信じられない")
Exemple #26
0
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
Exemple #27
0
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
Exemple #28
0
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
Exemple #29
0
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 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 determine_dominant_color_for_image(image):
    """ Determines the dominant color of a single image. """
    color_thief = ColorThief(image.image_name)
    try:
        return color_thief.get_color(quality=1)
    except:
        pass
    return 'nocolor'
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 []
Exemple #33
0
def dominantColor(filename):
    l = glob.glob(filename + 'frame*.jpg')
    arr = []

    for i in l:
        color_thief = ColorThief(i)
        dominant_color = color_thief.get_color(quality=1)
        arr.append(dominant_color)
        print dominant_color
    return arr
def getDominantColor(userUrl):
    userData = requests.get(userUrl).json()
    profileUrl = userData['avatar_url']

    ctPalette = CT(cStringIO.StringIO(urllib.urlopen(profileUrl).read()))
    # get the dominant color
    dominantColorRGB = ctPalette.get_color(quality=1)

    hex = convertRGBtoHex(dominantColorRGB)
    return hex
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
Exemple #36
0
 def get_color(self):
     if self.color:
         return self.color
     else:
         if not self.logo:
             self.get_logo()
         try:
             color_thief = ColorThief(self.logo)
             self.color = '#%02x%02x%02x' % color_thief.get_color(quality=1)
         except:
             self.color = "#0000ff"
         self.save()
         return self.color
Exemple #37
0
def get_product_info_internal(user_id, upc):
    logger_header('/get_product_info_internal')

    # Get data from searchupc API
    params = {'request_type': UPC_REQUEST_TYPE,
              'access_token': UPC_ACCESS_TOKEN,
              'upc': upc}
    barcode_data = requests.get(SEARCH_UPC_URL, params=params)
    barcode_data = barcode_data.json()
    product_name = barcode_data["0"]["productname"]
    product_img_url = barcode_data["0"]["imageurl"]

    # Download product image
    img_response = requests.get(product_img_url)

    # Get dominant color as RGB value
    color_thief = ColorThief(StringIO(img_response.content))
    dominant_color = color_thief.get_color(quality=1)
    dominant_color = tuple([color / 255.0 for color in dominant_color])
    red, green, blue = dominant_color[0], \
                       dominant_color[1], \
                       dominant_color[2]

    # Convert RGB color to HSV color, then increase saturation
    # value to 100%
    hsv_color = colorsys.rgb_to_hsv(red, green, blue)
    hue = hsv_color[0]
    saturation = hsv_color[1]
    value = hsv_color[2]
    new_rgb_color = colorsys.hsv_to_rgb(hue, 1.0, value)
    new_rgb_color = tuple([color * 255 for color in new_rgb_color])

    # Get color name of closest match
    color_name = get_color_name(new_rgb_color)

    logger.debug(new_rgb_color)
    logger.debug(color_name)

    product_info = {
        "product_name": product_name,
        "color": color_name,
        "product_img": product_img_url
    }

    db = MootDao()
    try:
        db.save_product(user_id, upc, product_name, color_name, "")
    except Exception as e:
        logger.critical("Problem saving product info to database: {}".format(e))

    return product_info
Exemple #38
0
def get_dominant_color(path, quality=1):
    """
    This method get the dominant color for an image.
    may throw exception.
    :param path: image path
    :param quality: resample quality 1 ~ 10 the higher the fast but not accurate,
    :return: a hex string like #ff0f0f
    """
    try:
        color_thief = ColorThief(path)
        (r, g, b) = color_thief.get_color(quality=quality)
        return '#{0:02x}{1:02x}{2:02x}'.format(r, g, b)
    except Exception as error:
        logger.error(error, exc_info=True)
        return '#000000'
Exemple #39
0
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;
    def grab_colors(self, images):
        seconds = 0
        rows = []

        for image in images:
            print(image['name'], end=' > ')

            try:
                request = self.service.files().get_media(
                    fileId=image['id'])

                fileBuffer = io.BytesIO()
                downloader = MediaIoBaseDownload(fileBuffer, request)
                done = False
                while done is False:
                    status, done = downloader.next_chunk()
                    downloaded = int(status.progress() * 100)

                    if downloaded < 100:
                        print('.', end='')
            except Exception:
                print('Can not download %s%' % image['name'])

            color_thief = ColorThief(fileBuffer)
            # get the dominant color
            dominant_color = color_thief.get_color(quality=1)
            hex_color = self._rgb_to_hex(dominant_color)

            rows.append({
                'fname': image['name'],
                'time_sec': seconds,
                'dominant_color': hex_color
            })

            print (hex_color)

            seconds = seconds + 5

        return rows
Exemple #41
0
    def readMainColorOfPicture(frame):
        frame = cv2.flip(frame,1)
        height, width, channels = frame.shape

        frame = frame[height/3:height*2/3,width/3:width*2/3]
        pil_im = Image.fromarray(frame)
        color_thief = ColorThief(pil_im)
        rgb=color_thief.get_color(quality=1)
        # print(rgb)
        # print(ColorReader.rgb_to_hsl(rgb))
        # print(color_thief.get_palette(quality=1))
        hsv = ImgColorReader.rgb_to_hue(rgb)
        # print(hsv[0]*360)
        hue = hsv[0] * 360
        print(hue)
        hueName = ImgColorReader.hue_to_name(hue)

        draw = ImageDraw.Draw(pil_im)
        box = (0,0,40,40)
        draw.rectangle(box,rgb)
        del draw
        # pil_im.show()
        return hueName
Exemple #42
0
def get_dominant_frame_color(method, file):
    """Extract the dominant color for a given file."""
    if method == "colortheif":
        from colorthief import ColorThief
        color_thief = ColorThief(file)
        return color_thief.get_color(quality=1)
    
    elif method == "colorcube":
        sys.path.append('ColorCube/Python')
        from ColorCube import ColorCube
        from PIL import Image
        cc = ColorCube(bright_threshold=0.0)
        img = Image.open(file)
        colors = cc.get_colors(img)
        return colors[0]
    
    elif method == "colorweave":
        from colorweave import palette
        p = palette(path=file, n=1)
        return hex_to_rgb(p[0])
        
    else:
        return average_image_color(file)
Exemple #43
0
#!/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))
Exemple #44
0
#!/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)

    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()




Exemple #46
0
    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)
Exemple #47
0
from colorthief import ColorThief
import sys
color_thief = ColorThief(sys.argv[1])
palette = color_thief.get_palette(color_count=6)
print palette
Exemple #48
0
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()
 def __init__(self, file):
     color_thief = ColorThief(file)
     self._color = color_thief.get_color(quality = 1)
def dominant(image):
    "Obtains the dominant color of a single image using `color-thief-py`"
    color_thief = ColorThief(image)
    return color_thief.get_color(quality=1)
# https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch06s02.html
import json
from colorthief import ColorThief

def jdefault(o):
    if isinstance(o, set):
        return list(o)
    return o.__dict__

colors = []

for x in range(1, 890):
    print "We're on time %d" % (x)

    file = 'full/' + str(x) + '.jpg'
    color_thief = ColorThief(file)
    dominant_color = color_thief.get_color(quality=1)
    print(dominant_color)

    colors.insert(x, dominant_color)
    # print(json.dumps(colors, default=jdefault))

print(json.dumps(colors, default=jdefault))
with open('colors.json', 'w') as f:
     json.dump(colors, f, default=jdefault)
Exemple #52
0
 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
Exemple #53
0
# -*- 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))