簡體   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