代码之家  ›  专栏  ›  技术社区  ›  Blender

创建图像颜色亮度的一维直方图?

  •  3
  • Blender  · 技术社区  · 15 年前

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

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

    使用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)
    
    2 回复  |  直到 15 年前
        1
  •  11
  •   Paul    15 年前

    我看到你在用核弹。我会先把灰度图像转换成一个麻木数组,然后使用NUMPY沿着一个轴求和。额外的好处:你可能会发现你的平滑函数运行得更快,当你修复它,接受一个1D数组作为输入。

    >>> 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,)
    
        2
  •  8
  •   Jason Sundram Red Alert    9 年前

    the docs for PIL , histogram 提供图像中每个像素值的像素计数列表。如果您有一个灰度图像,那么将有256个不同的可能值,范围从0到255,并且从 image.histogram 将有256个条目。

    推荐文章