Most people have suggested solutions that are likely to be fast (in fact, one that uses only 2 MB is probably acceptable in terms of memory usage and very fast, one that has a hash may be even faster, but it will definitely be use more than 2 MB of memory). Programming is always a trade-off between memory usage and processor time. Usually you can get results faster if you are willing to “spend” more memory, or you can get results slower by “spending” more time computing, however this usually protects you from large memory.
Here is one solution that no one has proposed so far. This is probably the one that costs less memory (you can optimize it, so it is unlikely to use more memory than it needs to save the image in memory, however the image will be resized, although you will have to copy it first). I doubt that it can beat the solution of the hash or bit masks in speed, it is just interesting if memory is your biggest problem.
Sort pixels in an image by color. You can easily convert each pixel to a 32-bit number, and 32-bit numbers can be compared with each other, with one number being less than the other, greater or equal. If you use Quicksort, no additional storage space is required for sorting, except for additional stack space. If you use Shellsort, no additional memory is required at all (although Shellsort will be much slower than Quicksort).
int num = (RED <16) + (GREEN <8) + BLUE;
As soon as you sort pixels like this one (which means you redid them inside the image), all pixels of the same color are always next to each other. This way, you can only iterate over the image and watch how often the color changes. For example. you save the current pixel color to (0, 0) and you start the counter with a value of 1. The next step is you go (0, 1). If this is the same color as before, there is nothing to do, continue with the next pixel (0, 2). However, if this is not the same, increase the counter by one and remember the color of this pixel for the next iteration.
As soon as you look at the last pixel (and possibly increase the counter again if it was not the same as the second last pixel), the counter contains the number of unique colors.
Iterating over all the pixels at least once is what you should do in any case, regardless of the solution, so it does not affect this solution more slowly or faster than other solutions. The speed of this algorithm depends on how quickly you can sort the pixels of the image by color.
As I said, this algorithm is easily beaten when the speed of your main concert (other solutions here are probably faster), but I doubt that it can be beaten when using memory is your main problem, as there is enough space besides the counter storage to store one color and a place to store the image itself, it will only need additional memory if your chosen sorting algorithm needs any.
Mecki
source share