简体   繁体   English

计算图像中的像素颜色

[英]Count pixel color in an image

I have images with only 4 colors. The colors are described in a numpy array.我的图像只有 4 个 colors。colors 在 numpy 数组中描述。

self.colors = np.array([[255,255,255], [0,0,255], [255, 0, 0], [0,255,0]])

I want to count the occurence of the color in every image.我想计算每张图像中颜色的出现次数。 For example, in one image, i have 5550 pixels with color [255,255,255], 3521 with colors [0,0,255] and so on.例如,在一张图像中,我有 5550 个像素的颜色 [255,255,255],3521 个像素的颜色为 colors [0,0,255] 等等。

I've tried different thing by looking at stackoverflow or opencv forum, but nothing seems to work.我通过查看 stackoverflow 或 opencv 论坛尝试了不同的方法,但似乎没有任何效果。

I somehow managed to do something, but it's slow.我不知何故设法做了一些事情,但速度很慢。

def countColors(self, image): 
    start_time = time.time()

    colors_Count = {}
    for color in self.colors:
        colors_Count[str(color)] = 0   
    for y in range(0, image.shape[1]):
        for x in range(0, image.shape[0]):
            try:
                colors_Count[str(image[x][y])] = colors_Count[str(image[x][y])] + 1
            except:
                print('Error at pixel :', x, y)  
                return
    print(time.time() - start_time, "seconds")
    return colors_Count

It returns me a dict, which is perfect.它返回给我一个 dict,这是完美的。

{'[255 255 255]': 35741,
'[  0   0 255]': 5020,
'[255   0   0]': 3869,
'[  0 255   0]': 5616}

The problem is.. it takes like 3-4 seconds per image on a big CPU.问题是……在大型 CPU 上每张图像需要 3-4 秒。 It's such a waste of time.太浪费时间了。

What could I use to improve this?我可以用什么来改善这个?

With the help of crackanddie, I was able to improve my solution.在 crackanddie 的帮助下,我能够改进我的解决方案。

If anybody is looking to count pixel like me very fast, here is my new code:如果有人想像我一样快速计算像素,这是我的新代码:

    def countColors(self, image): 
    start_time = time.time()
    colors_Count = {}

    for i in range(len(self.colors)):
        tmp = cv.inRange(image, self.colors[i], self.colors[i])
        count = cv.countNonZero(tmp)
        colors_Count[str(self.colors[i])] = count
        
    print(time.time() - start_time, "seconds")
    return colors_Count

Thank you again crackanddie, I was so stuck ahah再次感谢你 crackanddie,我被困住了啊哈

PIL package has a function that counts all colors really fast. PIL package 有一个 function 可以非常快速地计算所有 colors。 if you care only to count specific colors, just filter the response.如果您只关心计算特定的 colors,只需过滤响应即可。 As for run time, on small images both function (PIL and yours) are almost the same but on big images (I checked 1000,1000,3) PIL is a bit faster.至于运行时间,在小图像上,function(PIL 和你的)几乎相同,但在大图像上(我检查了 1000,1000,3)PIL 快一点。 The big advantage of using PIL is that there's no need to specify colors.使用 PIL 的一大优势是无需指定 colors。

def count_colors_2(cv_img: np.array) -> list:  # no need to give colors
    from PIL import Image
    start_time = time.time()
    pil_image = Image.fromarray(cv_img)
    colors_count_list = pil_image.getcolors()
    print('count_colors_2 time elapsed: {:.10f}s'.format(time.time() - start_time))
    for count, c_bgr in colors_count_list:
        print('\tcolor {} appeared {} times'.format(c_bgr, count))
    return colors_count_list

time and output check (yours is count_colors_1 and PIL is 2)时间和 output 检查(你的是 count_colors_1 和 PIL 是 2)

image dims (1000, 1000, 3)
count_colors_1 time elapsed: 0.0039894581s
    color [0 0 0] appeared 500000 times
    color [255 255 255] appeared 250000 times
    color [  0   0 255] appeared 250000 times
count_colors_2 time elapsed: 0.0029892921s
    color (255, 255, 255) appeared 250000 times
    color (0, 0, 0) appeared 500000 times
    color (0, 0, 255) appeared 250000 times

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM