void sequentialJulia()
{
	int i, j, maxk=0;
	float  y0;
	double  t1, t2, scale;
	scale = ((float)colors)/(log((float)MAX_ITER));
  pthread_t th[TH];
  params p[TH];
	t1 = get_time_sec();
	for (i = 0; i < num_rows; i++)
	{
		y0 = y_stop - ((float)i)*y_delta; 
    for(j=0;j<TH;j++){
      //start threads:
      p[j].id=j;
      p[j].scale=scale;
      p[j].y0=y0;
      p[j].row=i;
      pthread_create(&th[j],NULL,column_par,(void*)&p[j]);
    }
	} // loop over rows
  for(i=0;i<TH;i++){
    pthread_join(th[i],NULL);
  }
	t2 = get_time_sec();
    /* write out the resulting image */
    writePPM(image, num_rows, num_cols, colors /* s/b 255 */, "julia_seq.ppm");
	printf("Sequential code ran in %f seconds\n",t2-t1);
	printf("max k is %i\n",maxk);
} // end sequentialJulia
示例#2
0
int main(int argc, char** argv)
{
  const char *input_file  = argv[1];
  const char *output_file = argv[2];
  
  int num_generations = atoi(argv[3]);
  int population_size = atoi(argv[4]);  
  // population size, must be multiple of 4 right now
  assert(population_size % 4 == 0);
  
  // Load the desired image
  RGB *desired_image;  
  int width, height, max;
  desired_image = readPPM(input_file, &width, &height, &max);
  
  // Compute an image
  RGB *found_image = (RGB*)malloc(width*height*sizeof(RGB));
  compImage(desired_image, width, height, max, 
	    num_generations, population_size, found_image, output_file);
  
  // Write it back into an output file
  writePPM(output_file, width, height, max, found_image);
  
  free(found_image);
  free(desired_image);
  
  return(0);
}
示例#3
0
文件: HW1.cpp 项目: rjduran/MAT594G
//////////////////////////////////////////////////////////////////////
// Create an image and write it out to a file
//////////////////////////////////////////////////////////////////////
int main()
{
  int width = 400;
  int height = 400;
  VEC3F* image = new VEC3F[width * height]; // pixel values
  VEC3F* ray[width * height]; 				// array of VEC3F pointers
  int maxFrames = 1; 						// set to 30 to make 30 sequenced images
  
  for(int v = 0; v < maxFrames; v++) { 
	
    int i = 0; 
	for (int y = 0; y < height; y++) {
	  for (int x = 0; x < width; x++, i++) {
	    ray[i] = generateRay(x, y, -0.5f, 0.5f, -0.5f, 0.5f, width, height, v);  // generate Ray
		image[i] = rayColor(ray[i]); // get RGB pixel color of ray intersecting on surface
	  }
	}
	
	//save sequence of images for movie
	// std::stringstream stream;
	// stream << "image" << v << ".ppm";
	// std::string arraystring = stream.str();	
	// const char* filename = arraystring.c_str();
	
	//writePPM(image, width, height, filename);
	   } // v for loop
  writePPM(image, width, height, "image.ppm"); // comment this when saving movie
  delete[] image;

  return 0;
}
示例#4
0
void writeFrame(char* filename, bool pgm, bool frontBuffer)
{
    static GLubyte* frameData = NULL;
    static int currentSize = -1;

    int size = (pgm ? 1 : 4);

    if( frameData == NULL || currentSize != size*Win[0]*Win[1] )
    {
        if (frameData != NULL)
            delete [] frameData;

        currentSize = size*Win[0]*Win[1];

        frameData = new GLubyte[currentSize];
    }

    glReadBuffer(frontBuffer ? GL_FRONT : GL_BACK);

    if( pgm )
    {
        glReadPixels(0, 0, Win[0], Win[1],
                     GL_LUMINANCE, GL_UNSIGNED_BYTE, frameData);
        writePGM(filename, frameData, Win[0], Win[1]);
    }
    else
    {
        glReadPixels(0, 0, Win[0], Win[1],
                     GL_RGBA, GL_UNSIGNED_BYTE, frameData);
        writePPM(filename, frameData, Win[0], Win[1]);
    }
}
示例#5
0
void GLTools::writePPM(GLuint texId, char* name, int w, int h){
	float* buffer = new float[w*h];
	glBindTexture(GL_TEXTURE_2D, texId);
	glGetTexImage(GL_TEXTURE_2D, 0, GL_RED, GL_FLOAT, buffer);
	glBindTexture(GL_TEXTURE_2D, 0);
	writePPM(buffer, name, w, h);
	delete[] buffer;
}
示例#6
0
void GLTools::writePPM(float* bufferF, char* name, int w, int h){
	unsigned char* bufferC = new unsigned char[w*h];
	for(int j=0; j<w*h; j++){
		//float v = bufferF[j]*255.0;
		float v = bufferF[j]/4.0f*255.0f;
		bufferC[j] = (unsigned char)std::max(0.0f, std::min(255.0f, v));
	}
	writePPM(bufferC, name, w, h);
	delete[] bufferC;
}
示例#7
0
int main(int argc, char **argv) {
    if (argc < 6) {
	std::cerr <<  "Usage: raytracer <model_file> <output_file_name> <refract> <reflect> <aa>" << std::endl;
	exit(1);
    }
    std::ifstream input(argv[1]);
    parseModelFile(input, scene);
    std::string fname = argv[2];
    refract = (boost::starts_with(argv[3], "t")) ? true : false;
    reflect = (boost::starts_with(argv[4], "t")) ? true : false;
    aa = (boost::starts_with(argv[5], "t")) ? true : false;
    auto buf = getRaster();
    writePPM(std::move(buf), scene.cam.viewportHeight, scene.cam.viewportWidth, argv[2]);
    return 0;
}
示例#8
0
/* writes a PPM image to the given filename. Returns 0 on success. Optionally, you can look at the filename extension and write different file types. */
int image_write(Image *src, char *filename) {
    printf("Size: %d\n", src->imagesize);
    Pixel tempImage[ src->imagesize ]; // temp array to hold Pixels
    for (int row=0;row<src->rows;row++) {
        for (int col=0;col<src->cols;col++) {
            
            //printf("row: %d, col: %d\n", row, col);
            
            tempImage[row*src->cols + col].r = src->data[row][col].rgb[0] * 255;
            tempImage[row*src->cols + col].g = src->data[row][col].rgb[1] * 255;
            tempImage[row*src->cols + col].b = src->data[row][col].rgb[2] * 255;
            
        }
        
    }

    writePPM(tempImage, src->rows, src->cols, 255, filename);
    //free(tempImage);

    return(0);
}
示例#9
0
int main(int argc, char **argv)
{
    Image mandelbrot;
    int i;
    MPI_Status status;
    double t;

    /* Initialize MPI */
    MPI_Init (&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);

    mandelbrot = makeImage(WIDTH, HEIGHT);

    interval = mandelbrot->height / size;
    start = rank * interval;

    t = MPI_Wtime();
    mandelbrotSet (-0.65, 0, 2.5/HEIGHT, mandelbrot);
    printf("process %d: %f\n", rank, MPI_Wtime()-t);

    /* reconstruct image */
    if (rank == 0) {
        for (i=start+interval; i<mandelbrot->height; ++i) {
            MPI_Recv(mandelbrot->imdata[i], mandelbrot->width, MPI_INT,
                    MPI_ANY_SOURCE, i, MPI_COMM_WORLD, &status);
        }
        writePPM (mandelbrot, "mandelbrot.ppm");
    } else {
        for (i=start; i<start+interval; ++i) {
            MPI_Send(mandelbrot->imdata[i], mandelbrot->width, MPI_INT, 0, i,
                    MPI_COMM_WORLD);
        }
    }

    freeImage(mandelbrot);

    MPI_Finalize ();
    return 0;
}
int main(int argc, char *argv[]) {

    if( argc != 2 ) {
        printf("Too many or no one arguments supplied.\n");
    }

    double t_start, t_end;
    int i;
    char *filename = argv[1]; //Recebendo o arquivo!;

    PPMImage *image = readPPM(filename);
    PPMImage *image_output = readPPM(filename);

    t_start = rtclock();
    Smoothing_CPU_Serial(image_output, image);
    t_end = rtclock();
    // fprintf(stdout, "\n%0.6lfs\n", t_end - t_start);

    writePPM(image_output);

    free(image);
    free(image_output);
}
示例#11
0
inline void monitor(int         g,
                    const char *output_file,
                    int         width,
                    int         height,
                    int         max,
                    Individual *ind,
                    double      prev_fitness,
                    double     *old_time,
                    double     *new_time) {
  double current_fitness = ind->fitness;
  double change          =
    -(current_fitness - prev_fitness) / current_fitness * 100;

  if (g % MON_GEN == 0) {
    writePPM(output_file,
             width,
             height,
             max,
             ind->image);

#ifdef BONUS_VIDEO
    bonusVideo(g, output_file);
#endif /* ifdef BONUS_VIDEO */

    *old_time = *new_time;
    *new_time = omp_get_wtime();

    printf(
      " generation % 5d fitness %e  change from prev %.2e%c  time [%f] seconds \n",
      g,
      current_fitness,
      change,
      37,
      *new_time - *old_time);
   }
}
示例#12
0
int main()
{
  //Allocate the buffer.
  unsigned char * buffer = new unsigned char[frameWidth * frameHeight * 3];

  //Clear the buffer, manually
  memset(buffer, 255, frameWidth * frameHeight * 3);

  //Create the rendering buffer object
  agg::rendering_buffer rbuf(buffer, frameWidth, frameHeight, frameWidth * 3);
  
  //Create the Pixel format renderer
  agg::pixfmt_rgb24 pixf(rbuf);

  //Create one line (span) of type rgba8
  agg::rgba8 span[frameWidth];

  //Fill the buffer using blender color
  unsigned i;
  puts("Span...");
  for (i = 0; i < frameWidth; ++i)
  {
    agg::rgba c(380.0 + 400.0 * i / frameWidth, 0.8);
    span[i] = agg::rgba8(c);
  }

  for (i = 0; i < frameHeight; ++i)
  {
    pixf.blend_color_hspan(0, i, frameWidth, span, 0, 255);
  }
  puts("write...");
  writePPM(buffer, frameWidth, frameHeight, "agg_test.ppm");

  delete [] buffer;
  return 0;
}
示例#13
0
int main(int argc, char *argv[]) {
  Pixel *image1;
  Pixel *image2;
  Pixel *image3;
  int rows, cols, colors;
  long imagesize;
  // //int intensity, avg_r, avg_g, avg_b;


  if(argc < 5) {
    printf("Usage: %s <input file_1><input file_2><input mask><output file>\n", argv[0]);
    exit(-1);
  }

  /* read in the image */
  image1 = readPPM(&rows, &cols, &colors, argv[1]);
  if(!image1) {
    fprintf(stderr, "Unable to read file_1 %s\n", argv[1]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[1]);
  }

  image2 = readPPM(&rows, &cols, &colors, argv[2]);
  if(!image2) {
    fprintf(stderr, "Unable to read file_2 %s\n", argv[2]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[2]);
  }

  image3 = readPPM(&rows, &cols, &colors, argv[3]);
  if(!image3) {
    fprintf(stderr, "Unable to read mask %s\n", argv[3]);
    exit(-1);
  }else{
    printf("successfully opened image %s\n", argv[3]);
  }

  /* calculate the image size */
  imagesize = (long)rows * (long)cols;

  //image1 = makeMask(image1, imagesize); // use for creating the mask
  //image1 = setBackground(image1, image2, image3, imagesize); // setting the back ground ***use either this method or "translate" method. NOT BOTH
  image1 = translate(image1, image2, image3, imagesize, cols, rows,0,0); // sets the back ground as well as translates the front image.
  //image1 = toGreyscale(image1, imagesize); // turns an image to greyscale
  image1 = toNegative(image1, imagesize); // turns an image to negative
  //image1 = horizontalBlur(image1, imagesize); // turns the  image blury



//   /* write out the resulting image */
  writePPM(image1, rows, cols, colors /* s/b 255 */, argv[4]);

//   /* free the image memory */
#if USECPP
  delete[] image;
#else
  free(image1);
  free(image2);
  free(image3);
#endif

  return(0);
}
示例#14
0
int main(int argc, char *argv[]) {

    if (argc < 5 )
    {
        printf("\n Usage: ./denoise input.ppm output.ppm N F \n input.ppm is the name of the input file\n output.ppm is the name of the output file \n N specifies the size of the window\n F is the type of filtering");
        return 1;
    }
    const char *input = (argv[1]), *output = (argv[2]), *type = (argv[4]);

    int size = atoi(argv[3]);

    int *width, *height, *max;

    printf("Reading file %c", *input);
    clock_t start, end;
    double cpu_time_used;
    start = clock();

    RGB *readfile = readPPM(input, width, height, max);

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t %c read in %e seconds", *input, cpu_time_used);

    filter rtype;

    if ((*type) == 'A')
    {
      printf("Processing %d x %d image using %d x %d and mean filter...", *width, *height, size, size);
      rtype = MEAN;
    }
    else
    {
      printf("Processing %d x %d image using %d x %d and median filter...", *width, *height, size, size);

    }

    start = clock();

    RGB *writefile = denoiseImage (*width, *height, readfile, size, rtype);

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t image processed in %e seconds", cpu_time_used);


    printf("Writing file %c", *output);
    start = clock();

    writePPM(output, *width, *height, *max, writefile);
    printf("\n");

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("***\t %c read in %e seconds", *output, cpu_time_used);

    /*
    deallocateBST(bst_root);
    deallocateList(list_head);
    free(A);
     */
    return 0;
}
示例#15
0
void Image::writePPM()
{
        char str[1024];
        sprintf(str, "miro_%ld.ppm", time(0));
        writePPM(str);
}
示例#16
0
int main(int ac, const char **av) {
  // image size
  osp_vec2i imgSize;
  imgSize.x = 1024; // width
  imgSize.y = 768; // height

  // camera
  float cam_pos[] = {0.f, 0.f, 0.f};
  float cam_up [] = {0.f, 1.f, 0.f};
  float cam_view [] = {0.1f, 0.f, 1.f};

  // triangle mesh data
  float vertex[] = { -1.0f, -1.0f, 3.0f, 0.f,
                     -1.0f,  1.0f, 3.0f, 0.f,
                      1.0f, -1.0f, 3.0f, 0.f,
                      0.1f,  0.1f, 0.3f, 0.f };
  float color[] =  { 0.9f, 0.5f, 0.5f, 1.0f,
                     0.8f, 0.8f, 0.8f, 1.0f,
                     0.8f, 0.8f, 0.8f, 1.0f,
                     0.5f, 0.9f, 0.5f, 1.0f };
  int32_t index[] = { 0, 1, 2,
                      1, 2, 3 };


  // initialize OSPRay; OSPRay parses (and removes) its commandline parameters, e.g. "--osp:debug"
  ospInit(&ac, av);

  // create and setup camera
  OSPCamera camera = ospNewCamera("perspective");
  ospSetf(camera, "aspect", imgSize.x/(float)imgSize.y);
  ospSet3fv(camera, "pos", cam_pos);
  ospSet3fv(camera, "dir", cam_view);
  ospSet3fv(camera, "up",  cam_up);
  ospCommit(camera); // commit each object to indicate modifications are done


  // create and setup model and mesh
  OSPGeometry mesh = ospNewGeometry("triangles");
  OSPData data = ospNewData(4, OSP_FLOAT3A, vertex, 0); // OSP_FLOAT3 format is also supported for vertex positions (currently not on MIC)
  ospCommit(data);
  ospSetData(mesh, "vertex", data);

  data = ospNewData(4, OSP_FLOAT4, color, 0);
  ospCommit(data);
  ospSetData(mesh, "vertex.color", data);

  data = ospNewData(2, OSP_INT3, index, 0); // OSP_INT4 format is also supported for triangle indices
  ospCommit(data);
  ospSetData(mesh, "index", data);

  ospCommit(mesh);


  OSPModel world = ospNewModel();
  ospAddGeometry(world, mesh);
  ospCommit(world);


  // create and setup renderer
  OSPRenderer renderer = ospNewRenderer("scivis"); // choose Scientific Visualization renderer
  ospSet1f(renderer, "aoWeight", 1.0f);            // with full Ambient Occlusion
  ospSet1i(renderer, "aoSamples", 1);
  ospSetObject(renderer, "model",  world);
  ospSetObject(renderer, "camera", camera);
  ospCommit(renderer);


  // create and setup framebuffer
  OSPFrameBuffer framebuffer = ospNewFrameBuffer(&imgSize, OSP_FB_SRGBA, OSP_FB_COLOR | /*OSP_FB_DEPTH |*/ OSP_FB_ACCUM);
  ospFrameBufferClear(framebuffer, OSP_FB_COLOR | OSP_FB_ACCUM);

  // render one frame
  ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);

  // access framebuffer and write its content as PPM file
  const uint32_t * fb = (uint32_t*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);
  writePPM("firstFrameC.ppm", &imgSize, fb);
  ospUnmapFrameBuffer(fb, framebuffer);


  // render 10 more frames, which are accumulated to result in a better converged image
  for (int frames = 0; frames < 10; frames++)
    ospRenderFrame(framebuffer, renderer, OSP_FB_COLOR | OSP_FB_ACCUM);

  fb = (uint32_t*)ospMapFrameBuffer(framebuffer, OSP_FB_COLOR);
  writePPM("accumulatedFrameC.ppm", &imgSize, fb);
  ospUnmapFrameBuffer(fb, framebuffer);

  return 0;
}
示例#17
0
void Image::writePPM(char* pcFile)
{
    writePPM(pcFile, (unsigned char*)m_pixels, m_width, m_height);
}
示例#18
0
// Main function 
// *********************************************************************
int main(int argc, char **argv)
{
    // set and log Global and Local work size dimensions
    szLocalWorkSize = 16;
    szGlobalWorkSize = (iNumElements + szLocalWorkSize - 1) / szLocalWorkSize * szLocalWorkSize;  // rounded up to the nearest multiple of the LocalWorkSize

    // Allocate and initialize host arrays 
    std::vector<float> radius;
    std::vector<float4> position;
    std::vector<float4> emission;
    std::vector<float4> color;
    std::vector<cl_short> reflType;
    std::vector<float4> output;
    cl_int numSpheres = parallelize(spheres, radius, position, emission, color, reflType);

    output.resize(szGlobalWorkSize);

    // Create the OpenCL context on a GPU device
    cl_int err = 0;
    cxGPUContext = clCreateContextFromType(0, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
    CL_VERIFY(err);

    // Get the list of GPU devices associated with context
    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
    cdDevices = (cl_device_id*)malloc(szParmDataBytes);
    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);

    cqCommandQue = clCreateCommandQueue(cxGPUContext, cdDevices[0], 0, 0);

    // Allocate the OpenCL buffer memory objects for source and result on the device GMEM
    cl_mem radiusBuf = createBuffer(cxGPUContext, radius);
    cl_mem positionBuf = createBuffer(cxGPUContext, position);
    cl_mem emissionBuf = createBuffer(cxGPUContext, emission);
    cl_mem colorBuf = createBuffer(cxGPUContext, color);
    cl_mem reflTypeBuf = createBuffer(cxGPUContext, reflType);
    cl_mem outputBuf = clCreateBuffer(cxGPUContext, CL_MEM_WRITE_ONLY, sizeof(output[0]) * output.size(), NULL, 0);
    
    std::string source = readFile(cSourceFile);
    const char *cSource = source.c_str();

    // Create the program
    cpProgram = clCreateProgramWithSource(cxGPUContext, 1, &cSource, 0, 0);

    // Build the program
    err = clBuildProgram(cpProgram, 0, NULL, NULL, NULL, NULL);
    CL_VERIFY(err);

    // Create the kernel
    ckKernel = clCreateKernel(cpProgram, "radiance", &err);
    CL_VERIFY(err);

    // Set the Argument values
    CL_VERIFY(clSetKernelArg(ckKernel, 0, sizeof(cl_mem), (void*)&radiusBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 1, sizeof(cl_mem), (void*)&positionBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 2, sizeof(cl_mem), (void*)&emissionBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 3, sizeof(cl_mem), (void*)&colorBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 4, sizeof(cl_mem), (void*)&reflTypeBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 5, sizeof(cl_int), (void*)&numSpheres));
    CL_VERIFY(clSetKernelArg(ckKernel, 6, sizeof(cl_mem), (void*)&outputBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 7, sizeof(cl_int), (void*)&width));
    CL_VERIFY(clSetKernelArg(ckKernel, 8, sizeof(cl_int), (void*)&height));

    // --------------------------------------------------------
    // Start Core sequence... copy input data to GPU, compute, copy results back

    // Launch kernel
    CL_VERIFY(clEnqueueNDRangeKernel(cqCommandQue, ckKernel, 1, NULL, &szGlobalWorkSize, &szLocalWorkSize, 0, NULL, NULL));

    // Synchronous/blocking read of results, and check accumulated errors
    CL_VERIFY(clEnqueueReadBuffer(cqCommandQue, outputBuf, CL_TRUE, 0, sizeof(output[0]) * output.size(), &output.front(), 0, NULL, NULL));

    writePPM(output);
    writeRaw(output);

    // Cleanup and leave
    Cleanup (EXIT_SUCCESS);
}
示例#19
0
void fillWithBlack(line *CutLine, PPMImage *img, const char *filename)
{
    //Init all the needed structs, with two new images
    int i, j;
    PPMImage *newImgLEFT, *newImgRIGHT;
    char *left = "LEFT";
    char *right = "RIGHT";
    char delim[2] = "."; 
    char *name;
    char *ext;
    int new_fn_length = strlen(filename) + strlen(right) + 2;
    int limitL, limitR, rightBorder;
    char *filenameLEFT = calloc(new_fn_length, sizeof(char));
    char *filenameRIGHT = calloc(new_fn_length, sizeof(char));

    //Prepends the {LEFT,RIGHT} to the filename of the new images
    name = strtok((char *) filename, delim);
    ext = strtok(NULL,delim);

    snprintf(filenameLEFT, new_fn_length, "%s%s.%s",name,left,ext);
    snprintf(filenameRIGHT, new_fn_length, "%s%s.%s",name,right,ext);
    
    //Identify the limits of the two different pages
    if(tan(CutLine->alpha) >= 0)
    {
        limitL = (int) (CutLine->intercept + tan(CutLine->alpha)* img->y);
        limitR = (int) CutLine->intercept;
    }
    else
    {
        limitL = (int) (CutLine->intercept);
        limitR = (int) (img->x - (CutLine->intercept - img->y* tan(CutLine->alpha)));
    }
    rightBorder = img->x - limitR;
    
    //malloc of the new images
    newImgLEFT = (PPMImage*) malloc(sizeof(PPMImage));
    newImgLEFT->data = (PPMPixel*) malloc(limitL*img->y*sizeof(PPMPixel));
    newImgLEFT->y = img->y;    
    newImgLEFT->x = limitL;

    newImgRIGHT = (PPMImage*) malloc(sizeof(PPMImage));
    newImgRIGHT->data = (PPMPixel*) malloc(rightBorder*img->y*sizeof(PPMPixel));
    newImgRIGHT->y = img->y;    
    newImgRIGHT->x = rightBorder;

    //Divides the pixels in LEFT and RIGHT images
    for(j=0;j<img->y;j++)
    {
            for(i=0;i<img->x;i++)
            {

                    if(i < limitR)
                    {
                            newImgLEFT->data[j*limitL+i] = img->data[j*img->x+i];
                    }
                    else
                    {
                            if(i > limitL)
                            {
                                    newImgRIGHT->data[j*(img->x-limitR)+(i-limitR)] = img->data[j*img->x+i];
                            }
                            else
                            {
                                    if(i < (int) j*tan(CutLine->alpha)+CutLine->intercept)
                                    {
                                            newImgLEFT->data[j*limitL+i] = img->data[j*img->x+i];
                                            newImgRIGHT->data[j*(img->x-limitR)+(i-limitR)].red = (unsigned char)0;
                                            newImgRIGHT->data[j*(img->x-limitR)+(i-limitR)].green = (unsigned char)0;
                                            newImgRIGHT->data[j*(img->x-limitR)+(i-limitR)].blue = (unsigned char)0;
                                    }
                                    else
                                    {
                                            newImgRIGHT->data[j*(img->x-limitR)+(i-limitR)] = img->data[j*img->x+i];
                                            newImgLEFT->data[j*limitL+i].red = (unsigned char)0;
                                            newImgLEFT->data[j*limitL+i].green = (unsigned char)0;
                                            newImgLEFT->data[j*limitL+i].blue = (unsigned char)0;
                                    }
                            }
                    }
            }
    }

    //Writes the new images and frees the malloc'd structs
    writePPM(filenameLEFT,newImgLEFT);
    free(filenameLEFT);
    writePPM(filenameRIGHT,newImgRIGHT);
    free(filenameRIGHT);
    free(newImgLEFT->data);
    free(newImgRIGHT->data);
    free(newImgLEFT);
    free(newImgRIGHT);
}
void handle_output(char *output, img_t *in, img_t *out, img_t *original) {
#ifndef MPI
  /* For sequential code, the data to write is in out. */
  img_t *write = out;

  /* Write data to disk. */
  writePPM(output, write);

  /* Free memory for both images. */
  deletePPM(in);
  deletePPM(out);
#else
  /* Size and rank for MPI. */
  int size, rank;

  /* Local variables for image size and number of lines to compute. */
  int w, h, extrarows, index;

  /* Declare pointer to image to write. */
  img_t *write = NULL;

  /* Need to ask MPI who we are, and how many processes there are. */
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);  

  printf("RANK %i\n", rank);

  /* Allocate memory for output image. */
  if (rank == 0) {
    write = createPPM(original->w, original->h);
  }

  /* Get the local width and height. */
  w = out->w;
  h = out->h;

  /* All slaves send their result to the master */
  if (rank > 0) {
    MPI_Send(out->data, w * h * sizeof(pixel_t), MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD);
  } else {
    int part_h     = original->h / size;
    int extra_rows = original->h % size;

    if (rank < extra_rows) {
      part_h ++;
    }

    int offset = original->w * part_h;
    memcpy(write->data, out->data, offset * sizeof(pixel_t));

    /* Receive each part from the slaves */
    for (int i = 1; i < size; i++) {
      int part_h     = original->h / size;
      int extra_rows = original->h % size;

      if (rank < extra_rows) {
        part_h ++;
      }

      int buffer_length = part_h * original->w * sizeof(pixel_t);
      pixel_t *tmp = write->data + offset;

      MPI_Recv(tmp, buffer_length,
          MPI_UNSIGNED_CHAR, i, 0, MPI_COMM_WORLD, NULL);

      /* and copy the received bytes to the correct position */
      offset += buffer_length;
    }
  }

  /* Do the write-back once we have gathered all data. */
  if (rank == 0) {

    /* Write! */
    writePPM(output, write);

    /* ... and cleanup the memory */
    deletePPM(original);
    deletePPM(write);
  }

  /* Free memory for both images. */
  deletePPM(in);
  deletePPM(out);
#endif
}
示例#21
0
int main(int argc, char** argv) {
	
	PPMImage *image;
    int size;
	
	if(argc > 1) {
		image = readPPM("flower.ppm");
	} else {
		image = readStreamPPM(stdin);
	}
	AccurateImage *imageAccurate1_tiny = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_tiny = convertImageToNewFormat(image);
	
    // Process the tiny case:
    size = 2; 
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);
    performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, size);
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);
    performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, size);
    performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, size);

	
	AccurateImage *imageAccurate1_small = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_small = convertImageToNewFormat(image);
	
	// Process the small case:
    size = 3;
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);
    performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, size);
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);
    performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, size);
    performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, size);

	AccurateImage *imageAccurate1_medium = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_medium = convertImageToNewFormat(image);
	
	// Process the medium case:
    size = 5;
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);
    performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, size);
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);
    performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, size);
    performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, size);

	AccurateImage *imageAccurate1_large = convertImageToNewFormat(image);
	AccurateImage *imageAccurate2_large = convertImageToNewFormat(image);
	
    size = 8;
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);
    performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, size);
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);
    performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, size);
    performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, size);

	// Save the images.
	PPMImage *final_tiny = performNewIdeaFinalization(imageAccurate2_tiny,  imageAccurate2_small);
	PPMImage *final_small = performNewIdeaFinalization(imageAccurate2_small,  imageAccurate2_medium);
	PPMImage *final_medium = performNewIdeaFinalization(imageAccurate2_medium,  imageAccurate2_large);
	
	if(argc > 1) {
		writePPM("flower_tiny.ppm", final_tiny);
		writePPM("flower_small.ppm", final_small);
		writePPM("flower_medium.ppm", final_medium);
	} else {
		writeStreamPPM(stdout, final_tiny);
		writeStreamPPM(stdout, final_small);
		writeStreamPPM(stdout, final_medium);
	}
	return 0;
}
示例#22
0
int main(int argc, char **argv)
{
    Image mandelbrot;
    int i, running, data[WIDTH];
    MPI_Status status;
    double t;

    /* Initialize MPI */
    MPI_Init (&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);

    mandelbrot = makeImage(WIDTH, HEIGHT);

    /* reconstruct image */
    t = MPI_Wtime();
    if (rank == 0) {
    	running = size - 1;
        i = 0;
        while (running > 0) {
            MPI_Recv(data, mandelbrot->width, MPI_INT, MPI_ANY_SOURCE,
                    MPI_ANY_TAG, MPI_COMM_WORLD, &status);
            /* slave is returning calculated data, add it to the image */
            if (status.MPI_TAG < mandelbrot->height) {
                memcpy(mandelbrot->imdata[status.MPI_TAG], data,
                        sizeof(int) * mandelbrot->width);
            }

            /* we are done doing calculations, send termination signal */
            if (i >= mandelbrot->height) {
                MPI_Send(&i, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
                running--;
                printf("Slave %d shut down\n", status.MPI_SOURCE);
            /* send new data to calculate otherwise */
            } else {
                MPI_Send(&i, 1, MPI_INT, status.MPI_SOURCE, 1, MPI_COMM_WORLD);
                i++;
            }

        }

        writePPM (mandelbrot, "mandelbrot.ppm");
        writePPMCalculations(mandelbrot, "mandelbrotcalc");
    } else {
        /* register with the master */
        MPI_Send(mandelbrot->imdata[0], mandelbrot->width, MPI_INT, 0,
                mandelbrot->height, MPI_COMM_WORLD);
        while (1) {
            MPI_Recv(&i, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
            /* check if we received a kill signal */
            if (status.MPI_TAG == 0)
                break;
            mandelbrotSet (-0.65, 0, 2.5/HEIGHT, mandelbrot, i);
            MPI_Send(mandelbrot->imdata[i], mandelbrot->width, MPI_INT, 0, i,
                    MPI_COMM_WORLD);
        }
    }
    printf("process %d: %f\n", rank, MPI_Wtime()-t);

    freeImage(mandelbrot);

    MPI_Finalize ();
    return 0;
}
示例#23
0
int main(int argc, char** argv) {

	PPMImage *image;
        
	if(argc > 1) {
		image = readPPM("flower.ppm");
	} else {
		image = readStreamPPM(stdin);
	}

	AccurateImage *imageUnchanged = convertImageToNewFormat(image); // save the unchanged image from input image
	AccurateImage *imageBuffer = createEmptyImage(image);
	AccurateImage *imageSmall = createEmptyImage(image);
	AccurateImage *imageBig = createEmptyImage(image);
	
	PPMImage *imageOut;
	imageOut = (PPMImage *)malloc(sizeof(PPMImage));
	imageOut->data = (PPMPixel*)malloc(image->x * image->y * sizeof(PPMPixel));

	// Process the tiny case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	performNewIdeaIteration(imageBuffer, imageSmall, 2);
	performNewIdeaIteration(imageSmall, imageBuffer, 2);
	
	// Process the small case:
	performNewIdeaIteration(imageBig, imageUnchanged,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	performNewIdeaIteration(imageBuffer, imageBig,3);
	performNewIdeaIteration(imageBig, imageBuffer,3);
	
	// save tiny case result
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_tiny.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	
	// Process the medium case:
	performNewIdeaIteration(imageSmall, imageUnchanged, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	performNewIdeaIteration(imageBuffer, imageSmall, 5);
	performNewIdeaIteration(imageSmall, imageBuffer, 5);
	
	// save small case
	performNewIdeaFinalization(imageBig,  imageSmall,imageOut);
	if(argc > 1) {
		writePPM("flower_small.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}

	// process the large case
	performNewIdeaIteration(imageBig, imageUnchanged, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);
	performNewIdeaIteration(imageBuffer, imageBig, 8);
	performNewIdeaIteration(imageBig, imageBuffer, 8);

	// save the medium case
	performNewIdeaFinalization(imageSmall,  imageBig, imageOut);
	if(argc > 1) {
		writePPM("flower_medium.ppm", imageOut);
	} else {
		writeStreamPPM(stdout, imageOut);
	}
	
	// free all memory structures
	freeImage(imageUnchanged);
	freeImage(imageBuffer);
	freeImage(imageSmall);
	freeImage(imageBig);
	free(imageOut->data);
	free(imageOut);
	free(image->data);
	free(image);
	
	return 0;
}
示例#24
0
int main( int argc, char* argv[] )
{
    //===================================================================
    // Get the command-line options.
    //===================================================================
    Options opt;
    if( !options( argc, argv , opt ) )
    {
        return 1;
    }

    // Output the options.
    std::cerr << "Using demo sequence " << opt.sequenceNumber << "." << std::endl;
    std::cerr << "Output path is: \"" << opt.outputPath << "\"." << std::endl;
    std::cerr << "Number Of Images: " << opt.nImages << std::endl;
    std::cerr << "Start frame: " << opt.startFrame << std::endl;

    std::cerr << "Blur mode: " << ( opt.blurMode == Options::kGentle ? "Gentle" : "Aggressive") << std::endl;
    std::cerr << "Blur strength: " << opt.blurStrength << std::endl;
    std::cerr << "Contribution strength: " << opt.contributionStrength << std::endl;
    std::cerr << "Kernel width: " << opt.kernelWidth << std::endl;

    // Load the images.
    std::vector< Image > images( opt.nImages );
    int frame = opt.startFrame;
    for( unsigned int i = 0; i < images.size(); ++i )
    {
        std::stringstream s;
        s << "images/image" << opt.sequenceNumber << "." << frame << ".ppm";

        if( !readPPM( s.str(), images[i] ) )
        {
            std::cerr << "Failed to open image " << s.str() << std::endl;
            return 1;
        }

        if( ++frame >= 11 )
        {
            frame = 0;
        }
    }

    //===================================================================
    // The algorithm.
    //===================================================================

    SampleSet set( images );
    const int width = set.width(), height = set.height();
    Image result( width, height );


    int kernelRadius = opt.kernelWidth > 1 ? ( opt.kernelWidth - 1 ) / 2 : 0;
    std::vector< double > srcSamples;
    for( int y = 0; y < height; ++y )
    {
        for( int x = 0; x < width; ++x )
        {
            fprintf(stderr,"\rFiltering %5.2f%% complete.", 100. * y / ( height-1 ) );

            // Loop over each channel.
            for( unsigned int c = 0; c < 3; ++c )
            {
                double destMean = set.mean( x, y, c );
                double destDeviation = set.deviation( x, y, c );
                double destVariation = set.variance( x, y, c );
                double destRange = set.max( x, y, c ) - set.min( x, y, c );

                // Loop over the neighbouring pixels.
                double weightedSum = 0.;
                double v = 0.;
                for( int ky = -kernelRadius; ky <= kernelRadius; ++ky )
                {
                    for( int kx = -kernelRadius; kx <= kernelRadius; ++kx )
                    {
                        // Don't include the pixel being sampled in our calculations as we are
                        // summing the deviations from it and doing so will bias our results.
                        if( ky == 0 && kx == 0 )
                        {
                            continue;
                        }

                        // Gather information on the source pixel's samples.
                        srcSamples = set.samples( x + kx, y + ky, c );
                        double srcMin = set.min( x + kx, y + ky, c );
                        double srcMax = set.max( x + kx, y + ky, c );
                        double srcMean = set.mean( x + kx, y + ky, c );
                        double srcDeviation = set.deviation( x + kx, y + ky, c );
                        double srcVariation = set.variance( x + kx, y + ky, c );
                        double srcRange = set.max( x + kx, y + ky, c ) - set.min( x + kx, y + ky, c );

                        if( srcVariation == 0 && srcSamples[0] == 0. ) continue;

                        // A gaussian falloff that weights contributing samples which are closer to the pixel being filtered higher.
                        /// \todo Intuitive falloff parameters need to be added to the distance weight or at least a suitable curve found.
                        double distanceWeight = gaussian( sqrt( kx*kx + ky*ky ) / sqrt( kernelRadius*kernelRadius + kernelRadius*kernelRadius ), 0., .7, false );

                        // Similarity weight.
                        // This weight defines a measure of how similar the set of contributing samples is to the pixel being filtered.
                        // By itself it will produce a smart blur of sorts which is then attenuated by the variance of the source samples in the process of weighted offsets.
                        // Changing this value will effect how aggressive the filtering is.
                        double similarity;
                        if( opt.blurMode == Options::kAggressive )
                        {
                            similarity = ( srcMean - destMean ) * ( srcRange - destRange );
                        }
                        else
                        {
                            similarity = ( srcMean - destMean );
                        }
                        similarity *= similarity;

                        // Temporal weight.
                        // Weight the contribution using a function in the range of 0-1 which weights the importance of the
                        // contributing sample according to how close it is in time to the current time.
                        double time = 1.; // \todo: implement this! Example functions are Median, Gaussian, etc.

                        // Loop over each of the neighbouring samples.
                        for( unsigned int i = 0; i < srcSamples.size(); ++i )
                        {
                            // The contribution weight extends the range of allowed samples that can influence the pixel being filtered.
                            // It is simply a scaler that increases the width of the bell curve that the samples are weighted against.
                            double contribution = gaussian( srcSamples[i], destMean, destDeviation * ( 1 + opt.contributionStrength ) ) * gaussian( srcSamples[i], srcMean, srcDeviation );
                            contribution = contribution * ( 1. - opt.blurStrength ) + opt.blurStrength;

                            // This weight is a step function with a strong falloff close to the limits. However, it will never reach 0 so that the sample is not excluded.
                            // By using this weight the dependency on the limiting samples is much less which reduces the effect of sparkling artefacts.
                            double limitWeight = srcSamples.size() <= 2 ? 1. : softStep( srcSamples[i], srcMin, srcMax );

                            // Combine the weights together and normalize to the range of 0-1.
                            double weight = pow( M_E, -( similarity / ( contribution * srcVariation * time * distanceWeight * limitWeight ) ) );
                            weight = ( isnan( weight ) || isinf( weight ) ) ? 0. : weight;

                            // Sum the offset.
                            v += ( srcSamples[i] - destMean ) * weight;

                            // Sum the weight.
                            weightedSum += weight;
                        }
                    }
                }

                if( weightedSum == 0. || destVariation <= 0. )
                {
                    result.writeable( x, y )[c] = destMean;
                }
                else
                {
                    result.writeable( x, y )[c] = destMean + ( v / weightedSum );
                }
            }
        }
    }

    bool success = false;
    if( opt.extension == "bmp" )
    {
        success = writeBMP( opt.outputPath.c_str(), result );
    }
    else
    {
        success = writePPM( opt.outputPath.c_str(), result );
    }

    if( !success )
    {
        std::cerr << "Failed to write image." << std::endl;
        return 1;
    }

    return 0;
}
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels
	const int M = 21;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	
	/////////// Put your own unary classifier here! ///////////
  Eigen::MatrixXf unary = computeUnary( getLabeling( anno, W*H, M ), M );
	///////////////////////////////////////////////////////////
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Specify the unary potential as an array of size W*H*(#classes)
	// packing order: x0y0l0 x0y0l1 x0y0l2 .. x1y0l0 x1y0l1 ...
	crf.setUnaryEnergy( unary );
	// add a color independent term (feature = pixel location 0..W-1, 0..H-1)
	// x_stddev = 3
	// y_stddev = 3
	// weight = 3
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 3 ) );
	// add a color dependent term (feature = xyrgb)
	// x_stddev = 60
	// y_stddev = 60
	// r_stddev = g_stddev = b_stddev = 20
	// weight = 10
	crf.addPairwiseBilateral( 80, 80, 13, 13, 13, im, new PottsCompatibility( 10 ) );
	
	// Do map inference
// 	Eigen::MatrixXf Q = crf.startInference(), t1, t2;
// 	printf("kl = %f\n", crf.klDivergence(Q) );
// 	for( int it=0; it<5; it++ ) {
// 		crf.stepInference( Q, t1, t2 );
// 		printf("kl = %f\n", crf.klDivergence(Q) );
// 	}
// 	VectorXs map = crf.currentMap(Q);
	VectorXs map = crf.map(5);
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
示例#26
0
int main() {
    PPMImage *image;
    image = readPPM("flower.ppm");


    AccurateImage *imageAccurate1_tiny = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_tiny = convertImageToNewFormat(image);

    // Process the tiny case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 2; 
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
        performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, colour, size);
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
        performNewIdeaIteration(imageAccurate1_tiny, imageAccurate2_tiny, colour, size);
        performNewIdeaIteration(imageAccurate2_tiny, imageAccurate1_tiny, colour, size);
    }


    AccurateImage *imageAccurate1_small = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_small = convertImageToNewFormat(image);

    // Process the small case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 3;
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
        performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, colour, size);
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
        performNewIdeaIteration(imageAccurate1_small, imageAccurate2_small, colour, size);
        performNewIdeaIteration(imageAccurate2_small, imageAccurate1_small, colour, size);
    }

    AccurateImage *imageAccurate1_medium = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_medium = convertImageToNewFormat(image);

    // Process the medium case:
    for(int colour = 0; colour < 3; colour++) {
        int size = 5;
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
        performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, colour, size);
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
        performNewIdeaIteration(imageAccurate1_medium, imageAccurate2_medium, colour, size);
        performNewIdeaIteration(imageAccurate2_medium, imageAccurate1_medium, colour, size);
    }

    AccurateImage *imageAccurate1_large = convertImageToNewFormat(image);
    AccurateImage *imageAccurate2_large = convertImageToNewFormat(image);

    // Do each color channel
    for(int colour = 0; colour < 3; colour++) {
        int size = 8;
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
        performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, colour, size);
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
        performNewIdeaIteration(imageAccurate1_large, imageAccurate2_large, colour, size);
        performNewIdeaIteration(imageAccurate2_large, imageAccurate1_large, colour, size);
    }

    // Save the images.
    PPMImage *final_tiny = performNewIdeaFinalization(imageAccurate2_tiny,  imageAccurate2_small);
    writePPM("flower_tiny_correct.ppm",final_tiny);

    PPMImage *final_small = performNewIdeaFinalization(imageAccurate2_small,  imageAccurate2_medium);
    writePPM("flower_small_correct.ppm",final_small);

    PPMImage *final_medium = performNewIdeaFinalization(imageAccurate2_medium,  imageAccurate2_large);
    writePPM("flower_medium_correct.ppm",final_medium);

}
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels [use only 4 to make our lives a bit easier]
	const int M = 4;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	// Get the labeling
	VectorXs labeling = getLabeling( anno, W*H, M );
	const int N = W*H;
	
	// Get the logistic features (unary term)
	// Here we just use the color as a feature
  Eigen::MatrixXf logistic_feature( 4, N ), logistic_transform( M, 4 );
	logistic_feature.fill( 1.f );
	for( int i=0; i<N; i++ )
		for( int k=0; k<3; k++ )
			logistic_feature(k,i) = im[3*i+k] / 255.;
	
	for( int j=0; j<logistic_transform.cols(); j++ )
		for( int i=0; i<logistic_transform.rows(); i++ )
			logistic_transform(i,j) = 0.01*(1-2.*random()/RAND_MAX);
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Add a logistic unary term
	crf.setUnaryEnergy( logistic_transform, logistic_feature );
	
	// Add simple pairwise potts terms
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 1 ) );
	// Add a longer range label compatibility term
  crf.addPairwiseBilateral( 80.0f, 80.0f, 13.0f, 13.0f, 13.0f, &*im, new MatrixCompatibility::MatrixCompatibility( Eigen::MatrixXf::Identity(M,M) ) );
	
	// Choose your loss function
// 	LogLikelihood objective( labeling, 0.01 ); // Log likelihood loss
// 	Hamming objective( labeling, 0.0 ); // Global accuracy
// 	Hamming objective( labeling, 1.0 ); // Class average accuracy
// 	Hamming objective( labeling, 0.2 ); // Hamming loss close to intersection over union
	IntersectionOverUnion objective( labeling ); // Intersection over union accuracy
	
	int NIT = 5;
	const bool verbose = true;
	
  Eigen::MatrixXf learning_params( 3, 3 );
	// Optimize the CRF in 3 phases:
	//  * First unary only
	//  * Unary and pairwise
	//  * Full CRF
	learning_params<<1,0,0,
	                 1,1,0,
					 1,1,1;
	
	for( int i=0; i<learning_params.rows(); i++ ) {
		// Setup the energy
		CRFEnergy energy( crf, objective, NIT, learning_params(i,0), learning_params(i,1), learning_params(i,2) );
		energy.setL2Norm( 1e-3 );
		
		// Minimize the energy
		Eigen::VectorXf p = minimizeLBFGS( energy, 2, true );
		
		// Save the values
		int id = 0;
		if( learning_params(i,0) ) {
			crf.setUnaryParameters( p.segment( id, crf.unaryParameters().rows() ) );
			id += crf.unaryParameters().rows();
		}
		if( learning_params(i,1) ) {
			crf.setLabelCompatibilityParameters( p.segment( id, crf.labelCompatibilityParameters().rows() ) );
			id += crf.labelCompatibilityParameters().rows();
		}
		if( learning_params(i,2) )
			crf.setKernelParameters( p.segment( id, crf.kernelParameters().rows() ) );
	}
	// Return the parameters
	std::cout<<"Unary parameters: "<<crf.unaryParameters().transpose()<<std::endl;
	std::cout<<"Pairwise parameters: "<<crf.labelCompatibilityParameters().transpose()<<std::endl;
	std::cout<<"Kernel parameters: "<<crf.kernelParameters().transpose()<<std::endl;
	
	// Do map inference
	VectorXs map = crf.map(NIT);
	
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
示例#28
0
void Image::printImage(const char* fileName) const {
    std::ofstream myfile;
    myfile.open(fileName);
    writePPM(myfile);
    myfile.close();
}