I have images with only 4 colors. The colors are described in a numpy array.
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.
I've tried different thing by looking at stackoverflow or opencv forum, but nothing seems to work.
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.
{'[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. It's such a waste of time.
What could I use to improve this ?
inRangefor each of your color and then count them usingcountNonZerofunction. It could be faster