【问题标题】:python - how to get average pixel intensities along a line of an image and plot them on a graph?python - 如何获得沿图像线的平均像素强度并将它们绘制在图表上?
【发布时间】:2019-12-12 04:37:41
【问题描述】:

我有一张灰度图像。我想生成一个直方图,对应于沿 x 和 y 轴的每条线的平均像素强度。

for example this image should produce two histograms that look like bell curves

【问题讨论】:

    标签: python


    【解决方案1】:

    我会使用 PIL/pillow、numpy 和 matplotlib

    import numpy as np
    from PIL import Image
    import matplotlib.pyplot as plt
    
    # load Image as Grayscale
    i = Image.open("QWiTL.png").convert("L")
    # convert to numpy array
    n = np.array(i)
    
    # average columns and rows
    # left to right
    cols = n.mean(axis=0)
    # bottom to top
    rows = n.mean(axis=1)
    
    # plot histograms
    f, ax = plt.subplots(2, 1)
    ax[0].plot(cols)
    ax[1].plot(rows)
    f.show()
    

    【讨论】:

      【解决方案2】:

      假设你的图片是一个numpy数组,你可以从image.shape中获取宽度和高度

      pixel_sums_x = [sum(row) for row in image]
      pixel_avgs_x = [s / image_height for s in pixel_sums_x]
      
      pixel_sums_y = [sum(col) for col in zip(*image)]
      pixel_avgs_y = [s / image_width for s in pixel_sums_y]
      

      使用统计库:

      pixel_avgs_x = [statistics.mean(row) for row in image]
      pixel_avgs_y = [statistics.mean(col) for col in zip(*image)]
      

      然后您可以使用 matplotlib https://matplotlib.org/3.1.1/gallery/statistics/hist.html 绘制直方图

      【讨论】:

        【解决方案3】:

        我会参考之前问过的question,它讨论了如何找到整个图像的平均像素强度。您可以编辑此代码,而不是循环遍历每个像素,只需逐行循环,然后您将获得一个强度值数组。然后,使用以下代码绘制数据图表:

        import matplotlib.pyplot as plt
        
        #number of bins in the histogram. You can decide
        n_bins = 20
        
        fig, axs = plt.subplots(1, 1, tight_layout=True)
        axs[0].hist(x, bins=n_bins)
        #x is your array of values
        

        注意:需要下载matplotlib

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-30
          • 2022-01-10
          • 2020-02-19
          • 1970-01-01
          • 1970-01-01
          • 2012-09-06
          • 2011-02-10
          • 2022-10-16
          相关资源
          最近更新 更多