c++ - Unique value numbers in an array or image -


i reading image disk. image can gray scale image or binary image. however, cannot tell header file of image. doing tell number of unique pixels. if unique pixel number more two, image gray-scale; otherwise black-and-white image. using following function job:

  bool is_binary_image(  std::vector<unsigned char> &memory) {     std::set<unsigned char> myset;     for(  std::vector<unsigned char>::iterator  = memory.begin();         it!= memory.end();          it++)     {         myset.insert(*it);         if (myset.size()>2)             return false;     }      return true;  } 

this function can if candidate image gray-scale image. however, if candidate image binary, function time-consuming. ideas on improving function?

you can speed using array instead of map:

bool is_binary_image(  std::vector<unsigned char> &memory) {     int counter = 0;     int pixels[256] = {};      for(  std::vector<unsigned char>::iterator  = memory.begin();         it!= memory.end();          it++)     {         pixels[*it]++;         if (pixels[*it]==1)           counter++;         if (counter>2)             return false;     }     return true; } 

edit

and here optimized version (but less readable), thx templaterex:

bool is_binary_image(  std::vector<unsigned char> &memory) {     int counter = 0;     int pixels[256] = {};      for(  std::vector<unsigned char>::iterator  = memory.begin();         it!= memory.end();          it++)     {         if ((counter += (++pixels[*it] == 1))>2)             return false;     }     return true; } 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -