python-imaging-library - 查找图像 rgb 像素颜色计数的最快方法

标签 python-imaging-library opencv-python

我有一个用例,我必须在搜索后找到实时视频每一帧的连续 rgb 像素颜色计数,我发现了一段代码,它做同样的事情,但性能方面需要大约 3 秒才能给我输出,但在在我的情况下,我必须尽快进行此计算,可能是 1 秒内 25 帧。有人可以通过重构以下代码来帮助我弄清楚如何做到这一点

from PIL import Image
import timeit

starttime = timeit.default_timer()
with Image.open("netflix.png") as image:
    color_count = {}
    width, height = image.size
    print(width,height)
    rgb_image = image.convert('RGB')
    for x in range(width):
        for y in range(height):
            rgb = rgb_image.getpixel((x, y))
            if rgb in color_count:
                color_count[rgb] += 1
            else:
                color_count[rgb] = 1

    print('Pixel Count per Unique Color:')
    print('-' * 30)
    print(len(color_count.items()))
print("The time difference is :", timeit.default_timer() - starttime)

输出:

每个独特颜色的像素数:
130869

时差为:3.9660612

最佳答案

您需要使用 Numpy 或 OpenCV 来在 Python 中进行快速图像处理。我做了一个 9 色版的帕丁顿熊:

enter image description here

from PIL import Image
import numpy as np

# Open Paddington and make sure he is RGB - not palette
im = Image.open('paddington.png').convert('RGB')

# Make into Numpy array
na = np.array(im)

# Arrange all pixels into a tall column of 3 RGB values and find unique rows (colours)
colours, counts = np.unique(na.reshape(-1,3), axis=0, return_counts=1)

print(colours)
print(counts)

结果
[[ 14  48  84]
 [ 19  21  30]
 [ 33 108 163]
 [ 33 152 190]
 [ 72  58  58]
 [ 96 154 210]
 [180  89  64]
 [205 210 200]
 [208 151  99]]

[20389 40269 12820  1488 17185 25371 17050 16396  9032]

这意味着 RGB(14,48,84) 有 20,389 个像素,依此类推。

在我的 Mac 上,400x400 图像需要 125 毫秒,这将为您提供 8 fps,因此您最好至少拥有 4 个 CPU 内核并使用它们来获得 25+ fps。

更新

我认为你实际上可以比这快得多。如果您将每个像素的点积与 [1,256,65536] 相乘,您将得到每个像素的单个 24 位数字,而不是 3 个 8 位数字。然后找到唯一值要快得多。看起来像这样:
# Open Paddington and make sure he is RGB - not palette
im = Image.open('paddington.png').convert('RGB')

# Make into Numpy array
na = np.array(im)

# Make a single 24-bit number for each pixel
f = np.dot(na.astype(np.uint32),[1,256,65536]) 

nColours = len(np.unique(f))     # prints 9

在我的 Mac 上这需要 4 毫秒而不是 125 毫秒:-)

关键词 :Python、Numpy、PIL/Pillow、图像处理、计算独特颜色、计算颜色。

关于python-imaging-library - 查找图像 rgb 像素颜色计数的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669715/

相关文章:

python - 导入在 Python shell 中工作,但在从文件运行时不起作用

python - PIL简单渐变和TypeError : an integer is required

python - 像素坐标与绘图坐标

python - cv2.PutText vs cv2.AddText 两者有什么区别?

python - 计算 torch.utils.data.DataLoader 中数据对应的光流

python - 我如何删除这种类型的黑色图像的背景?

python - 通过这段代码,我想收集脸部样本,但它给了错误

python - 您可以将 "stream"图像发送到 ffmpeg 以构建视频,而不是将它们保存到磁盘吗?

python - Tensorflow Deeplab 图像颜色图去除混淆

numpy - 创建一个绿色 channel 比蓝色和红色 channel 更亮的蒙版?