Esempio n. 1
0
/*提高H3_1*/
int H3_1()
{
    //实现BitPlane保存信息
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=ℑ
    char str[str_info_len];
    int bit=7;//第1比特用来当作水印信息,因为低频率人眼不敏感
    //使用bit=7时,打开图片可以看到图片最上面的图片颜色信息有明显的痕迹
    //lena
    strcpy(str,"Lena!This is the DIP course.");
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    BitPlane(pimg,str,bit);
    WritePPM("lena_bitplane.ppm",pimg);
    str[0]=0;//清空
    unBitPlane(pimg,str,bit);
    printf("加密信息是: %s \n",str);

    //Parrots
    strcpy(str,"Parrots!This is the DIP course.");
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    BitPlane(pimg,str,bit);
    WritePPM("Parrots_bitplane.ppm",pimg);
    str[0]=0;//清空
    unBitPlane(pimg,str,bit);
    printf("加密信息是: %s \n",str);
    return 0;
}
Esempio n. 2
0
//函数定义
int H5()
{
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=ℑ
    struct Template tml;//定义模版
    struct Template * ptml=&tml;
    int * arr=NULL;
    char ch[1024];
    char * pch=ch;
    //lena-------------------------
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    arr=(int *)malloc(sizeof(int)*3*3);//申请一个3*3的模版矩阵
    //锐化模版
    strcpy(ch,"Harpening 锐化模版导入成功");
    /*  0  -1  0
     * -1  5  -1
     *  0  -1  0
     * */
    //arr[0][0]=0;arr[0][1]=-1;arr[0][2]=0;
    //arr[1][0]=-1;arr[1][1]=5;arr[1][2]=-1;
    //arr[2][0]=0;arr[2][1]=-1;arr[2][2]=0;
    arr[0]=0; arr[1]=-1; arr[2]=0;
    arr[3]=-1; arr[4]=5; arr[5]=-1;
    arr[6]=0; arr[7]=-1; arr[8]=0;
    ptml->square=arr;
    ptml->name=pch;
    ptml->x=3;
    ptml->y=3;
    ptml->max=1;
    Convolution(pimg,ptml);
    strcpy(fname,"锐化后的lena.ppm");
    WritePPM(fname,pimg);
    WritePPM(fname,pimg);
    //边缘检测
    FreePPM(pimg);
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    strcpy(ch,"Edge Detection边缘检测Sobel算子");
    /* -1  0  1
     * -2  0  2
     * -1  0  1
     * */
    arr[0]=-1; arr[1]=0; arr[2]=1;
    arr[3]=-2; arr[4]=0; arr[5]=2;
    arr[6]=-1; arr[7]=0; arr[8]=1;
    ptml->square=arr;
    ptml->name=pch;
    ptml->x=3;ptml->y=3;
    ptml->max=4;
    Convolution(pimg,ptml);
    strcpy(fname,"边缘检测后的lena.ppm");
    WritePPM(fname,pimg);
    free(arr);
    //lena--------------------------
    return 0;
}
Esempio n. 3
0
static void SaveOutput(const WebPDecBuffer* const buffer,
                       OutputFileFormat format, const char* const out_file) {
  FILE* fout = NULL;
  int needs_open_file = 1;
  int ok = 1;
  Stopwatch stop_watch;

  if (verbose)
    StopwatchReadAndReset(&stop_watch);

#ifdef HAVE_WINCODEC_H
  needs_open_file = (format != PNG);
#endif
  if (needs_open_file) {
    fout = fopen(out_file, "wb");
    if (!fout) {
      fprintf(stderr, "Error opening output file %s\n", out_file);
      return;
    }
  }

  if (format == PNG) {
#ifdef HAVE_WINCODEC_H
    ok &= WritePNG(out_file, buffer);
#else
    ok &= WritePNG(fout, buffer);
#endif
  } else if (format == PAM) {
    ok &= WritePPM(fout, buffer, 1);
  } else if (format == PPM) {
    ok &= WritePPM(fout, buffer, 0);
  } else if (format == PGM || format == YUV) {
    ok &= WritePGMOrYUV(fout, buffer, format);
  } else if (format == ALPHA_PLANE_ONLY) {
    ok &= WriteAlphaPlane(fout, buffer);
  }
  if (fout) {
    fclose(fout);
  }
  if (ok) {
    printf("Saved file %s\n", out_file);
    if (verbose) {
      const double write_time = StopwatchReadAndReset(&stop_watch);
      printf("Time to write output: %.3fs\n", write_time);
    }
  } else {
    fprintf(stderr, "Error writing file %s !!\n", out_file);
  }
}
Esempio n. 4
0
int testAmmCaptcha()
{
    AmmCaptcha_initialize("font.ppm","ourDictionaryCaptcha.txt");

    struct Image * captcha = createImage(300,70,3);

    RenderString(captcha,&fontRAW, 0 ,  20, "AmmarServer FTW");
    WritePPM(captcha,"captcha.ppm");

    coolPHPWave(captcha, 11,12,5,14);
    WriteJPEGFile(captcha,"captcha.jpg");

   /*
    RenderString(captcha,&fontRAW, 0 ,  30, "abcdefghijklmnopqrstuvwxyz");
    RenderString(captcha,&fontRAW, 0 ,  50, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    RenderString(captcha,&fontRAW, 0 ,  70, "0123456789");

    RenderString(captcha,&fontRAW, 0 ,  90, "ABCDTest123");

    RenderString(captcha,&fontRAW, 0 ,  120, "012345Test123");*/



    //warpImage(captcha,  40, 120 ,  60 , 150);



    AmmCaptcha_destroy();

    return 0;
}
Esempio n. 5
0
/*H3_2*/
int H3_2()
{
    //实现二值化
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=ℑ
    //lena
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    BinaryZationPPM(pimg,2);
    WritePPM("lena_binaryzation.ppm",pimg);
    //Parrots
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    BinaryZationPPM(pimg,4);
    WritePPM("Parrots_binaryzation.ppm",pimg);
    return 0;
}
Esempio n. 6
0
/*作业二*/
int H2()
{
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=ℑ
    //lena
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    NegativePPM(pimg);
    strcpy(fname,"lena_m.ppm");
    WritePPM(fname,pimg);
    //parrots 
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    NegativePPM(pimg);
    strcpy(fname,"Parrots_m.ppm");
    WritePPM(fname,pimg);
    return 0;
}
Esempio n. 7
0
int H3_3()
{
    /*实现图片的复制,因为以前对图片的操作都是在原图片进行的操作。所以可以用这个函数进行图片的复制*/
    char fname[file_name_len];
    struct IMG image;
    struct IMG image2;
    struct IMG * pimg=ℑ
    struct IMG * pimg2=&image2;
    //lena
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    CopyPPM(pimg,pimg2);
    WritePPM("lena_copy.ppm",pimg2);
    //Parrots
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    CopyPPM(pimg,pimg2);
    WritePPM("Parrots_copy.ppm",pimg2);
    return 0;
}
Esempio n. 8
0
bool
CompareToGolden(const uint8_t *image, int xRes, int yRes, const char *fn,
                const char *nameBase) {
    FILE *f = fopen(fn, "rb");
    if (!f) {
        perror(fn);
        return false;
    }

    int xr, yr;
    if (fscanf(f, "P6\n%d %d 255\n", &xr, &yr) != 2) {
        fprintf(stderr, "Error reading golden image \"%s\"\n", fn);
        return false;
    }

    if (xr != xRes || yr != yRes) {
        fprintf(stderr, "Golden image resolution (%d,%d) doesn't match "
                "rendered image resolution (%d,%d)\n", xr, yr, xRes, yRes);
        return false;
    }

    uint8_t *golden = new uint8_t[3*xRes*yRes];
    if (fread(golden, sizeof(uint8_t), 3*xRes*yRes, f) != (size_t)3*xRes*yRes) {
        perror(fn);
        return false;
    }

    uint8_t *diffImg = new uint8_t[3*xRes*yRes];
    int smallDiffs = 0, bigDiffs = 0;
    for (int i = 0; i < 3 * xRes * yRes; ++i) {
        int diff = abs((int)golden[i] - (int)image[i]);
        diffImg[i] = (uint8_t)diff;
        if (diff > 4)
            ++bigDiffs;
        else if (diff > 0)
            ++smallDiffs;
    }

    if (bigDiffs != 0 || smallDiffs != 0) {
        char diffName[128];
        sprintf(diffName, "diff_%s", nameBase);
        WritePPM(diffImg, xRes, yRes, diffName);
        printf("  Wrote diff image \"%s\"\n", diffName);
    }

    bool legit = (bigDiffs < 2048 && smallDiffs < 32768);
    printf("  Image diffs: %d small, %d big. %s\n", smallDiffs, bigDiffs,
           legit ? "Passed." : "FAILED");
    return legit;
}
Esempio n. 9
0
//////////////////////////////////////////////////////////////////////
// write the kernel to a PPM file
//////////////////////////////////////////////////////////////////////
void APSF::writePPM(const char* filename)
{
  unsigned char* ppm = new unsigned char[3 * _res * _res];

  for (int x = 0; x < _res * _res; x++)
  {
    ppm[3 * x]     = 255 * _kernel[x];
    ppm[3 * x + 1] = 255 * _kernel[x];
    ppm[3 * x + 2] = 255 * _kernel[x];
  }
  WritePPM(filename, ppm, _res, _res);
  
  delete[] ppm;
}
Esempio n. 10
0
void _xvImage(int type,
              unsigned char * red,
              unsigned char * green,
              unsigned char * blue,
              int w, int h)
{
#define mindim 300
    float mag;

    char tmpname[100];
    char command[200];

    FILE *fp;

    tmpnam(tmpname);

    fp = fopen(tmpname,"wb");
    if(!fp) {
        fprintf(stderr,"Failed to open temp file %s\n",tmpname);
        return;
    }

    switch(type) {
      case 1:WritePGM(fp,w,h,red); break;
      case 2:WritePPM(fp,w,h,red,green,blue); break;
      case 3:WritePBM(fp,w,h,red); break;
      default:
        fputs("Unknown type in _xvImage",stderr);
    }


    fclose(fp);

    if(w < mindim && h < mindim) {
        mag = w > h ? w : h;
        mag = mindim/mag;
    } else
        mag = 1.0;

    sprintf(command,"xv -RM -raw -expand %g  %s &",mag, tmpname);
    system(command);

#undef mindim
}
Esempio n. 11
0
int R2Image::
Write(const char *filename) const
{
  // Parse input filename extension
  char *input_extension;
  if (!(input_extension = (char*)strrchr(filename, '.'))) {
    fprintf(stderr, "Input file has no extension (e.g., .jpg).\n");
    return 0;
  }
  
  // Write file of appropriate type
  if (!strncmp(input_extension, ".bmp", 4)) return WriteBMP(filename);
  else if (!strncmp(input_extension, ".ppm", 4)) return WritePPM(filename, 1);
  else if (!strncmp(input_extension, ".jpg", 5)) return WriteJPEG(filename);
  else if (!strncmp(input_extension, ".jpeg", 5)) return WriteJPEG(filename);

  // Should never get here
  fprintf(stderr, "Unrecognized image file extension");
  return 0;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
	/*
	if(argc != 2) {
	fprintf(stderr, "Usage: %s <output_img>\n"
	"       <output_img>: PPM file\n", argv[0]);
	exit(-1);
	}
	*/

	fb = (rgb*)malloc(WIDTH * HEIGHT * sizeof(rgb));
	if (fb == NULL) {
		perror("malloc");
		exit(-1);
	}

	render();
	//WritePPM(argv[1], fb);
	WritePPM("test.ppm", fb);
	free(fb);

	return 0;
}
Esempio n. 13
0
int H4()
{
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=&image;
    //lena
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    int * hist;
    hist=(int *)malloc(sizeof(int)*(pimg->maxv+1)*((pimg->channel-5)*2+1));
    HistPPM(hist,pimg);
    strcpy(fname,"lena_hist");
    WriteHist(hist,fname,pimg);
    //直方图完成
    //均衡化处理
    HistEqualization(pimg,hist);
    strcpy(fname,"lena_hist_equalization.ppm");
    WritePPM(fname,pimg);
    strcpy(fname,"lena_hist_equalization");
    WriteHist(hist,fname,pimg);

    free(hist);
    return 0;
}
Esempio n. 14
0
/***************************************************
** display function -- what to draw               **
***************************************************/
void display ( void )
{
  /* Initialize our framebuffer objects */
  if (!fb) initFramebuffers();

  /* determing what are fps have been up till now */
  fps = UpdateFPS();

  /* benchmarking may be desired, if so we need to know # of frames done */
  if (benchmarking) frameCount++;

  /* some setup */
  glEnable( GL_NORMALIZE );
  glEnable( GL_DEPTH_TEST );
  glClearDepth( 1.0 );
  glClearColor( 0, 0, 0, 0 );
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

  /* Draw the scene we want to the framebuffer 'fb' */
  AllowUnclampedColors();  // This process may involve values outside [0..1]
  if (drawRefractionOnly)
	DrawRefractedScene( viewpoint );
  else 
    DrawCausticsSceneWithLightSpaceGatheredPhotons( viewpoint );
  ResumeClampingColors();  // OK, we can allow OpenGL to start clamping to [0..1] again.

  /* we only want to draw to the size of the visible screen, even if 'fb' is bigger! */
  glViewport( 0, 0, screenSize, screenSize );
  
  /* either display our final result, or, depending on user input, some intermediate step */
  if (displayBig > 0)
		DrawBigScreenTexture(displayBig);
  else
  {
	  displayLargeTexture( fb->GetColorTextureID( 0 ), GL_LINEAR, GL_LINEAR );
	
	  /* draw miscellaneous data onscreen */
	  glDisable( GL_DEPTH_TEST );
      if (drawSideImages && displayBig < 1)
		DisplaySideImages();
	  if (drawHelpMenu)
		drawHelpScreen();
      if (shaderLoadError)
		drawErrorMessage();
      if (!screenShot && !makingMovie)
		displayTimer( fps );
      glEnable( GL_DEPTH_TEST );
  }

  /* grab a screenshot if necessary */
  if (screenShot)
  {
    /* note data is stored in memory with y-inverted to how stored in PPM, so invert when writing */
	glReadPixels( 0, 0, screenSize, screenSize, GL_RGB, GL_UNSIGNED_BYTE, screenCapture );
	WritePPM( screenCaptureFilename, PPM_RAW, screenSize, -screenSize, screenCapture );    
	screenShot = 0;
  }

  /* flush GL commands & swap buffers */
  glFlush();
  glutSwapBuffers();

  /* if we're using the built-in movie capture, we need to add a frame */
  if (makingMovie) makeMovie->AddCurrentFrame();
}
Esempio n. 15
0
/*作业三*/
int H3()
{
    char fname[file_name_len];
    struct IMG image;
    struct IMG * pimg=&image;

    // hint
    // lena
    int * hist=NULL;
    int * array=NULL;
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    hist=(int *)calloc(sizeof(int),(pimg->maxv+1)*((pimg->channel-5)*2+1));//hist[] color:3*pimg->maxv
    if(hist==NULL)
    {
	printf("分配内存失败!\n");
	exit(-1);
    }
    printf("calloc=%d\n",sizeof(int)*(pimg->maxv+1)*((pimg->channel-5)*2+1));
    HistPPM(hist,pimg);
    strcpy(fname,"lena");
    WriteHist(hist,fname,pimg);
    
    //Parrots
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    hist=(int *)calloc(sizeof(int),(pimg->maxv+1)*((pimg->channel-5)*2+1));//Hist[] color:3*pimg->maxv 
    if(hist==NULL)
    {
	printf("分配内存失败!\n");
	exit(-1);
    }
    HistPPM(hist,pimg);
    strcpy(fname,"Parrots");
    WriteHist(hist,fname,pimg);

    //计算分量图
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    strcpy(fname,"Parrots");
    ComponentPPM(fname,pimg);
    free(hist);

    //计算映射函数
    //lena
    strcpy(fname,"lena.ppm");
    ReadPPM(fname,pimg);
    array=(int *)calloc(sizeof(int),(pimg->maxv+1)*((pimg->channel-5)*2+1));//Hist[] color:3*pimg->maxv 
    Square_MapPPM(array,pimg->maxv);
    MapPPM(array,pimg);
    strcpy(fname,"lena_square.ppm");
    WritePPM(fname,pimg);
    Sqrt_MapPPM(array,pimg->maxv);
    MapPPM(array,pimg);
    strcpy(fname,"lena_sqrt.ppm");
    WritePPM(fname,pimg);
    //Parrots
    strcpy(fname,"Parrots.ppm");
    ReadPPM(fname,pimg);
    array=(int *)calloc(sizeof(int),(pimg->maxv+1)*((pimg->channel-5)*2+1));//Hist[] color:3*pimg->maxv 
    Square_MapPPM(array,pimg->maxv);
    MapPPM(array,pimg);
    strcpy(fname,"Parrots_square.ppm");
    WritePPM(fname,pimg);
    Sqrt_MapPPM(array,pimg->maxv);
    MapPPM(array,pimg);
    strcpy(fname,"Parrots_sqrt.ppm");
    WritePPM(fname,pimg);
    free(array);
    return 0;
}
Esempio n. 16
0
/* ********************************************************************* */
void WriteData (const Data *d, Output *output, Grid *grid)
/*!
 * Write data to disk using any of the available formats.
 *
 * \param [in] d      pointer to PLUTO Data structre 
 * \param [in] output the output structure corresponding to a given
 *                    format
 * \param [in] grid   pointer to an array of Grid structures
 *********************************************************************** */
{
  int    i, j, k, nv;
  int    single_file;
  size_t dsize;
  char   filename[512], sline[512];
  static int last_computed_var = -1;
  double units[MAX_OUTPUT_VARS]; 
  float ***Vpt3;
  void *Vpt;
  FILE *fout, *fbin;
  time_t tbeg, tend;
  long long offset;

/* -----------------------------------------------------------
            Increment the file number and initialize units
   ----------------------------------------------------------- */

  output->nfile++;

  print1 ("> Writing file #%d (%s) to disk...", output->nfile, output->ext);

  #ifdef PARALLEL
   MPI_Barrier (MPI_COMM_WORLD);
   if (prank == 0) time(&tbeg);
  #endif

  for (nv = 0; nv < MAX_OUTPUT_VARS; nv++) units[nv] = 1.0;
  if (output->cgs) GetCGSUnits(units);

/* --------------------------------------------------------
            Get user var if necessary 
   -------------------------------------------------------- */

  if (last_computed_var != g_stepNumber && d->Vuser != NULL) {
    ComputeUserVar (d, grid);
    last_computed_var = g_stepNumber;
  }

/* --------------------------------------------------------
            Select the output type 
   -------------------------------------------------------- */

  if (output->type == DBL_OUTPUT) {

  /* ------------------------------------------------------------------- */
  /*! - \b DBL output:
        Double-precision data files can be written using single or
        multiple file mode. 
        - for single file, serial: we open the file just once before
          the main variable loop, dump variables and then close.
        - for single file, parallel the distributed array descriptor sz is
          different for cell-centered or staggered data type and we
          thus have to open and close the file after each variable
          has been dumped.
        - when writing multiple files we open, write to and close the
          file one each loop cycle.
        \note In all cases, the pointer to the data array that has to be 
              written must be cast into (void *) and the starting index of 
              the array must be zero.
  */
  /* ------------------------------------------------------------------- */

    int sz;
    single_file = strcmp(output->mode,"single_file") == 0;
    dsize = sizeof(double);

    if (single_file){  /* -- single output file -- */

      sprintf (filename, "%s/data.%04d.%s", output->dir,output->nfile, 
                                            output->ext);
      offset = 0;
      #ifndef PARALLEL
       fbin = OpenBinaryFile (filename, 0, "w");
      #endif
      for (nv = 0; nv < output->nvar; nv++) {
        if (!output->dump_var[nv]) continue;

        if      (output->stag_var[nv] == -1) {  /* -- cell-centered data -- */
          sz = SZ;
          Vpt = (void *)output->V[nv][0][0];
        } else if (output->stag_var[nv] == 0) { /* -- x-staggered data -- */
          sz  = SZ_stagx;
          Vpt = (void *)(output->V[nv][0][0]-1);
        } else if (output->stag_var[nv] == 1) { /* -- y-staggered data -- */
          sz = SZ_stagy;
          Vpt = (void *)output->V[nv][0][-1];
        } else if (output->stag_var[nv] == 2) { /* -- z-staggered data -- */
           sz = SZ_stagz;
           Vpt = (void *)output->V[nv][-1][0];
        }
        #ifdef PARALLEL
         fbin = OpenBinaryFile (filename, sz, "w");
         AL_Set_offset(sz, offset);
        #endif
        WriteBinaryArray (Vpt, dsize, sz, fbin, output->stag_var[nv]);
        #ifdef PARALLEL
         offset = AL_Get_offset(sz);
         CloseBinaryFile(fbin, sz);
        #endif
      }
      #ifndef PARALLEL
       CloseBinaryFile(fbin, sz);
      #endif

    }else{              /* -- multiple files -- */

      for (nv = 0; nv < output->nvar; nv++) {
        if (!output->dump_var[nv]) continue;
        sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], 
                                            output->nfile, output->ext);

        if      (output->stag_var[nv] == -1) {  /* -- cell-centered data -- */
          sz = SZ;
          Vpt = (void *)output->V[nv][0][0];
        } else if (output->stag_var[nv] == 0) { /* -- x-staggered data -- */
          sz  = SZ_stagx;
          Vpt = (void *)(output->V[nv][0][0]-1);
        } else if (output->stag_var[nv] == 1) { /* -- y-staggered data -- */
          sz = SZ_stagy;
          Vpt = (void *)output->V[nv][0][-1];
        } else if (output->stag_var[nv] == 2) { /* -- z-staggered data -- */
           sz = SZ_stagz;
           Vpt = (void *)output->V[nv][-1][0];
        }
        fbin = OpenBinaryFile (filename, sz, "w");
        WriteBinaryArray (Vpt, dsize, sz, fbin, output->stag_var[nv]);
        CloseBinaryFile (fbin, sz);
      }
    }

  } else if (output->type == FLT_OUTPUT) {

  /* ----------------------------------------------------------
                 FLT output for cell-centered data
     ---------------------------------------------------------- */

    single_file = strcmp(output->mode,"single_file") == 0;

    if (single_file){  /* -- single output file -- */
      sprintf (filename, "%s/data.%04d.%s", output->dir, output->nfile, 
                                            output->ext);
      fbin = OpenBinaryFile (filename, SZ_float, "w");
      for (nv = 0; nv < output->nvar; nv++) {
        if (!output->dump_var[nv]) continue;
/*        Vpt = (void *)(Convert_dbl2flt(output->V[nv],0))[0][0];  */
        Vpt3 = Convert_dbl2flt(output->V[nv], units[nv],0);
        Vpt = (void *)Vpt3[0][0];
        WriteBinaryArray (Vpt, sizeof(float), SZ_float, fbin, 
                          output->stag_var[nv]);
      }
      CloseBinaryFile(fbin, SZ_float);
/*
BOV_Header(output, filename);
*/
    }else{              /* -- multiple files -- */

      for (nv = 0; nv < output->nvar; nv++) {
        if (!output->dump_var[nv]) continue;
        sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], 
                                            output->nfile, output->ext);

        fbin = OpenBinaryFile (filename, SZ_float, "w");
/*        Vpt = (void *)(Convert_dbl2flt(output->V[nv],0))[0][0];   */
        Vpt3 = Convert_dbl2flt(output->V[nv], units[nv],0);
        Vpt = (void *)Vpt3[0][0];
        WriteBinaryArray (Vpt, sizeof(float), SZ_float, fbin, 
                          output->stag_var[nv]);
        CloseBinaryFile (fbin, SZ_float);
      }
    }

  }else if (output->type == DBL_H5_OUTPUT || output->type == FLT_H5_OUTPUT){

  /* ------------------------------------------------------
       HDF5 (static grid) output (single/double precision)
     ------------------------------------------------------ */

    #ifdef USE_HDF5 
     single_file = YES;
     WriteHDF5 (output, grid);
    #else
     print1 ("! WriteData: HDF5 library not available\n");
     return;
    #endif

  }else if (output->type == VTK_OUTPUT) { 

  /* ------------------------------------------------------------------- */
  /*! - \b VTK output:  
      in order to enable parallel writing, files must be closed and
      opened again for scalars, since the distributed array descriptors 
      used by ArrayLib (Float_Vect) and (float) are different. This is
      done using the AL_Get_offset() and AL_Set_offset() functions.      */
  /* ------------------------------------------------------------------- */
    
    single_file = strcmp(output->mode,"single_file") == 0;
    sprintf (filename, "%s/data.%04d.%s", output->dir, output->nfile,
                                          output->ext);

    if (single_file){  /* -- single output file -- */

      fbin  = OpenBinaryFile(filename, SZ_Float_Vect, "w");
      WriteVTK_Header(fbin, grid);
      for (nv = 0; nv < output->nvar; nv++) {  /* -- write vectors -- */
        if (output->dump_var[nv] != VTK_VECTOR) continue;
        WriteVTK_Vector (fbin, output->V + nv, units[nv],
                         output->var_name[nv], grid);
      }

      #ifdef PARALLEL
       offset = AL_Get_offset(SZ_Float_Vect);
       CloseBinaryFile(fbin, SZ_Float_Vect);
       fbin  = OpenBinaryFile(filename, SZ_float, "w");
       AL_Set_offset(SZ_float, offset);
      #endif
      
      for (nv = 0; nv < output->nvar; nv++) { /* -- write scalars -- */
        if (output->dump_var[nv] != YES) continue;
        WriteVTK_Scalar (fbin, output->V[nv], units[nv],
                         output->var_name[nv], grid);
      }
      CloseBinaryFile(fbin, SZ_float);

    }else{          /* -- multiple output files -- */

      for (nv = 0; nv < output->nvar; nv++) { /* -- write vectors -- */
        if (output->dump_var[nv] != VTK_VECTOR) continue;
        if (strcmp(output->var_name[nv],"vx1") == 0) {
          sprintf (filename, "%s/vfield.%04d.%s", output->dir, output->nfile, 
                                                  output->ext);
        }else if (strcmp(output->var_name[nv],"bx1") == 0) {
          sprintf (filename, "%s/bfield.%04d.%s", output->dir, output->nfile, 
                                                  output->ext);
        }else{
          print1 ("! WriteData: unknown vector type in VTK output\n"); 
          QUIT_PLUTO(1);
        }

        fbin = OpenBinaryFile(filename, SZ_Float_Vect, "w");
        WriteVTK_Header(fbin, grid);
        WriteVTK_Vector(fbin, output->V + nv, units[nv],
                        output->var_name[nv], grid);
        CloseBinaryFile(fbin, SZ_Float_Vect);
      }

      for (nv = 0; nv < output->nvar; nv++) {  /* -- write scalars -- */
        if (output->dump_var[nv] != YES) continue;
        sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], 
                                            output->nfile,  output->ext);
        fbin = OpenBinaryFile(filename, SZ_Float_Vect, "w");
        WriteVTK_Header(fbin, grid);
        #ifdef PARALLEL
         offset = AL_Get_offset(SZ_Float_Vect);
         CloseBinaryFile(fbin, SZ_Float_Vect);
         fbin  = OpenBinaryFile(filename, SZ_float, "w");
         AL_Set_offset(SZ_float, offset);
        #endif
        WriteVTK_Scalar(fbin, output->V[nv], units[nv],
                        output->var_name[nv], grid);
        CloseBinaryFile (fbin, SZ_float);
      }
    }

  }else if (output->type == TAB_OUTPUT) { 

  /* ------------------------------------------------------
               Tabulated (ASCII) output
     ------------------------------------------------------ */

    single_file = YES;
    sprintf (filename,"%s/data.%04d.%s", output->dir, output->nfile,
                                         output->ext);
    WriteTabArray (output, filename, grid);

  }else if (output->type == PPM_OUTPUT) { 

  /* ------------------------------------------------------
                   PPM output
     ------------------------------------------------------ */

    single_file = NO;
    for (nv = 0; nv < output->nvar; nv++) {
      if (!output->dump_var[nv]) continue;
      sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], 
                                          output->nfile, output->ext);
      WritePPM (output->V[nv], output->var_name[nv], filename, grid);
    }

  }else if (output->type == PNG_OUTPUT) { 

  /* ------------------------------------------------------
                   PNG  output
     ------------------------------------------------------ */

    #ifdef USE_PNG
     single_file = NO;
     for (nv = 0; nv < output->nvar; nv++) {
       if (!output->dump_var[nv]) continue;
       sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], 
                                           output->nfile, output->ext);
       WritePNG (output->V[nv], output->var_name[nv], filename, grid);
     }
    #else
     print1 ("! PNG library not available\n");
     return;
    #endif

  }

/* -------------------------------------------------------------
           Update corresponding ".out" file
   ------------------------------------------------------------- */

  sprintf (filename,"%s/%s.out",output->dir, output->ext);

  if (prank == 0) {
    if (output->nfile == 0) {
      fout = fopen (filename, "w");
    }else {
      fout = fopen (filename, "r+");
      for (nv = 0; nv < output->nfile; nv++) fgets (sline, 512, fout);
      fseek (fout, ftell(fout), SEEK_SET);
    }

  /* -- write a multi-column file -- */

    fprintf (fout, "%d %12.6e %12.6e %ld ",
             output->nfile, g_time, g_dt, g_stepNumber);

    if (single_file) fprintf (fout,"single_file ");
    else             fprintf (fout,"multiple_files ");

    if (IsLittleEndian()) fprintf (fout, "little ");
    else                  fprintf (fout, "big ");

    for (nv = 0; nv < output->nvar; nv++) { 
      if (output->dump_var[nv]) fprintf (fout, "%s ", output->var_name[nv]);
    }

    fprintf (fout,"\n");
    fclose (fout);
  }

  #ifdef PARALLEL
   MPI_Barrier (MPI_COMM_WORLD);
   if (prank == 0){
     time(&tend);
     print1 (" [%5.2f sec]",difftime(tend,tbeg));
   }
  #endif
  print1 ("\n");

}
Esempio n. 17
0
void CImage::WritePPM (const char *dir, const char *filename) {
    string path = dir;
    path += SEP;
    path += filename;
    WritePPM (path.c_str());
}
Esempio n. 18
0
int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "usage: mbrast [grid_file.out]\n");
        return 1;
    }

    // Read grids from grid dump file
    std::vector<ShadedGrid> grids;
    if (!ReadGrids(argv[1], &grids))
        return 1;

    InitSamples();

    // Extract the name of the scene in case a full pathname was provided
    // on the command line
    char *sceneName = rindex(argv[1], '/');
    if (sceneName != NULL)
        ++sceneName;
    else
        sceneName = argv[1];

    // Remove trailing ".grids" from scene name
    char *end = rindex(sceneName, '.');
    assert(end);
    *end = '\0';

    printf("Rendering scene \"%s\"\n", sceneName);

    // Change this call to switch to creating an instance of your 3D
    // rasterizer once you start implementing it.

#if MBRAST_MODE == NAIVE_RAST_2D || MBRAST_MODE == SMART_RAST_2D
    Rasterizer *rast = Create2DRasterizer();
#elif MBRAST_MODE == BASIC_RAST_3D || MBRAST_MODE == INTER_RAST_3D
    Rasterizer *rast = Create3DRasterizer();
#elif MBRAST_MODE == BASIC_RAST_5D
    Rasterizer *rast = Create5DRasterizer();
#endif

    // Initialize task system for multithreading if the rasterizer
    // indicates that it's thread safe.
    bool useTasks = rast->IsThreadSafe();
    int nThreads = NumSystemCores();
    assert(nThreads < MAX_CORES);
    if (useTasks) {
        printf("Using %d threads!\n", nThreads);
        TasksInit();
    }

    // Render the scene multiple times, with each of the pixelSamples
    // sample counts.  The sample counts must all be powers of two.
    // The bucketSize array, which must be the same size as
    // pixelSamples[], gives the length of the side of the bucket we'll
    // decompose the image into for the corresponding sample count.
    int pixelSamples[] = { 1, 4, 32 };
    int bucketSize[] = { 64, 32, 8 };
    assert(sizeof(pixelSamples) == sizeof(bucketSize));
    int samplesSize = sizeof(pixelSamples) / sizeof(pixelSamples[0]);

    int failures = 0;
    for (int samplesIndex = 0; samplesIndex < samplesSize; ++samplesIndex) {
        assert(pixelSamples[samplesIndex] <= MAX_SAMPLES_PER_PIXEL);
        int nPixelSamples = pixelSamples[samplesIndex];
        int bucketExtent = bucketSize[samplesIndex];

        printf("Rendering with %d samples per pixel\n", nPixelSamples);

        // 720p resolution.  (This can't be easily changed, as it's baked
        // into the xy coordinates of the micropolygons.  So changing this
        // here would require a corresponding adjustment to those
        // coordinate values when the grids are read in....)
        int xRes = 1280, yRes = 720;

        // Allow the rasterizer to preprocess the grids
        ResetAndStartTimer();
        rast->PreprocessGrids(grids, bucketExtent, xRes, yRes);
        double preprocessCycles = GetElapsedMCycles() / 1024.;
        printf("  Spent %.3f billion cycles on grid preprocessing.\n",
               preprocessCycles);

        // Allocate final output image as well as one Bucket structure for
        // each rasterization task thread we're running; this way the
        // rasterizer can update the framebuffer in its Bucket directly
        // without needing to coordinate with any other rasterizer threads.
        uint8_t *image = new uint8_t[xRes * yRes * 3];
        Bucket *buckets[MAX_CORES];
        int nBuckets = useTasks ? nThreads : 1;
        for (int i = 0; i < nBuckets; ++i)
            buckets[i] = new Bucket(bucketExtent, nPixelSamples);

        // Render with intervals set from 1 to the number of pixel samples
        // in multiples of two.
        for (int logIntervals = 0; (1 << logIntervals) <= nPixelSamples;
             ++logIntervals) {
            int nIntervals = (1 << logIntervals);

            printf("  Rendering with %d intervals: ", nIntervals);
            fflush(stdout);

            if (useTasks) {
                // Create a RastTask instance for each of the buckets of
                // the image; do this outside of the timer so as not to
                // penalize for the unnecessary dynamic allocation overhead
                // in the implementation here.
                std::vector<Task *> rastTasks;
                for (int y = 0; y < yRes; y += bucketExtent) {
                    for (int x = 0; x < xRes; x += bucketExtent) {
                        int x1 = std::min(x + bucketExtent, xRes);
                        int y1 = std::min(y + bucketExtent, yRes);
                        RastTask *rt = new RastTask(rast, &buckets[0], x, y,
                                                    x1, y1, nIntervals, grids,
                                                    image, xRes, yRes);
                        rastTasks.push_back(rt);
                    }
                }

                ResetAndStartTimer();
                EnqueueTasks(rastTasks);
                WaitForAllTasks();
            }
            else {
                // If not using tasks, just loop over all of the buckets
                // and rasterize.
                ResetAndStartTimer();
                for (int y = 0; y < yRes; y += bucketExtent) {
                    for (int x = 0; x < xRes; x += bucketExtent) {
                        buckets[0]->Start(x, y, std::min(x + bucketExtent, xRes),
                                          std::min(y + bucketExtent, yRes));
                        rast->Rasterize(grids, nIntervals, buckets[0]);
                        buckets[0]->Resolve(image, xRes, yRes);
                    }
                }
            }

            // Report total time for rasterization
            double rastGCycles = GetElapsedMCycles() / 1024.;
            printf("  %.3f billion cycles\n", rastGCycles);

            // Write the image
            char outName[256];
            sprintf(outName, "%s_int%d_samp%d.ppm", sceneName, nIntervals,
                    nPixelSamples);
            WritePPM(image, xRes, yRes, outName);
            printf("  Wrote output image \"%s\"\n", outName);

            // Compare to the "golden" image for correctness
            char goldenName[256];
            sprintf(goldenName, "golden/%s_%d.ppm", sceneName,
                    nPixelSamples);
            if (!CompareToGolden(image, xRes, yRes, goldenName, outName))
                ++failures;
        }
        printf("\n");

        for (int i = 0; i < nBuckets; ++i)
            delete buckets[i];

        delete[] image;
    }

    if (useTasks)
        TasksCleanup();

    delete rast;
    return failures;
}
void DrawRegion( Region key, float scale ) {
	
	if ( key == NULL ) return;
	
	int stable = key->stable;
	
	char name[256];
	sprintf(name,"/tmp/T%03d.ppm",stable);
	Image out = ReadPPMFile(name);
	
	static int count = 0;
	
	if ( !ImageIsGood(out) ) {
		out = ConvertImage1(CopyImage(key->image));
		sprintf(name,"/tmp/R%05d.ppm",count++);
	} else sprintf(name,"/tmp/T%03d.ppm",stable);
	
	fprintf(stderr,".");
	
	int rv = RandomNumber(0,255);
	int gv = RandomNumber(0,rv);
	int bv = RandomNumber(0,gv);
	
	int color = PIX3(rv,gv,bv);
	
	DrawPolygon(key->border,out,color);
	
	Ellipse e1 = NewEllipse(key->row,key->col,key->maj*scale,key->min*scale,key->phi);
	DrawEllipse(e1,out,color); free(e1);
	Image patch = CreateImage(41*sqrt(2),41*sqrt(2));
	RegionToPatch(key,key->image,patch,scale);

	FVec hist = GenerateOrientationHistogram(patch);
	GaussianBlur1D(hist->values,hist->l,hist->r,2);
	DrawFVec(hist,10,10,200,400,PIX3(0,0,250),out);
	FVecFree(hist);
	
	if ( PolygonIsGood(key->sizes) ) {
		
		struct PointSt p1 = key->sizes->vertices[0];
		struct PointSt p2 = key->sizes->vertices[key->sizes->numberOfVertices-1];

		int i;
		hist = FVecNew(0,255);
		Point p;
		while ( ( p = NextPolygonVertex(key->sizes) ) != NULL ) FVecSetAt(hist,p->y,p->x);
		if ( p1.y < p2.y ) {
			for(i=p1.y;i<=p2.y;i++) if ( hist->values[i] == 0.0 ) FVecAddAt(hist,i,1);
		} else {
			for(i=p2.y;i>=p1.y;i--) if ( hist->values[i] == 0.0 ) FVecAddAt(hist,i,1);
		}
		
		hist->l = MIN(p1.y,p2.y);
		hist->r = MAX(p2.y-1,p1.y-1);
		
		DrawSizeFVec(hist,497,0,1021,1023,color,stable,out);
		DrawSizeFVec(hist,498,0,1022,1023,color,stable,out);
		DrawSizeFVec(hist,499,0,1023,1023,color,stable,out);
		
	}
	
	WritePPM(name,out);
	FreeImage(out);

}
Esempio n. 20
0
int WriteSwappedPPM(char * filename,struct Image * pic)
{
   swapDepthEndianness(pic);
   return WritePPM(filename,pic);
}
int main (int argc, char **argv) {
	
	srand(time(NULL));
	
	int i, j, k;
	float minSize = 10000, maxSize = 1.0, minPeriod = 0.1, minStable = 0.1;

	PStack im2Regions = NewPStack(100);

	Image im2 = ReadPGMFile(argv[1]);
	Image out = ConvertImage1(CopyImage(im2));
	fprintf(stderr,"Read in image %s with dimensions %d %d\n",argv[1],im2->rows,im2->cols);
	FindMSERegions(im2,im2Regions,minSize,maxSize,1,2,FALSE,TRUE);

	PStack dc = NewPStack(10);
	
	for(i=0;i<im2Regions->stacksize;i++) {
		Region re = im2Regions->items[i];
		float area = PolygonArea(re->border);
		float numberOfSections = area / 44000;
		if ( numberOfSections >= 1 && numberOfSections < 5 ) {
			PolygonACD(re->border,0.06,dc);
		}
	}
	
	Region cc = im2Regions->items[i];
	//DrawPolygon(cc->border,out,PIX3(0,255,0));
	for(i=0;i<dc->stacksize;i++) {
		Polygon border = dc->items[i];
		int area = PolygonArea(border);
		if ( area < 44000 || area > 44000 * 1.6 ) continue;
		PolygonVertexEvolution(border,4);
		int color = RandomColor(150);
		for(j=0;j<border->numberOfVertices;j++) {
			Ellipse e = NewEllipse(border->vertices[j].x,border->vertices[j].y,5,5,0);
			DrawEllipse(e,out,color); free(e);
		}
		DrawPolygon(border,out,color);
	}
	WritePPM("sections.ppm",out);
	
	
	//RegionsToSIFTDescriptors(im1Regions,im1Descriptors,4,8,41);
	//fprintf(stderr,"Created %d descriptors from %d regions in %2.2f seconds\n",im1Descriptors->stacksize,im1Regions->stacksize,CPUTIME-t0);
	//PrintSIFTDescriptors("csift1",im1Descriptors);
	
	
	
	/*
	PStack im2Regions = NewPStack(100);
	PStack im2Descriptors = NewPStack(100);
	
	t0 = CPUTIME;
	
	Image im2 = ReadPGMFile(argv[2]);
	FindMSERegions(im2,im2Regions,minSize,maxSize,minPeriod,minStable);
	RegionsToSIFTDescriptors(im2Regions,im2Descriptors,4,8,41);
	fprintf(stderr,"Created %d descriptors from %d regions in %2.2f seconds\n",im2Descriptors->stacksize,im2Regions->stacksize,CPUTIME-t0);
	
	PStack matches = NewPStack(100);
	double **transform = AllocDMatrix(3,3,0,0);
	FindMatches(im1Descriptors,im2Descriptors,matches,10);
	fprintf(stderr,"Found %d initial matches.\n",matches->stacksize);
	ScreenMatches(matches,transform);
	fprintf(stderr,"A1 = [ ");
	for(k=0;k<3;k++)fprintf(stderr,"%f %f %f;",transform[k][0],transform[k][1],transform[k][2]);
	fprintf(stderr,"]\n");
	
	Image im3 = CreateImage(im1->rows,im1->cols);
	
	AffineTransformImage(im2,im3,NULL,transform);
	
	for (i=0;i<im1->rows;i++) {
		for (j=0;j<im1->cols;j++) {
			int rv = MAX(0,im1->pixels[i][j]);
			int bv = MAX(0,im3->pixels[i][j]);
			im3->pixels[i][j] = PIX3(rv,0,bv);
	}}
	
	WritePPM("affine.ppm",im3);
	*/
	return 0;
	
}