【问题标题】:how to generate per-pixel histogram from many images in numpy?如何从numpy中的许多图像生成每像素直方图?
【发布时间】:2022-10-24 21:59:13
【问题描述】:

我有数以万计的图像。我想为每个像素生成一个直方图。我使用 NumPy 提出了以下代码来执行此操作:

import numpy as np
import matplotlib.pyplot as plt

nimages = 1000
im_shape = (64,64)
nbins = 100
#predefine the histogram bins
hist_bins = np.linspace(0,1,nbins)
#create an array to store histograms for each pixel
perpix_hist = np.zeros((64,64,nbins))

for ni in range(nimages):
    #create a simple image with normally distributed pixel values
    im = np.random.normal(loc=0.5,scale=0.05,size=im_shape)

    #sort each pixel into the predefined histogram
    bins_for_this_image = np.searchsorted(hist_bins, im.ravel())
    bins_for_this_image = bins_for_this_image.reshape(im_shape)

    #this next part adds one to each of those bins
    #but this is slow as it loops through each pixel
    #how to vectorize?
    for i in range(im_shape[0]):
        for j in range(im_shape[1]):
            perpix_hist[i,j,bins_for_this_image[i,j]] += 1

#plot histogram for a single pixel
plt.plot(hist_bins,perpix_hist[0,0])
plt.xlabel('pixel values')
plt.ylabel('counts')
plt.title('histogram for a single pixel')
plt.show()

我想知道是否有人可以帮助我矢量化 for 循环?我想不出如何正确索引到 perpix_hist 数组。我有成千上万张图像,每张图像约为 1500x1500 像素,这太慢了。

【问题讨论】:

    标签: python numpy histogram vectorization


    【解决方案1】:

    您可以使用np.meshgrid 对其进行矢量化,并为第一、第二和第三维(您已经拥有的最后一个维度)提供索引。

    y_grid, x_grid = np.meshgrid(np.arange(64), np.arange(64))
    
    for i in range(nimages):
        #create a simple image with normally distributed pixel values
        im = np.random.normal(loc=0.5,scale=0.05,size=im_shape)
    
        #sort each pixel into the predefined histogram
        bins_for_this_image = np.searchsorted(hist_bins, im.ravel())
        bins_for_this_image = bins_for_this_image.reshape(im_shape)
    
        perpix_hist[x_grid, y_grid, bins_for_this_image] += 1
    

    【讨论】:

    • 很好,谢谢!我的图像尺寸提高了 10 倍。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2015-01-24
    • 2023-03-12
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多