繁体   English   中英

在图像数组上使用 numpy.histogram

[英]Using numpy.histogram on an array of images

我正在尝试计算 numpy 图像数组的图像直方图。 图像数组的形状为(n_images、width、height、colour_channels),我想返回一个形状数组(n_images、count_in_each_bin(即 255))。 这是通过两个中间步骤完成的,即平均每个图像的每个颜色通道,然后将每个 2D 图像展平为 1D 图像。

我认为已经用下面的代码成功地做到了这一点,但是我在最后的 for 循环中作弊了。 我的问题是 - 有没有办法摆脱最后一个 for 循环并使用优化的 numpy function 代替?

def histogram_helper(flattened_image: np.array) -> np.array:
    counts, _ = np.histogram(flattened_image, bins=[n for n in range(0, 256)])
    return counts

# Using 10 RGB images of width and height 300
images = np.zeros((10, 300, 300, 3))

# Take the mean of the three colour channels
channel_avg = np.mean(images, axis=3)

# Flatten each image in the array of images, resulting in a 1D representation of each image.
flat_images = channel_avg.reshape(*channel_avg.shape[:-2], -1)

# Now calculate the counts in each of the colour bins for each image in the array.
# This will provide us with a count of how many times each colour appears in an image.
result = np.empty((0, len(self.histogram_bins) - 1), dtype=np.int32)
for image in flat_images:
    colour_counts = self.histogram_helper(image)
    colour_counts = colour_counts.reshape(1, -1)
    result = np.concatenate([result, colour_counts])

您不一定需要为此调用np.histogramnp.bincount ,因为像素值在0N的范围内。 这意味着您可以将它们视为索引并简单地使用计数器。

这是我将如何转换初始图像的方法,我成像的初始图像是np.uint8

images = np.random.randint(0, 255, size=(10, 5, 5, 3))  # 10 5x5 images, 3 channels
reshaped = np.round(images.reshape(images.shape[0], -1, images.shape[-1]).mean(-1)).astype(images.dtype)

现在您可以使用np.add.at的无缓冲加法简单地计算直方图:

output = np.zeros((images.shape[0], 256), int)
index = np.arange(len(images))[:, None]
np.add.at(output, (index, reshaped), 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM