Advertisement
Guest User

Untitled

a guest
Jul 17th, 2014
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include "stb_image.h"  //Put stb_image.h from  https://github.com/nothings/stb/blob/master/stb_image.h along side this file in the same dir
  2.             //compile with g++ -Os getdot.cpp -o getdot.   Run with ./getdot <filename>
  3. #include <queue>
  4. #include <iostream>
  5. #include <string>
  6. #include <ctime>
  7. struct Image
  8. {
  9.     int width;
  10.     int height;
  11.     unsigned char* data;
  12.     Image(const std::string& filename)
  13.     {
  14.         int n;
  15.         data=stbi_load(filename.c_str(),&width,&height,&n,3);
  16.     }
  17.     ~Image()
  18.     {
  19.         stbi_free(data);
  20.     }
  21. };
  22.  
  23. struct Pixel
  24. {
  25.     int x,y,score;
  26.     Pixel(int tx,int ty,int tr,int tg,int tb):
  27.         x(tx),y(ty),score(tr-(tg+tb))
  28.     {}
  29.     bool operator<(const Pixel& o) const
  30.     {
  31.         return score >= o.score;//we want the heap top to be the lowest one on top, so invert
  32.     }
  33. };
  34.  
  35. Pixel getDot(const Image& i)
  36. {
  37.     std::priority_queue<Pixel> toppixels;
  38.     for(size_t y=0;y < i.height;y++)
  39.     {
  40.         for(size_t x=0;x < i.width;x++)
  41.         {
  42.             size_t index=y*width+x;
  43.             unsigned char *pixel_data=i.data+3*index;
  44.             toppixels.emplace(x,y,pixel_data[0],pixel_data[1],pixel_data[2]);
  45.             if(toppixels.size() >= 10)
  46.             {
  47.                 toppixels.pop();
  48.             }
  49.         }
  50.     }
  51.    
  52.     Pixel avg(0,0,0,0,0);
  53.     size_t n=toppixels.size();
  54.     while(!toppixels.empty())
  55.     {
  56.         Pixel c=toppixels.pop();
  57.         avg.x+=c.x;
  58.         avg.y+=c.y;
  59.         avg.score+=c.score;
  60.     }
  61.     avg.x/=n;
  62.     avg.y/=n;
  63.     avg.score/=n;
  64.    
  65.     return avg;
  66. }
  67.  
  68. int main(int argc,char** argv)
  69. {
  70.     Image image_to_load(argv[1]);//the filename is the first argument
  71.    
  72.     clock_t orig=clock();
  73.     Pixel center=getDot(image_to_load);
  74.     clock_t after=clock();
  75.    
  76.     clock_t deltams=(after-orig)*1000;
  77.    
  78.     std::cout << "The pixel center is at (" << avg.x << "," << avg.y << ")" << std::endl;
  79.     std::cout << "Finding it took approximately " << deltams/CLOCKS_PER_SEC << " ms" << std::endl;
  80.    
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement