如何找到最常出现的像素值?

时间:2018-10-01 12:35:32

标签: python image image-processing computer-vision

我有一组图像,其中每个像素由0-255范围内的3个整数组成。

我感兴趣的是找到一个对整个像素总体来说都是“代表性”(尽可能)的像素,并且该像素必须出现在像素群体中。 我正在确定在我的图像集中哪个像素是最常见的(中位数模式)。

我正在使用python,但不确定如何去做。 图像以尺寸为numpy array的{​​{1}}存储,其中[n, h, w, c]是图像数,n是高度,h是宽度{{ 1}} c`是通道(RGB)。

1 个答案:

答案 0 :(得分:2)

我将假设您需要找到最常见的元素,正如克里斯·伦戈(Cris Luengo)所提到的那样,它被称为模式。我还要假设通道的位深度是8位(0到255之间的值,即256模)。

这是一种与实现无关的方法:

目的是要对遇到的所有不同种类的像素进行计数。为此,使用字典是有意义的,其形式为{pixel_value : count}

填充该词典后,我们可以找到计数最高的像素。

现在,“像素”不可散列,因此无法直接存储在字典中。我们需要一种为每个唯一像素分配一个整数(我将其称为pixel_value)的方法,即您应该能够转换pixel_value <->像素的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_value填充字典。

相关问题