fork(1) download
  1. #include <pgm.h>
  2. #include <math.h>
  3.  
  4. enum { N = 4, M = 4 };
  5.  
  6. typedef struct pgm_t {
  7. int cols, rows;
  8. gray maxval;
  9. gray **pgm;
  10. } pgm;
  11.  
  12. struct pgm_t load_pgm( const char *filename ) {
  13. FILE *fp = fopen( filename, "w" );
  14. struct pgm_t pgm;
  15. pgm.pgm = pgm_readpgm( fp, &pgm.cols, &pgm.rows, &pgm.maxval );
  16. fclose( fp );
  17. return pgm;
  18. }
  19.  
  20. void store_pgm( const char *filename, const struct pgm_t *pgm ) {
  21. FILE *fp = fopen( filename, "w" );
  22. pgm_writepgm( fp, pgm->pgm, pgm->cols, pgm->rows, pgm->maxval, 0 );
  23. fclose( fp );
  24. }
  25.  
  26. struct pgm_t mesh( const struct pgm_t *src, int w, int h ) {
  27. struct pgm_t result;
  28. int x, y;
  29. double d = (double)(src->cols * src->rows)/w/h;
  30.  
  31. result.maxval = src->maxval;
  32. result.cols = w;
  33. result.rows = h;
  34. result.pgm = pgm_allocarray( w, h );
  35. for( x = 0; x < src->cols; ++x ) {
  36. for( y = 0; y < src->rows; ++y ) {
  37. result.pgm[x/w][y/h] += src->pgm[x][y];
  38. }
  39. }
  40.  
  41. for( x = 0; x < w; ++x ) {
  42. for( y = 0; y < h; ++y ) {
  43. result.pgm[x][y] /= d;
  44. }
  45. }
  46.  
  47. return result;
  48. }
  49. double calc_similarness( const struct pgm_t *a, const struct pgm_t *b ) {
  50. double result = 0;
  51. int x, y;
  52. #if 0
  53. assert( a->cols == b->cols );
  54. assert( a->rows == b->rows );
  55. assert( a->maxval == b->maxval );
  56. #endif
  57. for( x = 0; x < a->cols; ++x ) {
  58. for( y = 0; y < a->rows; ++y ) {
  59. result += fabs( a->pgm[x][y] - b->pgm[x][y] );
  60. }
  61. }
  62. return result / a->cols / a->rows;
  63. }
  64.  
  65. int main( int argc, const char *argv[]) {
  66. if( strcmp( argv[0], "(1)" ) == 0 ) {
  67. struct pgm_t g = load_pgm( argv[1] );
  68. struct pgm_t g2 = mesh( &g, N, M );
  69. store_pgm( "result-1.pgm", &g2 );
  70. }
  71. else if( strcmp( argv[0], "(2)" ) == 0 ) {
  72. struct pgm_t in = load_pgm( argv[1] );
  73. struct pgm_t meshed = mesh( &in, N, M );
  74. double max_similarness = 0.0;
  75. int most_similar_number = -1;
  76. int i;
  77. for( i = 0; i < 10; ++i ) {
  78. char buf[32];
  79. sprintf( buf, "std%i.pgm", i );
  80. struct pgm_t std_N = load_pgm( buf );
  81. struct pgm_t meshed_N = mesh( &std_N, N, M );
  82. double similarness = calc_similarness( &in, &std_N );
  83. if( similarness > max_similarness ) {
  84. max_similarness = similarness;
  85. most_similar_number = i;
  86. }
  87. printf( "SIMILARITY TO #%i IS %f\n", i, similarness );
  88. }
  89. printf( "MOST SIMILAR NUMBER IS: %d", most_similar_number );
  90. }
  91. else if( strcmp( argv[0], "(3)" ) == 0 ) {
  92. }
  93. }
  94.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty