Ejemplo n.º 1
0
 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)
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
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
Ejemplo n.º 7
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
Ejemplo n.º 8
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
Ejemplo n.º 9
0
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))
Ejemplo n.º 10
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')
Ejemplo n.º 11
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
Ejemplo n.º 13
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("やっとできた、めっちゃ信じられない")
Ejemplo n.º 14
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
Ejemplo n.º 15
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
Ejemplo n.º 16
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
Ejemplo n.º 17
0
    async def upcoming(self, ctx, params=None):
        if params is None:
            params = "3"
        else:
            pass

        response = requests.get(Ctftime.upcoming_url,
                                headers=Ctftime.headers,
                                params=params)
        data = response.json()

        for num in range(0, int(params)):
            ctf_title = data[num]["title"]
            ctf_start = data[num]["start"].replace("T", " ").split(
                "+", 1)[0] + " UTC"
            ctf_end = data[num]["finish"].replace("T", " ").split(
                "+", 1)[0] + " UTC"

            ctf_start = re.sub(":00 ", " ", ctf_start)
            ctf_end = re.sub(":00 ", " ", ctf_end)

            dur_dict = data[num]["duration"]
            ctf_hours = str(dur_dict["hours"])
            ctf_days = str(dur_dict["days"])
            ctf_link = data[num]["url"]
            ctf_image = data[num]["logo"]
            ctf_format = data[num]["format"]
            ctf_place = data[num]["onsite"]

            if not ctf_place:
                ctf_place = "Online"
            else:
                ctf_place = "Onsite"

            image = urllib.request.urlopen(Ctftime.default_image)
            image = io.BytesIO(image.read())
            color_thief = ColorThief(image)
            rgb_color = color_thief.get_color(quality=49)
            hexed = str(Ctftime.rgb2hex(*rgb_color[:3])).replace("#", "")
            f_color = int(hexed, 16)
            embed = discord.Embed(title=ctf_title,
                                  description=ctf_link,
                                  color=f_color)

            if ctf_image != "":
                embed.set_thumbnail(url=ctf_image)
            else:
                embed.set_thumbnail(url=Ctftime.default_image)

            embed.add_field(
                name="Duration",
                value=((ctf_days + " days, ") + ctf_hours) + " hours",
                inline=True,
            )
            embed.add_field(name="Format",
                            value=ctf_place + " " + ctf_format,
                            inline=True)
            embed.add_field(name=ctf_start, value=ctf_end, inline=True)
            await ctx.channel.send(embed=embed)
Ejemplo n.º 18
0
def get_color(image):
    color_thief = ColorThief(image)
    requested_colour = color_thief.get_color(quality=1)
    actual_name, closest_name = get_colour_name(requested_colour)
    if actual_name == None:
        return closest_name
    else:
        return actual_name
Ejemplo n.º 19
0
def dominant_color(image_path):
    '''Function to get dominant color from uploaded photo'''
    c_t = ColorThief(image_path)
    dom_col = c_t.get_color(quality=8)
    red = dom_col[0]
    green = dom_col[1]
    blue = dom_col[2]
    return {"user_img_colors": {"red": red, "green": green, "blue": blue}}
Ejemplo n.º 20
0
def imagecolor(imgurl):
    urllib.request.urlretrieve(imgurl, imgloc)
    color_thief = ColorThief(imgloc)
    # get the dominant color
    dominant_color = color_thief.get_color(quality=1)
    os.remove(imgloc)
    hexcode = '#%02x%02x%02x' % dominant_color
    return hexcode
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'
Ejemplo n.º 22
0
def party_color(party, default_color="#000000"):
    if party in party_image_links:
        path = 'ep/img/' + party_image_links[party]
        color_thief = ColorThief(path)
        rgb_color = color_thief.get_color(quality=1)
        return '#%02x%02x%02x' % rgb_color
    else:
        return default_color
Ejemplo n.º 23
0
 def get_color(self, url):
     r = requests.get(url)
     r = BytesIO(r.content)
     r.seek(0)
     ct = ColorThief(r)
     rgb = ct.get_color(quality=1)
     # Convert to base 16 int.
     return int('%02x%02x%02x' % rgb, 16)
Ejemplo n.º 24
0
def image_to_rgb(source_image):
    urlretrieve(source_image, 'image.jpg')

    color_thief = ColorThief('image.jpg')

    # get the dominant color
    dominant_color = color_thief.get_color(quality=1)
    return dominant_color
