python - 如何找到图像中最常见的像素值?

标签 python image image-processing computer-vision

编辑评论:


  • 如何计算图像中出现的像素数?

我有一组图像,其中每个像素由 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/

相关文章:

python - 根据累积量从轮廓填充区域

python - 从下面的代码中数据输出是水平的,是否可以垂直

python - 具有自动换行功能的 Python 文字处理函数

python - Seaborn 热图上的散点图

css - 链接背景图像

python - 如何在python中创建cmyk图像

python - 如何编写包含持久 C++ 对象的 TensorFlow 自定义操作?

java - 让标签图标出现在文本上方

algorithm - 快速检测图像中线条倾斜度的算法

opencv - 如何获得图像的面积并均衡所有图像