Getting Dominant Color Of An Image
How can I get the dominant color of an image as rgb or hexcode? I found a script called Color Thief but it does not allow image URLs only paths.
Solution 1:
use urllib
to download the image first, then delete the unnecessary file:
from colorthief import ColorThief
import urllib
import os
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
Solution 2:
If you don't want to download unnecessary file, do it this way:
# -*- 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))
Post a Comment for "Getting Dominant Color Of An Image"