使用PIL和Python 2.7。
我有以下代码来判断图像是大部分是暗还是亮。
def blackWhite(image):
'''Return `True` if the image is mostly white, else `False`'''
l=image.convert('L').load()
w,h=image.size
lums=sum([[l[x,y] for x in range(w)] for y in range(h)],[])
return sum(lums)/float(len(lums))>127
我试图对其进行修改,使得指向图像中心的点比外面的点重得多。
到目前为止,我已经编写了这段代码:
def blackWhite(image):
'''Return `True` if the image is mostly white, else `False` Weigh center pixels more heavily.'''
def weight(x,y):
'''Return the weight of the point at (x,y) based on function y = -0.5|x-8|+4'''
return (-0.5*abs(x-8)+4)*(-0.5*abs(x-8)+4)
l=image.convert('L').load()
w,h=image.size
lums=sum([[l[x,y] for x in range(w)] for y in range(h)],[])
weights=sum([[weight(x,y) for x in range(w)] for y in range(h)],[])
weighted=[x*weights[n] for n,x in enumerate(lums)]
return (sum(weighted)/float(len(weighted)))/sum(weights)
这返回的值不是我所期望的,我期望值超出255.这段代码中的错误在哪里?
答案 0 :(得分:0)
抱歉,我的配方没有。最后一行不应该除以加权长度和权重之和,它应该只除以权重之和。
return sum(weighted)/sum(weights)