我有一个用例,我必须找到连续的rgb像素颜色计数的每帧视频后,搜索我发现了一段代码,它做同样的事情,但性能明智的,它需要左右~ 3秒给我给予输出,但在我的情况下,我必须尽可能快地做这个计算可能是25帧在1秒。有人可以帮助我弄清楚如何通过重构以下代码
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
2条答案
按热度按时间r7xajy2e1#
你需要使用Numpy或OpenCV在Python中进行快速图像处理。我做了一个9色版本的帕丁顿:
结果
这意味着RGB(14,48,84)有20,389个像素,依此类推。
这需要125毫秒在我的Mac上为400 × 400的图像,这将给你给予8 fps,所以你最好有至少4个CPU核心,并使用所有这些得到25+ fps。
更新
我认为你实际上可以比这快得多。如果你把每个像素的点积与[1,256,65536]相乘,你会得到每个像素的一个24位数字,而不是3个8位数字。然后找到唯一值的速度要快得多。看起来像这样:
这在我的Mac上需要4毫秒而不是125毫秒:-)
关键词:Python,Numpy,PIL/Pillow,图像处理,count unique colors,count colors。
zzlelutf2#
此函数返回一个漂亮的DataFrame,其中包含您需要的所有信息,并且速度快如 lightning -**比colors,counts = np.unique(...)**快10倍