tags:

views:

527

answers:

4

Hi,

After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current position.

imageurl='http://www.example.com/'
opener1 = urllib2.build_opener()
page1=opener1.open(imageurl)
my_picture=page1.read()
fout = open('images/tony'+image[s], "wb")
fout.write(my_picture)
fout.close()
+2  A: 

Use a PIL (Python Image Library) histogram. Loop over the histogram and take the average of pixel color weighed by the pixel count.

olooney
A: 

You could use the PIL library's Image module to do this. See: http://www.pythonware.com/library/pil/handbook/image.htm.

Kyle Lutz
+1  A: 

As mentionned by others, PIL is the right library. Here is a function that open an image and look for the main color.

def get_main_color(file):
    img = Image.open(file)
    colors = img.getcolors(256) #put a higher value if there are many colors in your image
    max_occurence, most_present = 0, 0
    try:
        for c in colors:
            if c[0] > max_occurence:
                (max_occurence, most_present) = c
        return most_present
    except TypeError:
        raise Exception("Too many colors in the image")

I hope it helps

luc
+1  A: 

You should use PIL's Parser from the ImageFile class to read the file in from the url. Then life is pretty easy because you said that the whole image is the same color. Here is some code that builds on your code:

import urllib2
import ImageFile

image_url = "http://plainview.files.wordpress.com/2009/06/black.jpg"
opener1 = urllib2.build_opener()
page1=opener1.open(image_url)

p = ImageFile.Parser()

while 1:
    s = page1.read(1024)
    if not s:
        break
    p.feed(s)

im = p.close()
r,g,b = im.getpixel((0,0))

fout = open('images/tony'+image[s]+"%d%_d%_d"%(r,g,b), "wb")
fout.write(my_picture)
fout.close()

This should append the red green and blue values of the color of the first pixel of the image to the end of the image name. I tested everything up until the fout lines.

Justin Peel
Thanks Justin for ur reply it really helped a lot.Actually i got the filename with red green and blue values of the color of the given pixel of the image.Is it possible to get actual color name of that image for the given pixel....or can we convert the obtained pixels to corresponding color name regardsArun
you would need to make a dictionary with RGB values as the keys and the names as the values. You could use the color list at this site, http://en.wikipedia.org/wiki/List_of_colors, maybe. You would use urllib2 to retrieve the names and the corresponding RGB values.
Justin Peel