Ejemplo n.º 25
0
 async def palette(self, ctx, num):
     images = []
     stops = []
     res = requests.get(ctx.message.attachments[0].url)
     image = Image.open(BytesIO(res.content)).convert('RGB')
     cthief = ColorThief(BytesIO(res.content))
     if int(num) == 1:
         rgb = cthief.get_color(quality=1)
         image = Image.new('RGB', (50, 50), rgb)
         images.append(image)
     elif int(num) == 2:
         for i in range(1, 3):
             rgb = cthief.get_color(quality=2)
             image = Image.new('RGB', (50, 50), rgb)
             images.append(image)
     else:
         palette = cthief.get_palette(color_count=int(num) + 1)
         for rgb in palette:
             image = Image.new('RGB', (50, 50), rgb)
             images.append(image)
     for i in range(100, 0, -1):
         if len(images) >= i ** 2 and len(images) % i == 0:
             height = i * 50
             width = int(len(images) / i) * 50
             for j in range(1, i):
                 stops.append(int(len(images) / i * j))
             break
     #print(str(width) + " , " + str(height))
     output = Image.new('RGB', (width, height))
     xOffset = 0
     yOffset = 0
     index = 0
     for image in images:
         for stop in stops:
             if index == stop:
                 yOffset += 50
                 xOffset = 0
         #print(str(xOffset) + " , " + str(yOffset))
         output.paste(image, (xOffset, yOffset))
         xOffset += image.size[0]
         index += 1
     with BytesIO() as imageBinary:
         output.save(imageBinary, 'PNG')
         imageBinary.seek(0)
         await ctx.send(file=discord.File(fp=imageBinary, filename='image.png'))
Ejemplo n.º 26
0
 def get_palette(self, image):
     """
     Compute list of colors extracted form the image.
     :param image: Path to the image to manipulate.
     :return: List of RGB tuples.
     """
     color_thief = ColorThief(image)
     dominant_color = color_thief.get_color(quality=1)
     return [dominant_color]
Ejemplo n.º 27
0
 def from_image(self, img, ncolors):
     """Constructs an EmotaPal from an image"""
     colorthief = ColorThief(img)
     if ncolors == 1:
         clr = colorthief.get_color(quality=1)
         return self.from_colors([clr])
     elif ncolors > 1:
         clrs = colorthief.get_palette(color_count=ncolors, quality=1)
         return self.from_colors(clrs)
Ejemplo n.º 28
0
def get_rgb(pic_path):
    """
    返回指定图片主要色的RGB值
    :param pic_path:
    :return:
    """
    color_thief = ColorThief(pic_path)
    dominant_rgb = color_thief.get_color(quality=1)
    print(dominant_rgb)
Ejemplo n.º 29
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;
Ejemplo n.º 30
0
def getColor(fileName):
    color_thief = ColorThief(fileName)
    dominant_color = color_thief.get_color(quality=1)
    colors = [0, 0, 0]
    i = 0
    for color in dominant_color:
        colors[i] = color
        i += 1
    return colors
Ejemplo n.º 31
0
def palette(url):
    color_thief = ColorThief(url)
    arr = color_thief.get_color(quality=1)
    input_colors = [[arr[0], arr[1], arr[2]], "N", "N", "N", "N"]
    data = {'input': input_colors, "model": "default"}
    data = json.dumps(data)
    response = requests.post('http://colormind.io/api/', data=data)
    print('palette has been found')
    return response.json()
Ejemplo n.º 32
0
def getColorsFromFile(filePath):
  fileInfo = ColorThief(filePath)
  dominantColor = fileInfo.get_color(quality=1)
  palette = fileInfo.get_palette(color_count=6)
  colorsFromFile = []
  colorsFromFile.append('#%02x%02x%02x' % dominantColor)
  for i in palette:
    colorsFromFile.append('#%02x%02x%02x' % i)
  return colorsFromFile
Ejemplo n.º 33
0
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
Ejemplo n.º 34
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
Ejemplo n.º 35
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
Ejemplo n.º 36
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
Ejemplo n.º 37
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'
Ejemplo n.º 38
0
    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
Ejemplo n.º 39
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)
Ejemplo n.º 40
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
Ejemplo n.º 41
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()
Ejemplo n.º 42
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))
Ejemplo n.º 43
0
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)
Ejemplo n.º 44
0
 def __init__(self, file):
     color_thief = ColorThief(file)
     self._color = color_thief.get_color(quality = 1)
Ejemplo n.º 45
0
    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()