gpt4 book ai didi

python - PIL : Create one-dimensional histogram of image color lightness?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:47 24 4
gpt4 key购买 nike

我一直在编写脚本,基本上我需要它:

  • 将图像设为灰度(或双色,我将同时使用两者,看看哪个效果更好)。
  • 处理每一列并为每一列创建一个净强度值。
  • 将结果放入有序列表中。

使用 ImageMagick 有一种非常简单的方法来执行此操作(尽管您需要一些 Linux 实用程序来处理输出文本),但我并没有真正看到如何使用 Python 和 PIL 来执行此操作。

这是我目前所拥有的:

from PIL import Image

image_file = 'test.tiff'

image = Image.open(image_file).convert('L')

histo = image.histogram()
histo_string = ''

for i in histo:
histo_string += str(i) + "\n"

print(histo_string)

这输出了一些东西(我正在寻找结果图表),但它看起来与 ImageMagick 输出完全不同。我用它来检测扫描书籍的接缝和内容。

感谢所有提供帮助的人!


我现在有一个(看起来很讨厌的)解决方案:

from PIL import Image
import numpy

def smoothListGaussian(list,degree=5):
window=degree*2-1
weight=numpy.array([1.0]*window)
weightGauss=[]

for i in range(window):
i=i-degree+1
frac=i/float(window)
gauss=1/(numpy.exp((4*(frac))**2))
weightGauss.append(gauss)

weight=numpy.array(weightGauss)*weight
smoothed=[0.0]*(len(list)-window)

for i in range(len(smoothed)):
smoothed[i]=sum(numpy.array(list[i:i+window])*weight)/sum(weight)

return smoothed

image_file = 'verypurple.jpg'
out_file = 'out.tiff'

image = Image.open(image_file).convert('1')
image2 = image.load()
image.save(out_file)

intensities = []

for x in xrange(image.size[0]):
intensities.append([])

for y in xrange(image.size[1]):
intensities[x].append(image2[x, y] )

plot = []

for x in xrange(image.size[0]):
plot.append(0)

for y in xrange(image.size[1]):
plot[x] += intensities[x][y]

plot = smoothListGaussian(plot, 10)

plot_str = ''

for x in range(len(plot)):
plot_str += str(plot[x]) + "\n"

print(plot_str)

最佳答案

我看到您正在使用 numpy。我会先将灰度图像转换为 numpy 数组,然后使用 numpy 沿轴求和。奖励:当您将平滑函数修复为接受一维数组作为输入时,您可能会发现它运行得更快。

>>> from PIL import Image
>>> import numpy as np
>>> i = Image.open(r'C:\Pictures\pics\test.png')
>>> a = np.array(i.convert('L'))
>>> a.shape
(2000, 2000)
>>> b = a.sum(0) # or 1 depending on the axis you want to sum across
>>> b.shape
(2000,)

关于python - PIL : Create one-dimensional histogram of image color lightness?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com