我需要检测在线图像的颜色,并将其保存在检测到的颜色的名称中。
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()发布于 2010-02-16 13:37:47
Use a PIL (Python Image Library) histogram.循环直方图并取像素计数加权的像素颜色的平均值。
发布于 2010-02-16 14:17:27
正如其他人所提到的,PIL是正确的库。这是一个打开图像并查找主颜色的函数。
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")我希望它能帮上忙
更新:对于非常小的图像,将256传递给getcolor是可以的,但在大多数情况下可能不起作用。对于较大的图像,必须增大此值。例如,对于400像素* 300像素的图像,1024*1024是可以的。
发布于 2010-02-16 14:17:58
你应该从ImageFile类中使用PIL的解析器来读取url中的文件,这样就很容易了,因为你说过整个图像都是相同的颜色。下面是基于你的代码构建的一些代码:
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()这应该将图像的第一个像素的颜色的红色、绿色和蓝色值附加到图像名称的末尾。我测试了所有的东西直到最后一条线。
https://stackoverflow.com/questions/2270874
复制相似问题