Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting unique rgb

Tags:

python

I have found a working code for this, but don't understand everything about these lines:

counter = np.unique(img.reshape(-1, img.shape[2]), axis=0)
print(counter.shape[0])

Especially these values:

-1, img.shape[2], axis=0

What does that -1 do, why is the shape 2, and why is axis 0? And after that, why do we print shape[0]?

like image 205
kristof12301 Avatar asked Feb 05 '26 07:02

kristof12301


2 Answers

Try this:

a = np.array([
    [[1,2,3],[1,2,3],[1,2,3],[1,2,3]],
    [[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
])
a  # to print the contents
a.shape   # returns 2, 4, 3

Now, if you do reshape, it will change the shape, meaning it will re-arrange the items in the array.

# try:
a.reshape(2, 4, 3)
a.reshape(4, 2, 3)
# or even
a.reshape(12, 2, 1)
a.reshape(1, 1, 4, 2, 3)
a.reshape(1, 1, 4, 2, 1, 1, 3)
# or:
a.reshape(24, 1)
a.reshape(1, 24)

If you replace one of the numbers with -1, it will get calculated automatically. So:

a.reshape(-1, 3)
# is the same as 
a.reshape(8, 3)

and that'll give you the a "vector" of RGB values in a way. So now you have got the reshaped array and you just need to count unique values.

np.unique(a.reshape(8, 3), axis=0)

will return an array of unique values over axis 0 and you will just count them.

like image 129
Petr Blahos Avatar answered Feb 06 '26 21:02

Petr Blahos


If you don't understand a complex sentence, always break them up and print shapes.

print(img.shape)
img2 = img.reshape(-1, img.shape[2]) # reshape the original image into -1, 3; -1 is placeholder, so lets say you have a 
                                     # numpy array with shape (6,2), if you reshape it to (-1, 3), we know the second dim = 3
                                     # first dim = (6*2)/3 = 4, so -1 is replaced with 4
print(img2.shape)

counter = np.unique(img2, axis=0) # find unique elemenst
'''
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)[source]
Find the unique elements of an array.

Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

the indices of the input array that give the unique values
the indices of the unique array that reconstruct the input array
the number of times each unique value comes up in the input array
'''
print(counter)
print(counter.shape) # as, we have separate axis, so the channels are shown in dim 2
print(counter.shape[0])

But, this one is probably not correct as it doesn't consider unique RGB across channel.

So, the following is a better one, you flatten the array to get a list then using set find the unique elements and finally print the len of the set.

A handy shortcut is ->

print(len(set(img.flatten())))
like image 40
Zabir Al Nazi Avatar answered Feb 06 '26 20:02

Zabir Al Nazi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!