Пример #1
0
void dump_frame(BIFSVID b2v, char *conv_buf, char *out_path, u32 dump_type, avi_t *avi_out, u32 frameNum)
{
	u32 k;
	M4VideoSurface fb;

	/*lock it*/
	SR_GetScreenBuffer(b2v.sr, &fb);
	/*export frame*/
	switch (dump_type) {
	case 0:
		/*reverse frame*/
		for (k=0; k<fb.height; k++) {
			memcpy(conv_buf + k*fb.width*3, fb.video_buffer + (fb.height-k-1) * fb.pitch, sizeof(char) * fb.width  * 3);
		}
		if (AVI_write_frame(avi_out, conv_buf, fb.height*fb.width*3, 1) <0)
			printf("Error writing frame\n");
		break;
	case 2:
		write_raw(&fb, out_path, frameNum);
		break;
	case 1:
		write_bmp(&fb, out_path, frameNum);
		break;
	}
	/*unlock it*/
	SR_ReleaseScreenBuffer(b2v.sr, &fb);
}
Пример #2
0
void save_screen_shot(int automap_flag)
{
	static int savenum=0;
	char savename[13+sizeof(SCRNS_DIR)];
	unsigned char *buf;

	if (!GameArg.DbgGlReadPixelsOk){
		if (!automap_flag)
			HUD_init_message_literal(HM_DEFAULT, "glReadPixels not supported on your configuration");
		return;
	}

	stop_time();

	if (!PHYSFSX_exists(SCRNS_DIR,0))
		PHYSFS_mkdir(SCRNS_DIR); //try making directory

	do
	{
		sprintf(savename, "%sscrn%04d.tga",SCRNS_DIR, savenum++);
	} while (PHYSFSX_exists(savename,0));

	if (!automap_flag)
		HUD_init_message(HM_DEFAULT, "%s 'scrn%04d.tga'", TXT_DUMPING_SCREEN, savenum-1 );

#ifndef OGLES
	glReadBuffer(GL_FRONT);
#endif

	buf = d_malloc(grd_curscreen->sc_w*grd_curscreen->sc_h*3);
	write_bmp(savename,grd_curscreen->sc_w,grd_curscreen->sc_h,buf);
	d_free(buf);

	start_time();
}
Пример #3
0
void BackProjection::create_prob()
{
    int i, j;

    input = (unsigned char *)malloc(r * c * sizeof(unsigned char));

    for (i = 0; i < r; i++)
    {
        for (j = 0; j < c; j++)
        {
            input[ i * c + j ] = FALSE;
        }
    }
    create_image(r, c, input, r < c ? r : c, r < c ? (F_TYPE) r / (F_TYPE) 4.0: (F_TYPE) c / (F_TYPE) 4.0);

    std::string inName = "BackProjection_ref_in.dat";
    std::string bmpName = "BackProjection_ref_in.bmp";
    printimage(r, c, input, inName.c_str());
    write_bmp(bmpName.c_str(), input, r, c);

    rproj = (int *)malloc(r * sizeof(int));
    cproj = (int *)malloc(c * sizeof(int));
    uproj = (int *)malloc((r + c - 1) * sizeof(int));
    dproj = (int *)malloc((r + c - 1) * sizeof(int));

    rband = (int *)malloc(r * c * sizeof(int));
    cband = (int *)malloc(c * sizeof(int));
    uband = (int *)malloc((r + c - 1) * sizeof(int));
    dband = (int *)malloc((r + c - 1) * sizeof(int));

    makeband(r, c, rband, cband, uband, dband);
    create_input(r, c, input, rproj, cproj, uproj, dproj, uband, dband);
}
Пример #4
0
int ray_trace(char* filename) {
  ray3_t primary_ray;
  int frame_z = 300;
  int frame_x = 0;
  int frame_y = 0;
  color_t hicolor;

  for (frame_x = 0; frame_x < frame_width; ++frame_x) {
    for (frame_y = 0; frame_y < frame_height; ++frame_y) {

      /* Primary Ray (test ray) */
      primary_ray.origin = eye_origin;
      primary_ray.vector.x = (frame_x - (frame_width/2) - primary_ray.origin.x);
      primary_ray.vector.y = (frame_y - (frame_height/2) - primary_ray.origin.y);
      primary_ray.vector.z = (frame_z - primary_ray.origin.z);
      normalize_vector(&primary_ray.vector);

      hicolor = trace_ray(&primary_ray, 0);
      frame_buffer[frame_y][frame_x].r = (uint8_t) (hicolor.r * 0xFF);
      frame_buffer[frame_y][frame_x].g = (uint8_t) (hicolor.g * 0xFF);
      frame_buffer[frame_y][frame_x].b = (uint8_t) (hicolor.b * 0xFF);
      frame_buffer[frame_y][frame_x].a = (uint8_t) (hicolor.a * 0xFF);
    }
  }

  write_bmp(filename, frame_width, frame_height, frame_buffer);
  return 0;
}
Пример #5
0
__inline__ int write_bmp(char * filename,
        rgb_t * pixel,
        int  width,
        int  height)
{
    bmp_t bmp;
    int sizeImage = height* (int) real_width(width*sizeof(rgb_t));;

    bmp.file_header.type = 19778;  
    bmp.file_header.reserved1 = bmp.file_header.reserved2 = 0;
    bmp.file_header.offsetbytes = 54;  
    bmp.file_header.fsize = 54 + sizeImage;

    bmp.info_header.hsize = sizeof(bitmapInfoHeader_t);
    bmp.info_header.width = width;
    bmp.info_header.height = height;
    bmp.info_header.planes = 1;
    bmp.info_header.bitcount = 8 * sizeof(rgb_t);
    bmp.info_header.compression = 0;
    bmp.info_header.sizeimage = sizeImage;
    bmp.info_header.xpelspermeter = 0;
    bmp.info_header.ypelspermeter = 0;
    bmp.info_header.colorsused = 0;
    bmp.info_header.colorsimportant = 0;

    return write_bmp(filename, &bmp, pixel);
}
Пример #6
0
//-----------------------------------------------------------------------------
///
/// This method is for generating an bitmap image with some points representing
/// a line, a circle in the middle of the image and a background color.
///
/// @param points represents the line which has to be drawn onto the image.
/// @param width is the resolution for the x-axis given in pixel.
/// @param height is the resolution for the y-axis given in pixel.
/// @param filename has to be a valid .bmp filename.
///
/// @return int for success or failure of the whole function
//
int generateImage(short *points, int width, int height, 
                  char *filename)
{
  int count_i;
  int row;
  int col;
  int radius;

  // Color circle: dark green
  // Color background: green
  // Color line: white
  //                     R,   G,   B
  Color col_circle = {  39, 174,  96 };
  Color col_backgr = {  46, 204, 113 };
  Color col_line =   { 255, 255, 255 };

  Byte data[height * width * 3];

  Circle circle = { width / 2 - 1, height / 2 - 1, MIDDLE_CIRCLE_RADIUS };

  for(count_i = 0; count_i < height * width * 3; count_i += 3)
  {
    row = (count_i / 3) / width;
    col = (count_i / 3) % width;

    // Get radius with pythagoras
    radius = sqrt(pow(fabs(row - circle.y_), 2) + 
                  pow(fabs(col - circle.x_), 2));

    if(radius < circle.r_)
    {
      data[count_i] = col_circle.red_;
      data[count_i + 1] = col_circle.green_;
      data[count_i + 2] = col_circle.blue_;
    }
    else if(radius < circle.r_ + 1)
    {
      data[count_i] = (col_circle.red_ + col_backgr.red_) / 2;
      data[count_i + 1] = (col_circle.green_ + col_backgr.green_) / 2;
      data[count_i + 2] = (col_circle.blue_ + col_backgr.blue_) / 2;
    }
    else if (points[ARRAY_ACCESS(col, row, width)])
    {
      data[count_i] = col_line.red_;
      data[count_i + 1] = col_line.green_;
      data[count_i + 2] = col_line.blue_;
    }
    else
    {
      data[count_i] = col_backgr.red_;
      data[count_i + 1] = col_backgr.green_;
      data[count_i + 2] = col_backgr.blue_;
    }
  }

  return write_bmp(filename, width, height, data);
}
Пример #7
0
int main(void) {
    bmp_meta_t meta;
    unsigned char* image = read_bmp("test.bmp", &meta);
    if (image) {
        write_bmp(image, meta.width, meta.height, "test-copy.bmp");
    }

    return 0;
}
Пример #8
0
void BackProjection::output(void *param)
{
    outParam *Param = reinterpret_cast < outParam * >(param);
    std::string outName = Param->outputFilename;

    std::string datName = outName + ".dat";
    std::string bmpName = outName + ".bmp";

    printimage(r, c, guess, datName.c_str());
    write_bmp(bmpName.c_str(), guess, r, c);
}
Пример #9
0
bool EmdTimBitmap::writeBmpFile(QString path) {
    QFile file(path);

    if (!file.open(QFile::WriteOnly | QFile::Truncate)) {
        return false;
    }

    QDataStream out(&file);    

    bool stat = write_bmp(out, this->width(), this->height(), this->raw());
    return stat;
}
Пример #10
0
int render(const Setting& setting, Camera& camera, Screen& screen, Scene& scene, ImageBuffer& buffer)
{
	int time_count = 1;
	clock_t start_time, current_time;
	float now_time;
	start_time = clock();
	char fname[255];

	for (int y = 0; y < setting.reso_h; y++)
	{
		Imath::Rand48 rnd;
		std::cout << "Rendering (y = " << y << ") " << (100.0 * y / (setting.reso_h - 1)) << "%" << std::endl;

		for (int x = 0; x < setting.reso_w; x++)
		{
			int index = (setting.reso_h - y - 1) * setting.reso_w + x;
			buffer[index] = Imath::C3f(0,0,0);
			
			for (int sy = 0; sy < setting.supersamples; sy++)
			{
				for (int sx = 0; sx < setting.supersamples; sx++)
				{
					Imath::C3f acm_rad = Imath::C3f(0,0,0);

					for (int s = 0; s < setting.samples; s++)
					{
						Ray ray = Ray(camera,screen,setting,x,y,sx,sy);
						acm_rad += radiance(scene, ray, rnd, 0) / setting.samples / (setting.supersamples * setting.supersamples);
						buffer[index] += acm_rad;

						current_time = clock();
						now_time = static_cast<float>((current_time - start_time) / CLOCKS_PER_SEC);
						if (now_time > time_count * 60.0f)
						{
							std::cout << "width:" << setting.reso_w << std::endl;
							std::cout << "height:" << setting.reso_h << std::endl;
							std::cout << "sample:" << setting.samples << std::endl;
							std::cout << "subpixel:" << setting.supersamples << std::endl;
							std::cout << time_count << "minute(s)" << std::endl;
							std::cout << "image output..." << std::endl;
							sprintf(fname, "out_%02d.bmp", time_count);
							write_bmp(fname, buffer, setting);
							time_count++;
						}
					}
				}
			}

		}
	}

	return 0;
}
Пример #11
0
int main_replaced(int argc, char** argv){

    //Initialization
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    //Reading image
    if(rank == 0){
        image = read_bmp("Lenna_blur.bmp");
    }

    //Creating cartesian communicator
    MPI_Dims_create(size, 2, dims);
    MPI_Cart_create( MPI_COMM_WORLD, 2, dims, periods, 0, &cart_comm );
    MPI_Cart_coords( cart_comm, rank, 2, coords );

    MPI_Cart_shift( cart_comm, 0, 1, &north, &south );
    MPI_Cart_shift( cart_comm, 1, 1, &west, &east );

    local_image_size[0] = image_size[0]/dims[0];
    local_image_size[1] = image_size[1]/dims[1];

    //Allocating buffers
    int lsize = local_image_size[0]*local_image_size[1];
    int lsize_border = (local_image_size[0] + 2*BORDER)*(local_image_size[1] + 2*BORDER);
    local_image_orig = (unsigned char*)malloc(sizeof(unsigned char)*lsize);
    local_image[0] = (unsigned char*)calloc(lsize_border, sizeof(unsigned char));
    local_image[1] = (unsigned char*)calloc(lsize_border, sizeof(unsigned char));

    create_types();

    distribute_image();

    initialilze_guess();

    //Main loop
    for(int i = 0; i < ITERATIONS; i++){
        exchange_borders(i);
        perform_convolution(i);
    }

    gather_image();

    MPI_Finalize();

    //Write image
    if(rank==0){
        write_bmp(image, image_size[0], image_size[1]);
    }

    exit(0);
}
Пример #12
0
void save_screen_shot(int automap_flag)
{
//	fix t1;
    char message[100];
    static int savenum=0;
    char savename[13];
    unsigned char *buf;

    if (!ogl_readpixels_ok) {
        if (!automap_flag)
            hud_message(MSGC_GAME_FEEDBACK,"glReadPixels not supported on your configuration");
        return;
    }

    stop_time();

//added/changed on 10/31/98 by Victor Rachels to fix overwrite each new game
    if ( savenum == 9999 ) savenum = 0;
    sprintf(savename,"scrn%04d.tga",savenum++);

    while(!access(savename,0))
    {
        if ( savenum == 9999 ) savenum = 0;
        sprintf(savename,"scrn%04d.tga",savenum++);
    }
    sprintf( message, "%s '%s'", TXT_DUMPING_SCREEN, savename );
//end this section addition/change - Victor Rachels

    if (automap_flag) {
//	save_font = grd_curcanv->cv_font;
//	gr_set_curfont(GAME_FONT);
//	gr_set_fontcolor(gr_find_closest_color_current(0,31,0),-1);
//	gr_get_string_size(message,&w,&h,&aw);
//		modex_print_message(32, 2, message);
    } else {
        hud_message(MSGC_GAME_FEEDBACK,message);
    }

    buf = malloc(grd_curscreen->sc_w*grd_curscreen->sc_h*3);
    glReadBuffer(GL_FRONT);
    glReadPixels(0,0,grd_curscreen->sc_w,grd_curscreen->sc_h,GL_RGB,GL_UNSIGNED_BYTE,buf);
    write_bmp(savename,grd_curscreen->sc_w,grd_curscreen->sc_h,buf);
    free(buf);

    key_flush();
    start_time();
}
int main(int argc, char** argv){

    if(argc != 3){
        printf("Usage: %s image n_threads\n", argv[0]);
        exit(-1);
    }
    int n_threads = atoi(argv[2]);

    // read from the input bmp image file
    unsigned char* image = read_bmp(argv[1]);
    unsigned char* output_image = malloc(sizeof(unsigned char) * image_size);

    // create a histogram for the pixel values
    int* histogram = (int*)calloc(sizeof(int), color_depth);
#pragma omp parallel for num_threads(n_threads)
    for(int i = 0; i < image_size; i++){
        int image_val = image[i]; 
        // histogram[] is a shared variable, hence to avoid race conditions, critical clause has been used
#pragma omp critical
        histogram[image_val]++;
    }


    float* transfer_function = (float*)calloc(sizeof(float), color_depth);
    
    // finding the normalised values using cumulative mass function
    // different scheduling clauses can be used here for comparative analysis
#pragma omp parallel for num_threads(n_threads) schedule(static,1) 
    for(int i = 0; i < color_depth; i++){
        float sum = 0.0;
        for(int j = 0; j < i+1; j++){
            sum += (float)histogram[j];
        }
        transfer_function[i] += color_depth*((float)sum)/(image_size);
    }


#pragma omp parallel for num_threads(n_threads)
    for(int i = 0; i < image_size; i++){
        output_image[i] = transfer_function[image[i]];
    }

    // write data to output bmp image file
    write_bmp(output_image, image_width, image_height);
}
Пример #14
0
int main(int argc, char** argv){

    if(argc != 3){
        printf("Useage: %s image n_threads\n", argv[0]);
        exit(-1);
    }
    int n_threads = atoi(argv[2]);

    unsigned char* image = read_bmp(argv[1]);
    unsigned char* output_image = malloc(sizeof(unsigned char) * image_size);


    int* histogram = (int*)calloc(sizeof(int), color_depth);
#pragma omp parallel for num_threads(n_threads)
    for(int i = 0; i < image_size; i++){
        int image_val = image[i]; 
#pragma omp critical
        histogram[image_val]++;
    }


    float* transfer_function = (float*)calloc(sizeof(float), color_depth);
    
#pragma omp parallel for num_threads(n_threads) schedule(static,1)
    for(int i = 0; i < color_depth; i++){
        for(int j = 0; j < i+1; j++){
            transfer_function[i] += color_depth*((float)histogram[j])/(image_size);
        }
    }


#pragma omp parallel for num_threads(n_threads)
    for(int i = 0; i < image_size; i++){
        output_image[i] = transfer_function[image[i]];
    }

    write_bmp(output_image, image_width, image_height);
}
Пример #15
0
int main(int argc, char *argv[])
{
  struct timeval tv_start, tv_end;
  int picture[WIDTH * HEIGHT];
#if 0
  float real_start = -0.1592 - 0.01;
  float real_end = -0.1592 + 0.01;
  float imaginary_start = -1.0317 - 0.01;
  float imaginary_end = -1.0317 + 0.01;
#endif

  float real_start = 0.37 - 0.00;
  float real_end = 0.37 + 0.04;
  float imaginary_start = -0.2166 - 0.02;
  float imaginary_end = -0.2166 + 0.02;

#if 0
  float real_start = -2.00;
  float real_end = 1.00;
  float imaginary_start = -1.00;
  float imaginary_end = 1.00;
#endif

  int do_simd = 1;

  if (argc != 2)
  {
    printf("Usage: %s <normal/sse/avx2/avx_512>\n", argv[0]);
    exit(0);
  }

  if (strcmp(argv[1], "normal") == 0) { do_simd = 0; }
  else if (strcmp(argv[1], "sse") == 0) { do_simd = 1; }
  else if (strcmp(argv[1], "avx2") == 0) { do_simd = 2; }
  else if (strcmp(argv[1], "avx_512") == 0) { do_simd = 3; }

  gettimeofday(&tv_start, NULL);

  if (do_simd == 1)
  {
    mandel_calc_sse(picture, WIDTH, HEIGHT, real_start, real_end, imaginary_start, imaginary_end);
  }
    else
  if (do_simd == 2)
  {
    mandel_calc_avx2(picture, WIDTH, HEIGHT, real_start, real_end, imaginary_start, imaginary_end);
  }
    else
  if (do_simd == 3)
  {
    mandel_calc_avx_512(picture, WIDTH, HEIGHT, real_start, real_end, imaginary_start, imaginary_end);
  }
    else
  {
    mandel_calc(picture, WIDTH, HEIGHT, real_start, real_end, imaginary_start, imaginary_end);
  }

  gettimeofday(&tv_end, NULL);

#if 0
  int picture2[WIDTH * HEIGHT];
  mandel_calc(picture2, WIDTH, HEIGHT, real_start, real_end, imaginary_start, imaginary_end);

  int n;
  for (n = 0; n < WIDTH * HEIGHT; n++)
  {
    if (picture[n] != picture2[n])
    {
      printf("error %d  %8x %8x\n", n, picture[n], picture2[n]);
    }
  }
#endif

  printf("%ld %ld\n", tv_end.tv_sec, tv_end.tv_usec);
  printf("%ld %ld\n", tv_start.tv_sec, tv_start.tv_usec);
  long time_diff = tv_end.tv_usec - tv_start.tv_usec;
  while(time_diff < 0) { tv_end.tv_sec--; time_diff += 1000000; }
  time_diff += (tv_end.tv_sec - tv_start.tv_sec) * 1000000;
  printf("time=%f\n", (float)time_diff / 1000000);

  write_bmp(picture, WIDTH, HEIGHT);

  return 0;
}
Пример #16
0
int main(int argc, char *argv[])
{
    char*          szOutputFilename = 0;
    char*          szInputFilename = 0;

    uint32_t       ulColorSelectorIndex = 0;

    FILE*          pFile;
    struct stat    sFileStatus;
    int            nStatus;

    uint32_t       ulBlockSize;
    uint8_t*       pBlockBuffer;

    void*          pImageBuffer;
    bmp_pixel32_t* pImageBufferIndex;
    int            nImageBufferSize;
    int            nImageWidth;
    int            nImageHeight;

    uint32_t       ulSectorCount = 0;
    uint32_t       ulSectorIndex = 0;

    uint32_t       ulPercentDemoninator;
    uint32_t       ulPercentComplete = 0;
    uint32_t       ulPercentTemporary = 0;
    int            nReturnValue = 0;
    void           (*pfColorSelect)(bmp_pixel32_t*, uint8_t*, uint32_t) = 0;

    memset(&sFileStatus, 0x0, sizeof(struct stat));

    if (argc != 6)
    {
        fprintf(stderr, "Usage: %s [input filename] [ouput filename] [block size] [image width] [color selector]\n",
                argv[0]);
        nReturnValue = -1;
    }
    else
    {
        szInputFilename = argv[1];
        szOutputFilename = argv[2];
        sscanf(argv[3], "%lu", &ulBlockSize);
        sscanf(argv[4], "%lu", &nImageWidth);
        sscanf(argv[5], "%lu", &ulColorSelectorIndex);

        switch (ulColorSelectorIndex)
        {
        case AVERAGE:
            pfColorSelect = cs_average;
            break;

        case STDDEV:
            pfColorSelect = cs_stddev;
            break;

        case SOLID_FF:
            pfColorSelect = cs_solidffs;
            break;

        case CHKSUM24:
            pfColorSelect = cs_sum24;
            break;

        default:
            pfColorSelect = 0;
            break;
        }

        if (0 == pfColorSelect)
        {
            fprintf(stderr,
                "Invalid color selector index: %lu.  Valid selections:\n"
                "   0. Average\n"
                "   1. Standard Deviation\n"
                "   2. Solid FFs\n"
                "   3. Checksum (24-bit)\n",
                ulColorSelectorIndex);

            nReturnValue = -1;
        }

        else if (0 == (pBlockBuffer = (uint8_t*) malloc(ulBlockSize)))
        {
            fprintf(stderr, "buffer allocation failed.\n");
            nReturnValue = -1;
        }

        /* Status the file size. */
        else if (0 != (nStatus = stat(szInputFilename, &sFileStatus)))
        {
            fprintf(stderr, "stat() failed on file: '%s.  Error Code: %d\n",
                    szInputFilename, nStatus);
            nReturnValue = -1;
        }

        /* Open the file. */
        else if(0 == (pFile = fopen(szInputFilename, "rb")))
        {
            fprintf(stderr, "fopen() failed on file: '%s.\n",
                    szInputFilename);
            nReturnValue = -1;
        }

        /* Process the file. */
        else
        {
            /* find the number of bits in image. */
            ulSectorCount = ((uint32_t) sFileStatus.st_size / ulBlockSize);

            /* find the number of rows required to fit all bits. */
            nImageHeight = ((ulSectorCount + (nImageWidth - 1)) / nImageWidth);

            /* nImageBufferSize = (sFileStatus.st_size / SECTOR_SIZE) * sizeof(bmp_pixel32_t); */
            nImageBufferSize = (nImageWidth * nImageHeight) * sizeof(bmp_pixel32_t);

            /* Allocate Image Buffer. */
            if (0 == (pImageBuffer = malloc(nImageBufferSize)))
            {
                fprintf(stderr, "buffer allocation failed.\n");
                nReturnValue = -1;
            }

            /* Process the file data. */
            else
            {
                memset (pImageBuffer, 0x00, nImageBufferSize);
                pImageBufferIndex = (bmp_pixel32_t*) pImageBuffer;

                /* Current Sector Index / Percent Denominator equals (percentage * 10) */
                ulPercentDemoninator = (ulSectorCount / 1000);

                /* Read the buffer, 512 bytes at a time. */
                while (1 == fread(pBlockBuffer,ulBlockSize,1,pFile))
                {
                    pfColorSelect(pImageBufferIndex, pBlockBuffer, ulBlockSize);

                    ++pImageBufferIndex;
                    ++ulSectorIndex;

                    ulPercentTemporary = (ulSectorIndex / ulPercentDemoninator);

                    if (ulPercentComplete != ulPercentTemporary)
                    {
                        ulPercentComplete = ulPercentTemporary;
                        fprintf(stdout, "Processing %3lu.%lu%%...\r",
                            (ulPercentComplete / 10), (ulPercentComplete % 10));
                    }

                }

                /* Write the image buffer to file. */
                write_bmp(szOutputFilename, nImageWidth, nImageHeight, pImageBuffer);

                /* Free the buffer. */
                free (pImageBuffer);
                pImageBuffer = 0;
            }

            /* Close the file. */
            if((pFile != 0) && (0 != (nStatus = fclose(pFile))))
            {
                fprintf(stderr, "fclose() failed on file: '%s.\n",
                        szInputFilename);
                nReturnValue = -1;
            }

            /* Free the buffer. */
            free (pBlockBuffer);
            pBlockBuffer = 0;
        }
    }

    return nReturnValue;
}
Пример #17
0
// Serial ray casting
unsigned char* raycast_serial(unsigned char* data, unsigned char* region){
    unsigned char* image = (unsigned char*)malloc(sizeof(unsigned char)*IMAGE_DIM*IMAGE_DIM);
    
    // Camera/eye position, and direction of viewing. These can be changed to look
    // at the volume from different angles.
    float3 camera = {.x=1000,.y=1000,.z=1000};
    float3 forward = {.x=-1, .y=-1, .z=-1};
    float3 z_axis = {.x=0, .y=0, .z = 1};
    
    // Finding vectors aligned with the axis of the image
    float3 right = cross(forward, z_axis);
    float3 up = cross(right, forward);
    
    // Creating unity lenght vectors
    forward = normalize(forward);
    right = normalize(right);
    up = normalize(up);
    
    float fov = 3.14/4;
    float pixel_width = tan(fov/2.0)/(IMAGE_DIM/2);
    float step_size = 0.5;
    
    // For each pixel
    for(int y = -(IMAGE_DIM/2); y < (IMAGE_DIM/2); y++){
        for(int x = -(IMAGE_DIM/2); x < (IMAGE_DIM/2); x++){
            
            // Find the ray for this pixel
            float3 screen_center = add(camera, forward);
            float3 ray = add(add(screen_center, scale(right, x*pixel_width)), scale(up, y*pixel_width));
            ray = add(ray, scale(camera, -1));
            ray = normalize(ray);
            float3 pos = camera;
            
            // Move along the ray, we stop if the color becomes completely white,
            // or we've done 5000 iterations (5000 is a bit arbitrary, it needs 
            // to be big enough to let rays pass through the entire volume)
            int i = 0;
            float color = 0;
            while(color < 255 && i < 5000){
                i++;
                pos = add(pos, scale(ray, step_size));          // Update position
                int r = value_at(pos, region);                  // Check if we're in the region
                color += value_at(pos, data)*(0.01 + r) ;       // Update the color based on data value, and if we're in the region
            }
            
            // Write final color to image
            image[(y+(IMAGE_DIM/2)) * IMAGE_DIM + (x+(IMAGE_DIM/2))] = color > 255 ? 255 : color;
        }
    }
    
    return image;
}


// Check if two values are similar, threshold can be changed.
int similar(unsigned char* data, int3 a, int3 b){
    unsigned char va = data[a.z * DATA_DIM*DATA_DIM + a.y*DATA_DIM + a.x];
    unsigned char vb = data[b.z * DATA_DIM*DATA_DIM + b.y*DATA_DIM + b.x];
    
    int i = abs(va-vb) < 1;
    return i;
}


// Serial region growing, same algorithm as in assignment 2
unsigned char* grow_region_serial(unsigned char* data){
    unsigned char* region = (unsigned char*)calloc(sizeof(unsigned char), DATA_DIM*DATA_DIM*DATA_DIM);
    
    stack_t* stack = new_stack();
    
    int3 seed = {.x=50, .y=300, .z=300};
    push(stack, seed);
    region[seed.z *DATA_DIM*DATA_DIM + seed.y*DATA_DIM + seed.x] = 1;
    
    int dx[6] = {-1,1,0,0,0,0};
    int dy[6] = {0,0,-1,1,0,0};
    int dz[6] = {0,0,0,0,-1,1};
    
    while(stack->size > 0){
        int3 pixel = pop(stack);
        for(int n = 0; n < 6; n++){
            int3 candidate = pixel;
            candidate.x += dx[n];
            candidate.y += dy[n];
            candidate.z += dz[n];
            
            if(!inside_int(candidate)){
                continue;
            }
            
            if(region[candidate.z * DATA_DIM*DATA_DIM + candidate.y*DATA_DIM + candidate.x]){
                continue;
            }
            
            if(similar(data, pixel, candidate)){
                push(stack, candidate);
                region[candidate.z * DATA_DIM*DATA_DIM + candidate.y*DATA_DIM + candidate.x] = 1;
            }
        }
    }
    
    return region;
}

unsigned char* grow_region_gpu(unsigned char* data){
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_kernel kernel;
    cl_int err;
    char *source;
    int i;
    
    clGetPlatformIDs(1, &platform, NULL);
    clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
    context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
    
    printPlatformInfo(platform);

    queue = clCreateCommandQueue(context, device, 0, &err);
    kernel = buildKernel("region.cl", "region", NULL, context, device);

    //Host variables
    unsigned char* host_region = (unsigned char*)calloc(sizeof(unsigned char), DATA_SIZE);
    int            host_unfinished;

    cl_mem device_region     = clCreateBuffer(context, CL_MEM_READ_WRITE, DATA_SIZE * sizeof(cl_uchar) ,NULL,&err);
    cl_mem device_data       = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar), NULL,&err);
    cl_mem device_unfinished = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_int), NULL,&err);
    clError("Error allocating memory", err);

    //plant seed
    int3 seed = {.x=50, .y=300, .z=300};
    host_region[index(seed.z, seed.y, seed.x)] = 2;

    //Copy data to the device
    clEnqueueWriteBuffer(queue, device_data  , CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), data       , 0, NULL, NULL);
    clEnqueueWriteBuffer(queue, device_region, CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), host_region, 0, NULL, NULL);

    //Calculate block and grid sizes
    size_t global[] = { 512, 512, 512 }; 
    size_t local[] = { 8, 8, 8 };


    //Run kernel untill completion
    do{
        host_unfinished = 0;
        clEnqueueWriteBuffer(queue, device_unfinished, CL_FALSE, 0, sizeof(cl_int), &host_unfinished  , 0, NULL, NULL);
        clFinish(queue);

        err = clSetKernelArg(kernel, 0, sizeof(device_data), (void*)&device_data);
        err = clSetKernelArg(kernel, 1, sizeof(device_region), (void*)&device_region);
        err = clSetKernelArg(kernel, 2, sizeof(device_unfinished), (void*)&device_unfinished);
        clError("Error setting arguments", err);

        //Run the kernel
        clEnqueueNDRangeKernel(queue, kernel, 3, NULL, &global, &local, 0, NULL, NULL);
        clFinish(queue);
        clError("Error running kernel", err);

        err = clEnqueueReadBuffer(queue, device_unfinished, CL_TRUE, 0, sizeof(cl_int), &host_unfinished, 0, NULL, NULL);
        clFinish(queue);
        clError("Error reading buffer 1", err);

    }while(host_unfinished);

    //Copy result to host
    err = clEnqueueReadBuffer(queue, device_region, CL_TRUE, 0, DATA_SIZE * sizeof(cl_uchar), host_region, 0, NULL, NULL);
    clFinish(queue);
    clError("Error reading buffer 2", err);

    return host_region;
}

unsigned char* raycast_gpu(unsigned char* data, unsigned char* region){
    cl_platform_id platform;
    cl_device_id device;
    cl_context context;
    cl_command_queue queue;
    cl_kernel kernel;
    cl_int err;
    char *source;
    int i;
    
    clGetPlatformIDs(1, &platform, NULL);
    clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
    context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);

    printPlatformInfo(platform);
    printDeviceInfo(device);

    queue = clCreateCommandQueue(context, device, 0, &err);
    kernel = buildKernel("raycast.cl", "raycast", NULL, context, device);


    cl_mem device_region = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar) ,NULL,&err);
    cl_mem device_data   = clCreateBuffer(context, CL_MEM_READ_ONLY, DATA_SIZE * sizeof(cl_uchar), NULL,&err);
    cl_mem device_image  = clCreateBuffer(context, CL_MEM_READ_WRITE, IMAGE_SIZE * sizeof(cl_uchar),NULL,&err);
    clError("Error allocating memory", err);
    //Copy data to the device
    clEnqueueWriteBuffer(queue, device_data  , CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), data  , 0, NULL, NULL);
    clEnqueueWriteBuffer(queue, device_region, CL_FALSE, 0, DATA_SIZE * sizeof(cl_uchar), region, 0, NULL, NULL);

    int grid_size = IMAGE_DIM;
    int block_size = IMAGE_DIM;


    //Set up kernel arguments
    err = clSetKernelArg(kernel, 0, sizeof(device_data), (void*)&device_data);
    err = clSetKernelArg(kernel, 1, sizeof(device_region), (void*)&device_region);
    err = clSetKernelArg(kernel, 2, sizeof(device_image), (void*)&device_image);
    clError("Error setting arguments", err);

    //Run the kernel
    const size_t globalws[2] = {IMAGE_DIM, IMAGE_DIM};
    const size_t localws[2] = {8, 8};
    clEnqueueNDRangeKernel(queue, kernel, 2, NULL, &globalws, &localws, 0, NULL, NULL);
    
    clFinish(queue);


    //Allocate memory for the result
    unsigned char* host_image = (unsigned char*)malloc(IMAGE_SIZE_BYTES);

    //Copy result from device
    err = clEnqueueReadBuffer(queue, device_image, CL_TRUE, 0, IMAGE_SIZE * sizeof(cl_uchar), host_image, 0, NULL, NULL);
    clFinish(queue);


    //Free device memory
    return host_image;
}


int main(int argc, char** argv){
    
    unsigned char* data = create_data();
    
    unsigned char* region = grow_region_gpu(data);
    
    unsigned char* image = raycast_gpu(data, region);
    
    write_bmp(image, IMAGE_DIM, IMAGE_DIM);
}
Пример #18
0
Файл: main.c Проект: Bevara/GPAC
/*generates an intertwined bmp from a scene file with 5 different viewpoints*/
void bifs3d_viewpoints_merger(GF_ISOFile *file, char *szConfigFile, u32 width, u32 height, char *rad_name, u32 dump_type, char *out_dir, Double fps, s32 frameID, s32 dump_time)
{
	GF_User user;
	char out_path[GF_MAX_PATH];
	char old_driv[1024];
	BIFSVID b2v;
	Bool needs_raw;
	GF_Err e;
	GF_VideoSurface fb;
	unsigned char **rendered_frames;
	u32 nb_viewpoints = 5;
	u32 viewpoint_index;


	/* Configuration of the Rendering Capabilities */
	{
		const char *test;
		char config_path[GF_MAX_PATH];
		memset(&user, 0, sizeof(GF_User));
		user.config = gf_cfg_init(szConfigFile, NULL);

		if (!user.config) {
			fprintf(stdout, "Error: Configuration File \"%s\" not found in %s\n", GPAC_CFG_FILE, config_path);
			return;
		}

		test = gf_cfg_get_key(user.config, "General", "ModulesDirectory");
		user.modules = gf_modules_new((const unsigned char *) test, user.config);
		strcpy(old_driv, "raw_out");
		if (!gf_modules_get_count(user.modules)) {
			printf("Error: no modules found\n");
			goto err_exit;
		}

		/*switch driver to raw_driver*/
		test = gf_cfg_get_key(user.config, "Video", "DriverName");
		if (test) strcpy(old_driv, test);

		needs_raw = 0;
		test = gf_cfg_get_key(user.config, "Compositor", "RendererName");
		/*since we only support RGB24 for MP42AVI force using RAW out with 2D driver*/
		if (test && strstr(test, "2D")) {
			gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output");
			needs_raw = 1;
		}
		if (needs_raw) {
			test = gf_cfg_get_key(user.config, "Video", "DriverName");
			if (stricmp(test, "raw_out") && stricmp(test, "Raw Video Output")) {
				printf("couldn't load raw output driver (%s used)\n", test);
				goto err_exit;
			}
		}
	}

	memset(&b2v, 0, sizeof(BIFSVID));
	user.init_flags = GF_TERM_NO_AUDIO;
	/* Initialization of the compositor */
	b2v.sr = gf_sc_new(&user, 0, NULL);
	gf_sc_set_option(b2v.sr, GF_OPT_VISIBLE, 0);

	/* Initialization of the scene graph */
	b2v.sg = gf_sg_new();
	gf_sg_set_scene_time_callback(b2v.sg, get_scene_time, &b2v);
	gf_sg_set_init_callback(b2v.sg, node_init, &b2v);
	gf_sg_set_modified_callback(b2v.sg, node_modif, &b2v);

	/*load config*/
	gf_sc_set_option(b2v.sr, GF_OPT_RELOAD_CONFIG, 1);

	{
		u32 di;
		u32 track_number;
		GF_ESD *esd;
		u16 es_id;
		b2v.bifs = gf_bifs_decoder_new(b2v.sg, 0);

		for (track_number=0; track_number<gf_isom_get_track_count(file); track_number++) {
			esd = gf_isom_get_esd(file, track_number+1, 1);
			if (!esd) continue;
			if (!esd->dependsOnESID && (esd->decoderConfig->streamType == GF_STREAM_SCENE)) break;
			gf_odf_desc_del((GF_Descriptor *) esd);
			esd = NULL;
		}
		if (!esd) {
			printf("no bifs track found\n");
			goto err_exit;
		}

		es_id = (u16) gf_isom_get_track_id(file, track_number+1);
		e = gf_bifs_decoder_configure_stream(b2v.bifs, es_id, esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, esd->decoderConfig->objectTypeIndication);
		if (e) {
			printf("BIFS init error %s\n", gf_error_to_string(e));
			gf_odf_desc_del((GF_Descriptor *) esd);
			esd = NULL;
			goto err_exit;
		}

		{
			GF_ISOSample *samp = gf_isom_get_sample(file, track_number+1, 1, &di);
			b2v.cts = samp->DTS + samp->CTS_Offset;
			/*apply command*/
			gf_bifs_decode_au(b2v.bifs, es_id, samp->data, samp->dataLength, ((Double)(s64)b2v.cts)/1000.0);
			gf_isom_sample_del(&samp);
		}

		b2v.duration = gf_isom_get_media_duration(file, track_number+1);

		gf_odf_desc_del((GF_Descriptor *) esd);

	}
	gf_sc_set_scene(b2v.sr, b2v.sg);

	if (!width || !height) {
		gf_sg_get_scene_size_info(b2v.sg, &width, &height);
	}
	/*we work in RGB24, and we must make sure the pitch is %4*/
	if ((width*3)%4) {
		printf("Adjusting width (%d) to have a stride multiple of 4\n", width);
		while ((width*3)%4) width--;
	}
	gf_sc_set_size(b2v.sr, width, height);
	gf_sc_get_screen_buffer(b2v.sr, &fb);
	width = fb.width;
	height = fb.height;
	gf_sc_release_screen_buffer(b2v.sr, &fb);

	GF_SAFEALLOC(rendered_frames, nb_viewpoints*sizeof(char *));
	for (viewpoint_index = 1; viewpoint_index <= nb_viewpoints; viewpoint_index++) {
		GF_SAFEALLOC(rendered_frames[viewpoint_index-1], fb.width*fb.height*3);
		gf_sc_set_viewpoint(b2v.sr, viewpoint_index, NULL);
		gf_sc_draw_frame(b2v.sr);
		/*needed for background2D !!*/
		gf_sc_draw_frame(b2v.sr);
		strcpy(out_path, "");
		if (out_dir) {
			strcat(out_path, out_dir);
			if (out_path[strlen(out_path)-1] != '\\') strcat(out_path, "\\");
		}
		strcat(out_path, rad_name);
		strcat(out_path, "_view");
		gf_sc_get_screen_buffer(b2v.sr, &fb);
		write_bmp(&fb, out_path, viewpoint_index);
		memcpy(rendered_frames[viewpoint_index-1], fb.video_buffer, fb.width*fb.height*3);
		gf_sc_release_screen_buffer(b2v.sr, &fb);
	}

	if (width != 800 || height != 480) {
		printf("Wrong scene dimension, cannot produce output\n");
		goto err_exit;
	} else {
		u32 x, y;
		GF_VideoSurface out_fb;
		u32 bpp = 3;
		out_fb.width = 800;
		out_fb.height = 480;
		out_fb.pitch = 800*bpp;
		out_fb.pixel_format = GF_PIXEL_RGB_24;
		out_fb.is_hardware_memory = 0;
		GF_SAFEALLOC(out_fb.video_buffer, out_fb.pitch*out_fb.height)
#if 1
		for (y=0; y<out_fb.height; y++) {
			/*starting red pixel is R1, R5, R4, R3, R2, R1, R5, ... when increasing line num*/
			u32 line_shift = (5-y) % 5;
			for (x=0; x<out_fb.width; x++) {
				u32 view_shift = (line_shift+bpp*x)%5;
				u32 offset = out_fb.pitch*y + x*bpp;
				/* red */
				out_fb.video_buffer[offset] = rendered_frames[view_shift][offset];
				/* green */
				out_fb.video_buffer[offset+1] = rendered_frames[(view_shift+1)%5][offset+1];
				/* blue */
				out_fb.video_buffer[offset+2] = rendered_frames[(view_shift+2)%5][offset+2];
			}
		}
#else
		/*calibration*/
		for (y=0; y<out_fb.height; y++) {
			u32 line_shift = (5- y%5) % 5;
			for (x=0; x<out_fb.width; x++) {
				u32 view_shift = (line_shift+bpp*x)%5;
				u32 offset = out_fb.pitch*y + x*bpp;
				out_fb.video_buffer[offset] = ((view_shift)%5 == 2) ? 0xFF : 0;
				out_fb.video_buffer[offset+1] = ((view_shift+1)%5 == 2) ? 0xFF : 0;
				out_fb.video_buffer[offset+2] = ((view_shift+2)%5 == 2) ? 0xFF : 0;
			}
		}
#endif
		write_bmp(&out_fb, "output", 0);
	}

	/*destroy everything*/
	gf_bifs_decoder_del(b2v.bifs);
	gf_sg_del(b2v.sg);
	gf_sc_set_scene(b2v.sr, NULL);
	gf_sc_del(b2v.sr);



err_exit:
	/*	if (rendered_frames) {
			for (viewpoint_index = 1; viewpoint_index <= nb_viewpoints; viewpoint_index++) {
				if (rendered_frames[viewpoint_index-1]) gf_free(rendered_frames[viewpoint_index-1]);
			}
			gf_free(rendered_frames);
		}
		if (output_merged_frame) gf_free(output_merged_frame);
	*/
	if (user.modules) gf_modules_del(user.modules);
	if (needs_raw) gf_cfg_set_key(user.config, "Video", "DriverName", old_driv);
	gf_cfg_del(user.config);
}
Пример #19
0
Файл: main.c Проект: treblih/dip
inline int
image_proc(u8 ** index, u8 * image_buf, u8 * color_buf, int width,
	   int height, BMP_HEADER * p_header)
{
	char interact = 0;
	int char_test = 0;

	while (1) {
		printf("\n\nDIP has already held your image, what's next?\n"
		       "type:\n"
		       "[s] -> smooth\n"
		       "[h] -> sharp\n"
		       "[l] -> enlarge / shrink\n"
		       "[r] -> rotate\n" "[e] -> exit\n\n");
		while ((char_test = getchar()) != '\n' && char_test != EOF) {
			interact = char_test;

			/* 
			 * so significant here
			 * we need just a char, if user inputs such as 'sel',
			 * so the final char which installed in the var is
			 * 'l', not 's'
			 */
			while ((char_test = getchar()) != '\n'
			       && char_test != EOF) ;
			break;
		}

		switch (interact) {
		case 's':
			printf("which algorithm u wanna use?\n"
			       "type:\n"
			       "[k] -> k_near_average\n"
			       "[a] -> average_filter \t[1, 1, 1, 1, 1, 1, 1, 1, 1]\n"
			       "[m] -> median_filter\n");
			__asm__ __volatile__("2:");
			while ((char_test = getchar()) != '\n'
			       && char_test != EOF) {
				interact = char_test;
				while ((char_test = getchar()) != '\n'
				       && char_test != EOF) ;
				break;
			}

			switch (interact) {
			case 'k':
				smooth_avr_k(index, height, width);
				break;
			case 'a':
				smooth_avr_filter(index, height, width);
				break;
			case 'm':
				smooth_median_filter(index, height, width);
				break;
			default:
				printf("\nhey bro, type \"k\" or \"9\"\n");
				__asm__ __volatile__("jmp 2b");
				break;
			}
			if (write_bmp(p_header, color_buf, image_buf)) {
				printf("Sorry, Failure!\n");
			}
			printf("Well Done!\n");
			break;
		case 'h':
			printf("which algorithm u wanna use?\n"
			       "type:\n"
			       "[l] -> laplacian \t[0, 1, 0; 1, -4, 1; 0, 1, 0]\n"
			       "[f] -> high pass filter [-1, -1, -1; -1, 9, -1; -1, -1, -1]\n"
			       "[a] -> ladder \t\t[-1, 1; -1, 1]\n");
			__asm__ __volatile__("3:");
			while ((char_test = getchar()) != '\n'
			       && char_test != EOF) {
				interact = char_test;
				while ((char_test = getchar()) != '\n'
				       && char_test != EOF) ;
				break;
			}

			switch (interact) {
			case 'a':
				sharp_ladder(index, height, width);
				break;
			case 'l':
				sharp_laplacian(index, height, width);
				break;
			case 'f':
				sharp_hpass_filter(index, height, width);
				break;
			default:
				printf("\nhey bro, type \"l\" or \"f\"\n");
				__asm__ __volatile__("jmp 3b");
				break;
			}
			if (write_bmp(p_header, color_buf, image_buf)) {
				printf("Sorry, Failure!\n");
			}
			printf("Well Done!\n");
			break;
		case 'l':
			stretch(index, p_header, color_buf, width, height);
			break;
		case 'r':
			rotate(index, p_header, color_buf, width, height);
			break;
		case 'e':
			{
				int i = 0;
				for (; i < 10; i++) {
					printf("%x %c\n", *bp, *bp);
					bp++;
				}
				free(p_header);
				/* to avoid accessing freed memory */
				p_header = NULL;
			}
			return 0;
		default:
			printf("\nHey bro, please follow the rule\n");
			break;
		}
	}
}
Пример #20
0
int
write_image(const char *filename, int width, int height, unsigned char *rgb)
{
    FILE *outfile;
    char *extension = strrchr(filename, '.');
    char *lowercase;
    char *ptr;
    int success = 0;
  
    lowercase = malloc(strlen(extension) + 1);
    strcpy(lowercase, extension);
    ptr = lowercase;

    while (*ptr != '\0') *ptr++ = tolower(*extension++);

    outfile = fopen(filename, "wb");
    if (outfile == NULL) return(0);
  
    if (strcmp(lowercase, ".bmp" ) == 0)
    {
        success = write_bmp(filename, width, height, rgb); 
    }
    else if (strcmp(lowercase, ".gif" ) == 0)
    {
#ifdef HAVE_LIBGIF
        success = write_gif(filename, width, height, rgb); 
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with GIF support\n");
        success = 0;
#endif /* HAVE_LIBPNG */
    }
    else if ((   strcmp(lowercase, ".jpg" ) == 0)
             || (strcmp(lowercase, ".jpeg") == 0))
    {
#ifdef HAVE_LIBJPEG
        success = write_jpeg(outfile, width, height, rgb, Q); 
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with JPEG support\n");
        success = 0;
#endif /* HAVE_LIBJPEG */
    }

    else if (strcmp(lowercase, ".png" ) == 0)
    {
#ifdef HAVE_LIBPNG
        success = write_png(outfile, width, height, rgb, alpha); 
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with PNG support\n");
        success = 0;
#endif /* HAVE_LIBPNG */
    }

    else if ((   strcmp(lowercase, ".pbm") == 0)
             || (strcmp(lowercase, ".pgm") == 0)
             || (strcmp(lowercase, ".ppm") == 0))
    {
#ifdef HAVE_LIBPNM
        if (strcmp(lowercase, ".pbm") == 0)
            success = write_pnm(outfile, width, height, rgb, 1, PBM_TYPE, 0);
        else if (strcmp(lowercase, ".pgm") == 0)
            success = write_pnm(outfile, width, height, rgb, 255, 
                                PGM_TYPE, 0);
        else if (strcmp(lowercase, ".ppm") == 0)
            success = write_pnm(outfile, width, height, rgb, 255, 
                                PPM_TYPE, 0);
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with PNM support\n");
        success = 0;
#endif /* HAVE_LIBPNM */
    }

    else if ((strcmp(lowercase, ".tif" ) == 0)
             || (strcmp(lowercase, ".tiff" ) == 0))
    {
#ifdef HAVE_LIBTIFF
        success = write_tiff(filename, width, height, rgb); 
#else
        fprintf(stderr, 
                "Sorry, this program was not compiled with TIFF support\n");
        success = 0;
#endif /* HAVE_LIBTIFF */
    }

    else
    {
        fprintf(stderr, "Unknown image format\n");
        success = 0;
    }

    free(lowercase);
    fclose(outfile);
    return(success);
}
Пример #21
0
int main(int argc, char** argv)
{
	int x = 0, y = 0, sample = 0, subpixel = 0;
	int i = 1;
	while (true)
	{
		if (i >= argc) break;

		if (std::string(argv[i]).compare("-x") == 0)
		{
			i++;
			x = atoi(argv[i]);
			i++;
			continue;
		}

		if (std::string(argv[i]).compare("-y") == 0)
		{
			i++;
			y = atoi(argv[i]);
			i++;
			continue;
		}

		if (std::string(argv[i]).compare("-s") == 0)
		{
			i++;
			sample = atoi(argv[i]);
			i++;
			continue;
		}

		if (std::string(argv[i]).compare("-p") == 0)
		{
			i++;
			subpixel = atoi(argv[i]);
			i++;
			continue;
		}

	}

	if (x == 0 || y == 0 || sample == 0 || subpixel == 0)
	{
		std::cout << "argv error. using default setting." << std::endl;
		x = 640;
		y = 480;
		sample = 4;
		subpixel = 2;
	}

	std::cout << "width:" << x << std::endl;
	std::cout << "height:" << y << std::endl;
	std::cout << "sample:" << sample << std::endl;
	std::cout << "subpixel:" << subpixel << std::endl;

	Setting render_settings(x, y, sample, subpixel);
	Camera cam(Imath::V3d(50.0, 52.0, 220.0), Imath::V3d(0.0, -0.04, -30.0).normalized(), Imath::V3d(0.0, -1.0, 0.0));
	Screen screen(cam, render_settings);
	ImageBuffer image(render_settings.reso_w * render_settings.reso_h);

	//Mesh mesh = Mesh();
	//mesh.push_back(Triangle(Imath::V3d(12.8, 5.0, -10), Imath::V3d(5.0, 20.0, -10), Imath::V3d(20.0, 20.0, -10)));
	//Geometry geom(mesh, Imath::V3d(0, 0, 0), Imath::C3f(0.7, 0.5, 0.5));
	//Geometry geom(mesh, Imath::V3d(0, 0, 0), Imath::C3f(0.7, 0.5, 0.5));
	Scene scene;
	//scene.geometries.push_back(geom);
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(1e5 + 1, 40.8, 81.6),		1e5),	Imath::V3d(1e5 + 1, 40.8, 81.6),	Imath::C3f(0.75, 0.25, 0.25), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(-1e5 + 99, 40.8, 81.6),	1e5),	Imath::V3d(-1e5 + 99, 40.8, 81.6),	Imath::C3f(0.25, 0.25, 0.75), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(50, 40.8, 1e5),			1e5),	Imath::V3d(50, 40.8, 1e5),			Imath::C3f(0.75, 0.75, 0.75), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(50, 40.8, -1e5 + 250),	1e5),	Imath::V3d(50, 40.8, -1e5 + 250),	Imath::C3f(0.0,  0.0,  0.0), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(50, 1e5, 81.6),			1e5),	Imath::V3d(50, 1e5, 81.6),			Imath::C3f(0.75, 0.75, 0.75), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(50, -1e5 + 81.6, 81.6),	1e5),	Imath::V3d(50, -1e5 + 81.6, 81.6),	Imath::C3f(0.75, 0.75, 0.75), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(65, 20, 20),				20),	Imath::V3d(65, 20, 20),				Imath::C3f(0.25, 0.75, 0.25), Imath::C3f(0, 0, 0), Reflection::Diffuse));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(27, 16.5, 47),			16.5),	Imath::V3d(27, 16.5, 47),			Imath::C3f(0.99, 0.99, 0.99), Imath::C3f(0, 0, 0), Reflection::Specular));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(77, 16.5, 78),			16.5),	Imath::V3d(77, 16.5, 78),			Imath::C3f(0.99, 0.99, 0.99), Imath::C3f(0, 0, 0), Reflection::Refraction));
	scene.geometries.push_back(Geometry(Sphere(Imath::V3d(50, 90, 81.6),			15.0),	Imath::V3d(50, 90, 81.6),			Imath::C3f(0.0,  0.0,  0.0), Imath::C3f(36, 36, 36), Reflection::Diffuse));
	//scene.geometries.push_back(Geometry(Triangle(Imath::V3d(12.8, 5.0, -10), Imath::V3d(5.0, 20.0, -10), Imath::V3d(20.0, 20.0, -10)), Imath::V3d(65, 20, 20), Imath::C3f(0.75, 0.75, 0.75), Imath::C3f(0, 0, 0), Reflection::Diffuse));

	render(render_settings,cam,screen,scene,image);
	write_bmp("out_complete.bmp", image, render_settings);
	return 0;
}
Пример #22
0
int main(int argc, char **argv) {
    // bmp_t *b1, *b2, *bout;
    img_t *i1, *i2, **m;
    FILE *f;
    double zweight;
    int diameter;

    img_pyr_t *a_imgpyr, *b_imgpyr;

#if 1
    double tmin = 0, tmax = 1.0;
    int i, steps = 32;
#else
    double tmin = 0.5, tmax = 0.5;
    int i, steps = 1;
#endif

    img_dist_pyr_t *apyr, *bpyr;

    if (argc != 8) {
        printf("Usage: morphimg2 <zweight> <diameter> <in1.bmp> <in2.bmp> <in1.pyr> <in2.pyr> <out.bmp>\n");
        return 1;
    }

    zweight = atof(argv[1]);
    diameter = atoi(argv[2]);

#if 0
    /* Read the first bitmap */
    f = fopen(argv[3], "r");
    if (f == NULL) {
        printf("Could not open file %s for reading\n", argv[3]);
        return 1;
    }
    b1 = read_bmp(f);
    fclose(f);
    
    /* Read the second bitmap */
    f = fopen(argv[4], "r");
    if (f == NULL) {
        printf("Could not open file %s for reading\n", argv[4]);
        return 1;
    }
    b2 = read_bmp(f);
    fclose(f);

    /* Convert the bitmaps to images */
    if (b1 == NULL || b2 == NULL) {
        printf("Error reading bitmaps\n");
        return 1;
    }

    i1 = bmp2img(b1), i2 = bmp2img(b2);
    
    if (i1 == NULL || i2 == NULL) {
        printf("Error in bmp2img conversion\n");
        return 1;
    }
#endif

    i1 = img_read_bmp_file(argv[3]);
    i2 = img_read_bmp_file(argv[4]);

    /* Read the first map */
    f = open_file(argv[5], "r");
    apyr = img_read_distance_pyramid(f);
    fclose(f);
    
    /* Read the second map */
    f = open_file(argv[6], "r");
    bpyr = img_read_distance_pyramid(f);
    fclose(f);

    set_ann_z_weight(zweight);

    a_imgpyr = img_create_gaussian_pyramid(i1, 0);
    b_imgpyr = img_create_gaussian_pyramid(i2, 0);

#if 1
    m = img_morph3(i1, i2, diameter, &(apyr->dmaps[0]), &(bpyr->dmaps[0]), zweight, 1, tmin, tmax, steps);

    for (i = 0; i < steps; i++) {
	char outfile[64];

#if 0
	bout = img2bmp(m[i]);
    
	if (bout == NULL) {
	    printf("Error in img2bmp conversion\n");
	    return 1;
	}
#endif

	sprintf(outfile, "%s%03d.bmp", argv[7], i);

	f = fopen(outfile, "w");
	if (f == NULL) {
	    printf("Error opening %s for writing\n", outfile);
	    return 1;
	}
	    
	// write_bmp(f, bout);
	// fclose(f);
        img_write_bmp_file(m[i], outfile);

	// free_bmp(bout);
    }
#else
    iout = img_morph(i1, i2);
    bout = img2bmp(iout);
    
    if (bout == NULL) {
	printf("Error in img2bmp conversion\n");
	return 1;
    }

    f = fopen(argv[7], "w");
    if (f == NULL) {
	printf("Error opening %s for writing\n", argv[7]);
	return 1;
    }

    write_bmp(f, bout);
    fclose(f);
    
    free_bmp(bout);
#endif

    // free_bmp(b1);
    // free_bmp(b2);
    img_free(i1);
    img_free(i2);

    return 0;
}
Пример #23
0
int main(int argc, char **argv) {
  cl_int status;

  const char *platform_name = "NVIDIA";

  if (!find_platform(platform_name, &platform)) {
    fprintf(stderr,"Error: Platform \"%s\" not found\n", platform_name);
    print_platforms();
    teardown(-1);
  }

  status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL);
  checkError (status, "Error: could not query devices");

  context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
  checkError(status, "could not create context");

  const char name[] = KERNELDIR "/gauss.cl";

  unsigned char *source;
  size_t size;
  if (!load_file(name, &source, &size)) {
    teardown(-1);
  }

  program = clCreateProgramWithSource(context, 1, (const char **) &source, &size, &status);
  checkError(status, "Error: failed to create program %s: ", name);

  status = clBuildProgram(program, 1, &device, "-I.", NULL, NULL);
  if (status != CL_SUCCESS) {
    print_build_log(program, device);
    checkError(status, "Error: failed to create build %s: ", name);
  }

  free(source);

  print_device_info(device, 0);

  queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &status);
  checkError(status, "could not create command queue");

  cl_ulong start, end;
  cl_event event;

  unsigned char *data;
  size_t datasize;

  if (!load_file("lena.dat", &data, &datasize)) {
    teardown(-1);
  }

  size_t width  = 512;
  size_t height = 512;
  size_t buf_size = width*height*sizeof(cl_float);

  float *data_out = malloc(buf_size);
  if (!data_out) {
    fprintf(stderr,"\nError: malloc failed\n");
    teardown(-1);
  }

  kernel = clCreateKernel(program, "gauss", &status);
  checkError(status, "could not create kernel");

  cl_image_format format = { CL_R, CL_UNORM_INT8};
  buffer_in = clCreateImage2D (context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, &format,
    width, height, 0,
    data,
    &status);
  checkError(status, "Error: could not create image");

  buffer_out = clCreateBuffer(context, CL_MEM_READ_WRITE, buf_size, NULL, &status);
  checkError(status, "Error: could not create buffer_out");

  // execute kernel
  int arg = 0;
  status  = clSetKernelArg(kernel, arg++, sizeof(cl_mem), &buffer_in);
  status  = clSetKernelArg(kernel, arg++, sizeof(cl_mem), &buffer_out);
  checkError(status, "Error: could not set args");

  size_t work_size[] = {width, height};
  size_t local_size[] = {1, 1};

  status = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, work_size, local_size, 0, NULL, &event);
  checkError(status, "Error: could not enqueue kernel");

  status = clWaitForEvents(1, &event);
  checkError(status, "Error: could not wait for event");

  status  = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
  checkError(status, "Error: could not get start profile information");

  status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);
  checkError(status, "Error: could not get end profile information");

  status = clReleaseEvent(event);
  checkError(status, "Error: could not release event");

  // read results back
  status = clEnqueueReadBuffer(queue, buffer_out, CL_FALSE, 0, buf_size, data_out, 0, NULL, NULL);
  checkError(status, "Error: could not copy data into device");

  status  = clFinish(queue);
  checkError(status, "Error: could not finish successfully");

  double elapsed = (end - start) * 1e-9f;
  printf("time: %f\n", elapsed);

  write_bmp("gauss.bmp", data_out, width, height, NORMAL);

  free(data);
  free(data_out);
  teardown(0);
}
Пример #24
0
		std::ostream& operator<<(std::ostream& os, const BMP<DIB, I, D>& bmp)
		{
			write_bmp(bmp, os);
			return os;
		}
Пример #25
0
int main (int argc, char **argv) {
    // Reading command line arguments
    iterations = 100;
    imageSize = 512;
    if(argc == 3){
        iterations = atoi(argv[1]);
        imageSize = atoi(argv[2]);
    }

    // MPI initialization, getting rank and size
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // Creating cartesian communicator
    MPI_Dims_create(size, 2, dims);
    MPI_Cart_create( MPI_COMM_WORLD, 2, dims, periods, 0, &cart_comm );
    MPI_Cart_coords( cart_comm, rank, 2, coords );

    // Finding neighbours processes
    MPI_Cart_shift(cart_comm, 0, 1, &north, &south);
    MPI_Cart_shift(cart_comm, 1, 1, &west, &east);


    // Determining size of local subdomain
    local_height = imageSize/dims[0];
    local_width = imageSize/dims[1];

    // Creating and commiting MPI datatypes for message passing
    create_types();

    // Allocating memory for local arrays
    local_pres = (float*)malloc(sizeof(float)*(local_width + 2*border)*(local_height+2*border));
    local_pres0 = (float*)malloc(sizeof(float)*(local_width + 2*border)*(local_height+2*border));
    local_diverg = (float*)malloc(sizeof(float)*local_width*local_height);

    // Initializing the CFD computation, only one process should do this.
    if(rank == 0){
        initFluid( &config, imageSize, imageSize);
        pres = config.pres;
        diverg = config.div;

        imageBuffer = (unsigned char*)malloc(sizeof(unsigned char)*imageSize*imageSize);
    }

    // Solving the CFD equations, one iteration for each timestep.
    // These are not the same iterations used in the Jacobi solver.
    // The solveFluid function call the Jacobi solver, wich runs for 
    // 100 iterations for each of these iterations.
    for(int i = 0; i < iterations; i++){
        solveFluid(&config);
    }

    // Converting the density to an image and writing it to file.
    if(rank == 0){
        densityToColor(imageBuffer, config.dens, config.N);
        write_bmp(imageBuffer, imageSize, imageSize);

        // Free fluid simulation memory
        freeFluid( &config );
    }
    
    // Finalize
    MPI_Finalize();
}
Пример #26
0
int main(int argc, char** argv){

  if(argc != 3){
    printf("Useage: %s image n_threads\n", argv[0]);
    exit(-1);
  }
  int n_threads = atoi(argv[2]);
  pthread_t threads[n_threads];

  unsigned char* image = read_bmp(argv[1]);
  unsigned char* output_image = malloc(sizeof(unsigned char) * image_size);


  int* histogram = (int*)calloc(sizeof(int), color_depth);
  int** histograms = (int**)malloc(sizeof(int*)*n_threads);
  // This for loop have very few iterations so I will not parallelize it (the overhead is greater than the gain)
  for(int i=0;i<n_threads;i++) {
    histograms[i] = (int*)calloc(sizeof(int), color_depth);
  }
  //For each pixel, increment the correct cell in the local histogram
  for(int thread = 0; thread<n_threads; thread++) {
    histogram_count_args* a = malloc(sizeof(histogram_count_args));
    a->n_threads = n_threads;
    a->thread_n = thread;
    a->histograms = histograms;
    a->image = image;
    pthread_create(&threads[thread], NULL, threaded_histogram_count, (void *)a);
  }
  for(int i = 0; i < n_threads; i++) pthread_join(threads[i], NULL); // Wait for all threads to finish
  // For each cell in the local histogram, add it to the global histogram
  // For the color depths used in these example images, paralellizing this is not that usefull,
  // For images with larger color depth however, it's quite usefull.
  for(int thread = 0; thread<n_threads; thread++) {
    histogram_sum_args* a = malloc(sizeof(histogram_sum_args));
    a->n_threads = n_threads;
    a->thread_n = thread;
    a->histogram = histogram;
    a->histograms = histograms;
    pthread_create(&threads[thread], NULL, threaded_histogram_sum, (void *)a);
  }
  for(int i = 0; i < n_threads; i++) pthread_join(threads[i], NULL); // Wait for all threads to finish
  for(int i=0;i<color_depth;i++) {
  }
  
  
  
  float* transfer_function = (float*)calloc(sizeof(float), color_depth);
  for(int thread = 0; thread<n_threads; thread++) {
    transfer_args* a = malloc(sizeof(transfer_args));
    a->n_threads = n_threads;
    a->thread_n = thread;
    a->transfer_function = transfer_function;
    a->histogram = histogram;

    pthread_create(&threads[thread], NULL, threaded_transfer, (void *)a);
  }



  for(int i = 0; i < n_threads; i++) pthread_join(threads[i], NULL); // Wait for all threads to finish

  for(int i = 0; i < image_size; i++){
    output_image[i] = transfer_function[image[i]];
  }

  write_bmp(output_image, image_width, image_height);


  // A little code snippet to compare the result to a correct.bmp image.
  // This is here just for testing.
  unsigned char* fasit = read_bmp("correct.bmp");
  int no_errors = 1;
  for(int i=0;i<image_size;i++) {
    if(!(output_image[i] == fasit[i]
          || output_image[i]+1 == fasit[i]
          || output_image[i]-1 == fasit[i])) {
      no_errors = 0;
    }
  }
  printf("Correct: %d\n", no_errors);
}