编辑评论:
- 如何计算图像中出现的像素数?
我有一组图像,其中每个像素由 3 个 0-255 范围内的整数组成。
我有兴趣找到一个对整个像素群作为一个整体“具有代表性”(尽可能多)的像素,并且该像素必须出现在像素群中。
我正在确定图像集中最常见的像素(中值模式)最有意义。
我正在使用python
,但我不知道如何去做。
图像存储为维度为 [n, h, w, c]
的 numpy 数组
,其中 n
是图像数量,h
是高度,w
是宽度,
c` 是 channel (RGB)。
最佳答案
我假设您需要找到最常见的元素,正如 Cris Luengo 提到的那样,称为模式。我还假设 channel 的位深度为 8 位(值在 0 到 255 之间,即模 256)。
这是一种独立于实现的方法:
目的是维护遇到的所有不同类型像素的计数。为此使用字典是有意义的,其形式为 {pixel_value : count}
.
一旦填充了这个字典,我们就可以找到计数最高的像素。
现在,“像素”不可散列,因此不能直接存储在字典中。我们需要一种方法来为每个唯一像素分配一个整数(我将其称为像素值),即,您应该能够转换像素值 <--> 像素的 RGB 值
此函数将 RGB 值转换为 0 到 16,777,215 范围内的整数:
def get_pixel_value(pixel):
return pixel.red + 256*pixel.green + 256*256*pixel.blue
并将 Pixel_value 转换回 RGB 值:
def get_rgb_values(pixel_value):
red = pixel_value%256
pixel_value //= 256
green = pixel_value%256
pixel_value //= 256
blue = pixel_value
return [red,green,blue]
该函数可以找到图像中最常见的像素:
def find_most_common_pixel(image):
histogram = {} #Dictionary keeps count of different kinds of pixels in image
for pixel in image:
pixel_val = get_pixel_value(pixel)
if pixel_val in histogram:
histogram[pixel_val] += 1 #Increment count
else:
histogram[pixel_val] = 1 #pixel_val encountered for the first time
mode_pixel_val = max(histogram, key = histogram.get) #Find pixel_val whose count is maximum
return get_rgb_values(mode_pixel_val) #Returna a list containing RGB Value of the median pixel
如果您希望找到一组图像中最常见的像素,只需添加另一个循环 for image in image_set
并填充所有图像中所有 Pixel_values 的字典。
关于python - 如何找到图像中最常见的像素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52591281/