Exemple #1
0
int main() {
  unsigned char rgb_buf[WIDTH*HEIGHT*3];
  float hsv_buf[WIDTH*HEIGHT*3];
  char *filename_in;
  char *filename_out;
  float f1, f2, f3, f4;
  FILE *fp;
  int i;
  
  filename_in = "testdata/pixbuff_7.ppm";
  filename_out = "testdata/pixbuff_7_hsv.txt";
  read_ppm(rgb_buf, filename_in);
  rgb2hsv(rgb_buf, hsv_buf);
  // verify sample hsv values
  f1 = hsv_buf[ind3(0, 0, 0)];
  f2 = hsv_buf[ind3(0, 0, 1)];
  f3 = hsv_buf[ind3(0, 0, 2)];
  f4 = hsv_buf[ind3(1, 1, 0)];

  printf("should be 53, 23, 40, 53\n");
  printf("%f %f %f %f\n", f1*360, f2*100, f3*100, f4*360);
  printf("Writing buffer for verification...\n");
  
  fp = fopen(filename_out, "w");
  for (i=0; i<WIDTH*HEIGHT*3; i++) {
    fprintf(fp, "%f\n", hsv_buf[i]);
  }
  fclose(fp);
  return 0;
}
Exemple #2
0
int main (int argc, char * argv[]){
    char * path = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/input0.ppm";
    char * path_csv = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/input1.csv";
    char * path_out = "/Users/neo_cupid/Desktop/18645/final_proj/data-2/1/outTest.ppm";
    clock_t begin, end;
    double time_spent;
    
    begin = clock();
    
    PPM_IMG img = read_ppm (path);
    PPM_IMG output;
    output.h = img.h;
    output.w = img.w;
    output.data = (unsigned char *)malloc(3 * img.w * img.h * sizeof(unsigned char));
    float mask[25];
    read_csv(path_csv, mask);
    convolution(CHANNELS, img.w, img.h, mask, img, &output);
    write_ppm(output, path_out);
    free (output.data);
    free(img.data);
    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("execution time: %lf.\n",time_spent);
    return 0;
    
}
Exemple #3
0
int read_dcraw(const char *filename, uint8_t **memptr, size_t *memsize, int *n_axis, int *w, int *h, int *bitsperpixel)
{
	struct dcraw_header header;
	FILE *handle = NULL;
	char *cmd;

    if (dcraw_parse_header_info(filename, &header)  || ! header.width  || ! header.height)
	{
        DEBUGDEVICE(device, INDI::Logger::DBG_DEBUG, "read_file_from_dcraw: failed to parse header");
        return -1;
	}

    DEBUGFDEVICE(device, INDI::Logger::DBG_DEBUG, "Reading exposure %d x %d", header.width, header.height);
    asprintf(&cmd, "%s -c -t 0 -4 -D %s", dcraw_cmd, filename);

    DEBUGFDEVICE(device, INDI::Logger::DBG_DEBUG, "%s", cmd);

	handle = popen(cmd, "r");
	free(cmd);
    if (handle == NULL)
    {
        DEBUGDEVICE(device, INDI::Logger::DBG_DEBUG, "read_file_from_dcraw: failed to run dcraw");
        return -1;
	}

    int rc= read_ppm(handle, &header, memptr, memsize, n_axis, w, h, bitsperpixel);

    pclose(handle);

    return rc;
}
Matrix<Color> read_img(std::string filename)
{
    std::size_t n = filename.size();
    std::string extension3 = filename.substr(n-3, n);
    std::string extension4 = filename.substr(n-4, n);
    if(!extension3.compare("bmp"))
    {
        return read_bmp(filename);
    }
    else if(!extension3.compare("gif"))
    {
        return read_gif(filename);
    }
    else if(!extension3.compare("ico"))
    {
        return read_ico(filename);
    }
    /*else if(!extension3.compare("jpg"))
    {
        return read_jpeg(filename);
    }*/
    else if(!extension3.compare("pcx"))
    {
        return read_pcx(filename);
    }
    else if(!extension3.compare("png"))
    {
        return read_png(filename);
    }
    else if(!extension3.compare("pbm"))
    {
        return bw2colorimage(read_pbm(filename));
    }
    else if(!extension3.compare("pgm"))
    {
        return gray2colorimage(read_pgm(filename));
    }
    else if(!extension3.compare("ppm"))
    {
        return read_ppm(filename);
    }
    else if(!extension3.compare("tga"))
    {
        return read_tga(filename);
    }
    else if(!extension4.compare("tiff"))
    {
        return read_tiff(filename);
    }
    else
    {
        return Matrix<Color>();
    }
}
Exemple #5
0
int main()
{
  image_t *img = read_ppm("example.ppm");
  if (!img)
    return EXIT_FAILURE;
  for (size_t i = 0; i<img->width*img->height; ++i)
  {
    img->red_buffer[i] = 255-img->green_buffer[i];
  }
  write_ppm("example-out.ppm", img);
  return EXIT_SUCCESS;
}
Exemple #6
0
void Heightfield::load( char* filename )	{

	clear();
	defaults();
	
#if 0
	_header = new BITMAPINFOHEADER();
	_imageData = LoadBitmapFile( filename, _header );
#else
	_imageData = read_ppm( filename );
#endif
	if( _imageData )	{
		initializeTerrain( _imageData );
	}
}
Exemple #7
0
int main() {
  unsigned char buf[WIDTH*HEIGHT*3];
  char *filename_in;
  char *filename_out;
  filename_in = "testdata/pixbuff_7.ppm";
  filename_out = "testdata/blurtest.ppm";
  read_ppm(buf, filename_in);
  printf("These two sequences of numbers should be different.\n");
  printf("%d %d %d\n", buf[12], buf[13], buf[14]);
  gauss_blur(buf);
  printf("%d %d %d\n", buf[12], buf[13], buf[14]);
  write_ppm(buf, filename_out);
  printf("Confirm that the image testdata/blurtest.ppm is a blurred copy of image testdata/pixbuff_7.ppm\n");
  return 0;
}
Exemple #8
0
void gl_state_input (sprite_info_t Gl_array[]){

    int i,j,m;
    int type;
    int xcoord;
    int ycoord;

    for (i = 0; i < INPUT_STRUCT_LENGTH; i++){
        xcoord = Gl_array[i].x;
        ycoord = Gl_array[i].y;
        type = Gl_array[i].id;
        if(type == ESKIMO){
            read_ppm(50, xcoord, ycoord);
        }

    }
}
Exemple #9
0
int main(int argc, char* argv[]) {
    framebuffer_t* fb;
    img32_t* img;
    
    // check for proper usage
    if(argc == 1) {
	fprintf(stderr, "Usage: %s lena.ppm\n", argv[0]);
	return EX_USAGE;
    }
    
    // initialize the framebuffer (with single buffering)
    fprintf(stderr, "Starting up...\n");
    if((fb = fb_open(0x11e, 0, 0)) == NULL) {
	perror("fb_open");
	return EX_UNAVAILABLE;
    }

    // clear the screen in a shade of blue
    cls(fb, 0x00007F);

    // pause
    getc(stdin);

    // load the image
    img = read_ppm(argv[1]);
    
    // clear the screen in a shade of red
    cls(fb, 0x7F0000);

    // display the image centered
    blit(fb, img, fb->info.vi_width / 2 - img->w / 2, fb->info.vi_height / 2 - img->h / 2);
    
    // free the image
    free(img);

    // pause for dramatic effect...
    getc(stdin);
    
    // tidy up
    fprintf(stderr, "Shutting down...\n");
    fb_close(fb);
    return EX_OK;
}
Exemple #10
0
int initialize_font()
{
	ppm_t* fonts = (ppm_t*) read_ppm(get_dir("/ppms/font.ppm"),get_dir("/ppms/font.ppm"));
	if(fonts == NULL) return 1;
	size_t i,n;
	int xi, xf, yi, yf;
	for(i = 0; i <= FONT_END - FONT_START; i++)
	{
		initialize_single_char(i, fonts);
	}
	for(n = 0; n < NUM_FONTSIZES-1; n++)
	{
		for(i = 0; i <= FONT_END - FONT_START; i++)
		{
			chars1[n][i] = (ppm_t *)reduce_float(chars1[NUM_FONTSIZES-1][i], (NUM_FONTSIZES - n) );
		}
	}
	delete_ppm_t(fonts);
	return 0;
}
Exemple #11
0
int main()
{
    PPM_IMG img_ibuf_c;

    printf("Running colour space converter .\n");
    img_ibuf_c = read_ppm("in.ppm");
    copy_image(img_ibuf_c);
    run_cpu_color_test(img_ibuf_c);
    run_gpu_color_test(img_ibuf_c);
    printf("GPU and CPU conversion on RGB to YUV: %s\n", confirm_gpu_rgb2yuv() ? "true" : "false");
    printf("GPU and CPU conversion on YUV to RGB: %s\n", confirm_gpu_yuv2rgb() ? "true" : "false");

    free_ppm(img_ibuf_c);

    free_ppm(img_obuf_rgb_cpu);
    free_yuv(img_obuf_yuv_cpu);
    free_ppm(img_obuf_rgb_gpu);
    free_yuv(img_obuf_yuv_gpu);

    return 0;
}
Exemple #12
0
void read_image(void)
{
    G_debug(1, "read_image");

    if (!cairo || !surface)
	return;

    if (file_type == FTYPE_PPM) {
	G_debug(1, "Reading image from %s", file_name);
	read_ppm();
    }
    else if (file_type == FTYPE_BMP) {
	G_debug(1, "Reading image from %s", file_name);
	read_bmp();
    }
#if CAIRO_HAS_PNG_FUNCTIONS
    else if (file_type == FTYPE_PNG) {
	cairo_surface_t *img_surf;

	G_debug(1, "Reading image from %s", file_name);

	img_surf = cairo_image_surface_create_from_png(file_name);
	if (!img_surf)
	    return;

	cairo_save(cairo);
	cairo_set_source_surface(cairo, img_surf, 0, 0);
	cairo_paint(cairo);
	cairo_restore(cairo);

	cairo_surface_destroy(img_surf);
    }
#endif
    /* vector format files are written directly to file */

    modified = 0;
}
/* simulate processing for one complete frame cycle */
int main(int argc, char* argv[]) {
  
  unsigned char rgb_buf[WIDTH*HEIGHT*3];
  float hsv_buf[WIDTH*HEIGHT*3];
  unsigned char mask_buf[WIDTH*HEIGHT];
  int mass, x, y;
  
  if (argc < 2) {
    printf("Usage: exe filename.ppm\n");
    return 1;
  }

  // read frame
  read_ppm(rgb_buf, argv[1]);
  // blur
  gauss_blur(rgb_buf);
  // convert to hue, saturation, value
  rgb2hsv(rgb_buf, hsv_buf);
  // convert to mask with orange threshold 
  orange_thresh(hsv_buf, mask_buf);
  // apply 3x3 median filter
  median_filter(mask_buf);
  // compute mass and centroid
  mass = centroid(mask_buf, &x, &y);
  printf("Mass: %d; ", mass);
  if (mass) {
    printf("Centroid: (%d, %d)\n", x, y);
  } else {
    printf("No centroid\n");
  }
  // output mask for verification
  write_ppm1(mask_buf, "testdata/full_frame_test.ppm");
  printf("Wrote mask to 'testdata/full_frame_test.ppm' for verification.\n");

  return 0;
}
/* this is the plugin entry point */
enum plugin_status plugin_start(const void* parameter)
{
    static char filename[MAX_PATH];
    int fd;

    int cols; 
    int rows; 
    int maxval; 
   
    int result;
    
    struct bitmap small_bitmap, orig_bitmap;
    
    if(!parameter) return PLUGIN_ERROR;

    size_t buffer_size;
    char *audiobuf = rb->plugin_get_buffer(&buffer_size);
    if (buffer_size < PPM_MAXSIZE + LCD_WIDTH * LCD_HEIGHT + 1)
    {
        /* steal from audiobuffer if plugin buffer is too small */
        audiobuf = rb->plugin_get_audio_buffer(&buffer_size);

        if (buffer_size < PPM_MAXSIZE + LCD_WIDTH * LCD_HEIGHT + 1)
        {
            rb->splash(HZ, "Not enough memory");
            return PLUGIN_ERROR;
        }
    }

    /* align on 16 bits */
    audiobuf = (char *)(((uintptr_t)audiobuf + 1) & ~1);
    buffer = (fb_data *)audiobuf;
    lcd_buf = (fb_data*) (audiobuf + PPM_MAXSIZE);

    rb->strcpy(filename, parameter);
    
    fd = rb->open(filename, O_RDONLY);
    if (fd < 0)
    {
        ppm_error("Couldnt open file: %s, %d", filename, fd);
        return PLUGIN_ERROR;
    }

    result = read_ppm(fd, &cols, &rows, &maxval);

    rb->close(fd);
    if(result == PLUGIN_ERROR) return PLUGIN_ERROR;

    orig_bitmap.width = cols;
    orig_bitmap.height = rows;
    orig_bitmap.data = (char*)buffer;
    
    if (cols > LCD_WIDTH || rows > LCD_HEIGHT)
    {
        if (cols > LCD_WIDTH) {
            small_bitmap.width = LCD_WIDTH;
            small_bitmap.height = 
                (int)(((float)LCD_WIDTH / (float)cols) * (float)rows);
            
        } else { /* rows > LCD_HEIGHT */
            
            small_bitmap.width = 
                (int)(((float)LCD_HEIGHT / (float)rows) * (float)cols);
            small_bitmap.height = LCD_HEIGHT;            
        } 
        small_bitmap.data = (char*)lcd_buf;

        smooth_resize_bitmap( &orig_bitmap, &small_bitmap );
        
        rb->lcd_bitmap((fb_data*)small_bitmap.data, 0, 0,
                       small_bitmap.width, small_bitmap.height);
    } else {
        rb->lcd_bitmap((fb_data*)orig_bitmap.data, 0, 0, cols, rows);   
    }
    rb->lcd_update();
    rb->button_get(true);
    
    return PLUGIN_OK;
}
int thresmain(int argc, char *argv[]) {
	int thread_count;
	int xsize, ysize, colmax;
	pixel * src;
	pixel * dst;
	imagethread * imageThreads;
	thresfilterdata * thresdata;
	pthread_mutex_t thresholdsum_mutex = PTHREAD_MUTEX_INITIALIZER;
	unsigned int thresholdsum = 0;
	int i;
	char * inputFilepath;
	char * outputFilepath;
	struct timespec stime, etime;

	src = allocate_image(MAX_PIXELS);
	dst = allocate_image(MAX_PIXELS);

	/* Take care of the arguments */

	if (argc != 4) {
		fprintf(stderr, "Usage: %s thread_count infile outfile\n", argv[0]);
		return 1;
	}

	thread_count = atoi(argv[1]);
	if(thread_count < 1){
		fprintf(stderr, "Too few threads\n");
		return 1;
	}

	inputFilepath = strdup(argv[2]);
	outputFilepath = strdup(argv[3]);

	/* read file */
	if(read_ppm (inputFilepath, &xsize, &ysize, &colmax, (char *) src) != 0)
		return 1;

	if (colmax > 255) {
		fprintf(stderr, "Too large maximum color-component value\n");
		return 1;
	}

	printf("Creating threads\n");
	imageThreads = createThreadData(thread_count);

	printf("Dividing image\n");
	divide(imageThreads, thread_count, src, dst, xsize, ysize);
	printf("\n");

	printf("Setting arguments\n");
	thresdata = (thresfilterdata*) malloc(sizeof(thresfilterdata) * thread_count);
	for(i = 0; i < thread_count; i++){
		thresdata[i].xsize = xsize;
		thresdata[i].ysize = ysize;
		thresdata[i].src = src;
		thresdata[i].dst = dst;
		thresdata[i].thresholdsum = &thresholdsum;
		thresdata[i].imageThreads = imageThreads;
		thresdata[i].rank = i;
		thresdata[i].thresholdsum_mutex = &thresholdsum_mutex;
	}

	clock_gettime(CLOCK_REALTIME, &stime);
	printf("Starting threads\n");
	setThreadSyncCount(thread_count);
	for(i = 0; i < thread_count; i++){
		//printf("Starting thread %d\n", i);
		imageThreads[i].argument = &thresdata[i];
		imageThreads[i].thread = createThread(thresfilterwrapper, imageThreads[i].argument);
	}

	printf("Threads working on average value\n");
	SynchronizationPoint();
	printf("Average value is %d\n", thresholdsum/(xsize*ysize));
	printf("Threads working on threshold\n");
	SynchronizationPoint();
	printf("Threads done\n");
	clock_gettime(CLOCK_REALTIME, &etime);

	printf("Filtering took: %g secs\n", (etime.tv_sec  - stime.tv_sec) +
		1e-9*(etime.tv_nsec  - stime.tv_nsec)) ;

	/* write result */
	printf("Writing output file\n");

	if(write_ppm (outputFilepath, xsize, ysize, (char *)src) != 0){
		return 1;
	}

	return 0;
}
int sample_main(int argc, char *argv[]) {
    VkResult U_ASSERT_ONLY res;
    bool U_ASSERT_ONLY pass;
    struct sample_info info = {};
    char sample_title[] = "Texture Initialization Sample";

    init_global_layer_properties(info);
    init_instance_extension_names(info);
    init_device_extension_names(info);
    init_instance(info, sample_title);
    init_enumerate_device(info);
    init_connection(info);
    init_window_size(info, 50, 50);
    init_window(info);
    init_swapchain_extension(info);
    init_device(info);
    init_command_pool(info);
    init_command_buffer(info);
    execute_begin_command_buffer(info);
    init_device_queue(info);

    /* VULKAN_KEY_START */
    /*
     * Set up textures:
     * - Create a linear tiled image
     * - Map it and write the texture data into it
     * - If linear images cannot be used as textures, create an optimally
     *       tiled image and blit from the linearly tiled image to the optimally
     *       tiled image
     * -
     * -
     * -
     */

    struct texture_object texObj;
    std::string filename = get_base_data_dir();
    filename.append("lunarg.ppm");
    if (!read_ppm(filename.c_str(), texObj.tex_width, texObj.tex_height, 0,
                  NULL)) {
        std::cout << "Could not read texture file lunarg.ppm\n";
        exit(-1);
    }

    VkFormatProperties formatProps;
    vkGetPhysicalDeviceFormatProperties(info.gpus[0], VK_FORMAT_R8G8B8A8_UNORM,
                                        &formatProps);

    /* See if we can use a linear tiled image for a texture, if not, we will
     * need a staging image for the texture data */
    bool needStaging = (!(formatProps.linearTilingFeatures &
                          VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
                           ? true
                           : false;

    VkImageCreateInfo image_create_info = {};
    image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
    image_create_info.pNext = NULL;
    image_create_info.imageType = VK_IMAGE_TYPE_2D;
    image_create_info.format = VK_FORMAT_R8G8B8A8_UNORM;
    image_create_info.extent.width = texObj.tex_width;
    image_create_info.extent.height = texObj.tex_height;
    image_create_info.extent.depth = 1;
    image_create_info.mipLevels = 1;
    image_create_info.arrayLayers = 1;
    image_create_info.samples = NUM_SAMPLES;
    image_create_info.tiling = VK_IMAGE_TILING_LINEAR;
    image_create_info.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
    image_create_info.usage = needStaging ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT
                                          : VK_IMAGE_USAGE_SAMPLED_BIT;
    image_create_info.queueFamilyIndexCount = 0;
    image_create_info.pQueueFamilyIndices = NULL;
    image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
    image_create_info.flags = 0;

    VkMemoryAllocateInfo mem_alloc = {};
    mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    mem_alloc.pNext = NULL;
    mem_alloc.allocationSize = 0;
    mem_alloc.memoryTypeIndex = 0;

    VkImage mappableImage;
    VkDeviceMemory mappableMemory;

    VkMemoryRequirements mem_reqs;

    /* Create a mappable image.  It will be the texture if linear images are ok
     * to be textures or it will be the staging image if they are not.
     */
    res = vkCreateImage(info.device, &image_create_info, NULL, &mappableImage);
    assert(res == VK_SUCCESS);

    vkGetImageMemoryRequirements(info.device, mappableImage, &mem_reqs);

    mem_alloc.allocationSize = mem_reqs.size;

    /* Find the memory type that is host mappable */
    pass = memory_type_from_properties(info, mem_reqs.memoryTypeBits,
                                       VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
                                       &mem_alloc.memoryTypeIndex);
    assert(pass);

    /* allocate memory */
    res = vkAllocateMemory(info.device, &mem_alloc, NULL, &(mappableMemory));
    assert(res == VK_SUCCESS);

    /* bind memory */
    res = vkBindImageMemory(info.device, mappableImage, mappableMemory, 0);
    assert(res == VK_SUCCESS);

    VkImageSubresource subres = {};
    subres.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
    subres.mipLevel = 0;
    subres.arrayLayer = 0;

    VkSubresourceLayout layout;
    void *data;

    /* Get the subresource layout so we know what the row pitch is */
    vkGetImageSubresourceLayout(info.device, mappableImage, &subres, &layout);

    res = vkMapMemory(info.device, mappableMemory, 0, mem_reqs.size, 0, &data);
    assert(res == VK_SUCCESS);

    /* Read the ppm file into the mappable image's memory */
    if (!read_ppm(filename.c_str(), texObj.tex_width, texObj.tex_height,
                  layout.rowPitch, (unsigned char *)data)) {
        std::cout << "Could not load texture file lunarg.ppm\n";
        exit(-1);
    }

    vkUnmapMemory(info.device, mappableMemory);

    if (!needStaging) {
        /* If we can use the linear tiled image as a texture, just do it */
        texObj.image = mappableImage;
        texObj.mem = mappableMemory;
        texObj.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
        set_image_layout(info, texObj.image, VK_IMAGE_ASPECT_COLOR_BIT,
                         VK_IMAGE_LAYOUT_PREINITIALIZED, texObj.imageLayout);
    } else {
        /* The mappable image cannot be our texture, so create an optimally
         * tiled image and blit to it */
        image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL;
        image_create_info.usage =
            VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
        image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;

        res =
            vkCreateImage(info.device, &image_create_info, NULL, &texObj.image);
        assert(res == VK_SUCCESS);

        vkGetImageMemoryRequirements(info.device, texObj.image, &mem_reqs);

        mem_alloc.allocationSize = mem_reqs.size;

        /* Find memory type - don't specify any mapping requirements */
        pass = memory_type_from_properties(info, mem_reqs.memoryTypeBits, 0,
                                           &mem_alloc.memoryTypeIndex);
        assert(pass);

        /* allocate memory */
        res = vkAllocateMemory(info.device, &mem_alloc, NULL, &texObj.mem);
        assert(res == VK_SUCCESS);

        /* bind memory */
        res = vkBindImageMemory(info.device, texObj.image, texObj.mem, 0);
        assert(res == VK_SUCCESS);

        /* Since we're going to blit from the mappable image, set its layout to
         * SOURCE_OPTIMAL */
        /* Side effect is that this will create info.cmd */
        set_image_layout(info, mappableImage, VK_IMAGE_ASPECT_COLOR_BIT,
                         VK_IMAGE_LAYOUT_PREINITIALIZED,
                         VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);

        /* Since we're going to blit to the texture image, set its layout to
         * DESTINATION_OPTIMAL */
        set_image_layout(info, texObj.image, VK_IMAGE_ASPECT_COLOR_BIT,
                         VK_IMAGE_LAYOUT_UNDEFINED,
                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

        VkImageCopy copy_region;
        copy_region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
        copy_region.srcSubresource.mipLevel = 0;
        copy_region.srcSubresource.baseArrayLayer = 0;
        copy_region.srcSubresource.layerCount = 1;
        copy_region.srcOffset.x = 0;
        copy_region.srcOffset.y = 0;
        copy_region.srcOffset.z = 0;
        copy_region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
        copy_region.dstSubresource.mipLevel = 0;
        copy_region.dstSubresource.baseArrayLayer = 0;
        copy_region.dstSubresource.layerCount = 1;
        copy_region.dstOffset.x = 0;
        copy_region.dstOffset.y = 0;
        copy_region.dstOffset.z = 0;
        copy_region.extent.width = texObj.tex_width;
        copy_region.extent.height = texObj.tex_height;
        copy_region.extent.depth = 1;

        /* Put the copy command into the command buffer */
        vkCmdCopyImage(info.cmd, mappableImage,
                       VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, texObj.image,
                       VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);

        /* Set the layout for the texture image from DESTINATION_OPTIMAL to
         * SHADER_READ_ONLY */
        texObj.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
        set_image_layout(info, texObj.image, VK_IMAGE_ASPECT_COLOR_BIT,
                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
                         texObj.imageLayout);
    }
    execute_end_command_buffer(info);
    execute_queue_command_buffer(info);

    VkSamplerCreateInfo samplerCreateInfo = {};
    samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
    samplerCreateInfo.magFilter = VK_FILTER_NEAREST;
    samplerCreateInfo.minFilter = VK_FILTER_NEAREST;
    samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
    samplerCreateInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
    samplerCreateInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
    samplerCreateInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
    samplerCreateInfo.mipLodBias = 0.0;
    samplerCreateInfo.anisotropyEnable = VK_FALSE,
    samplerCreateInfo.maxAnisotropy = 0;
    samplerCreateInfo.compareEnable = VK_FALSE;
    samplerCreateInfo.compareOp = VK_COMPARE_OP_NEVER;
    samplerCreateInfo.minLod = 0.0;
    samplerCreateInfo.maxLod = 0.0;
    samplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;

    /* create sampler */
    res =
        vkCreateSampler(info.device, &samplerCreateInfo, NULL, &texObj.sampler);
    assert(res == VK_SUCCESS);

    VkImageViewCreateInfo view_info = {};
    view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
    view_info.pNext = NULL;
    view_info.image = VK_NULL_HANDLE;
    view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
    view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
    view_info.components.r = VK_COMPONENT_SWIZZLE_R;
    view_info.components.g = VK_COMPONENT_SWIZZLE_G;
    view_info.components.b = VK_COMPONENT_SWIZZLE_B;
    view_info.components.a = VK_COMPONENT_SWIZZLE_A;
    view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
    view_info.subresourceRange.baseMipLevel = 0;
    view_info.subresourceRange.levelCount = 1;
    view_info.subresourceRange.baseArrayLayer = 0;
    view_info.subresourceRange.layerCount = 1;

    /* create image view */
    view_info.image = texObj.image;
    res = vkCreateImageView(info.device, &view_info, NULL, &texObj.view);
    assert(res == VK_SUCCESS);

    info.textures.push_back(texObj);
    /* VULKAN_KEY_END */

    /* Clean Up */
    vkDestroySampler(info.device, texObj.sampler, NULL);
    vkDestroyImageView(info.device, texObj.view, NULL);
    vkDestroyImage(info.device, texObj.image, NULL);
    vkFreeMemory(info.device, texObj.mem, NULL);
    if (needStaging) {
        /* Release the resources for the staging image */
        vkFreeMemory(info.device, mappableMemory, NULL);
        vkDestroyImage(info.device, mappableImage, NULL);
    }
    destroy_command_buffer(info);
    destroy_command_pool(info);
    destroy_device(info);
    destroy_window(info);
    destroy_instance(info);
    return 0;
}
Exemple #17
0
int main (int argc, char ** argv) {
   int radius;
    int xsize, ysize, colmax;
    pixel src[MAX_PIXELS];
    struct timespec stime, etime;
	#define MAX_RAD 1000
	int np, me;
    double w[MAX_RAD];
	MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &np );
    MPI_Comm_rank( MPI_COMM_WORLD, &me );
    /* Take care of the arguments */

	if(me ==  MASTER){
		if (argc != 4) {
			fprintf(stderr, "Usage: %s radius infile outfile\n", argv[0]);
			exit(1);
		}
		radius = atoi(argv[1]);
		if((radius > MAX_RAD) || (radius < 1)) {
			fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\n", radius, MAX_RAD);
			exit(1);
		}
		/* read file */
		if(read_ppm (argv[2], &xsize, &ysize, &colmax, (char *) src) != 0)
			exit(1);

		if (colmax > 255) {
			fprintf(stderr, "Too large maximum color-component value\n");
			exit(1);
		}
		/* filter */
		get_gauss_weights(radius, w);
		
		printf("Has read the image and generated Coefficients\n");
	}
	// radius, common to everybody
    MPI_Bcast( &radius, 1, MPI_INT, 0, MPI_COMM_WORLD );
    // w, common to everybody
    MPI_Bcast( w, MAX_RAD, MPI_DOUBLE, 0, MPI_COMM_WORLD );
    //xsize, common to everybody
    MPI_Bcast( &xsize, 1, MPI_INT, 0, MPI_COMM_WORLD );
     //ysize, common to everybody
    MPI_Bcast( &ysize, 1, MPI_INT, 0, MPI_COMM_WORLD );
    
/* create a datatype for struct pixel */
    const int nitems=3;
    int          blocklengths[3] = {1,1,1};
    MPI_Datatype types[3] = {MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR};
    MPI_Datatype mpi_pixel_type;
    MPI_Aint     offsets[3];

    offsets[0] = 0;
    offsets[1] = 1;
	offsets[2] = 2;	
    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_pixel_type);
    MPI_Type_commit(&mpi_pixel_type);


 /* calculate areas to be computed by each processor */
 	int * sendcounts;
	int * displace;
	int * recvcounts;
	int * recvdisplace;
	int * rag;
	sendcounts = malloc(sizeof(int)*np);  
	recvcounts = malloc(sizeof(int)*np);  
	displace = malloc(sizeof(int)*np);
	recvdisplace = malloc(sizeof(int)*np);
	int original_radius;
	int line, rem, sum;
	sum= 0;
	rem = ysize % np;
	
	// calculate send counts and displacements
	int i;
	int pointer[np];
	if(np>1){
		line = (ysize/np);		
		original_radius = radius;
		
		for (i = 0; i < np; i++) {
			radius = original_radius;
			displace[i] = sum;
			recvdisplace[i] = displace[i];
			
			int line_rem = 0;
			if (rem > 0) {
				line_rem++;
				rem--;
			}
			
			line_rem+=line;
			recvcounts[i] = line_rem;			
			if(i == 0){
				if(displace[i]/xsize + line_rem + radius > ysize){
					radius = ysize - (displace[i]/xsize + line_rem);	
				}
				sendcounts[i] = line_rem+radius;				
				pointer[0] = 0;
			}else
			
			if(i == np-1){
				
				if(displace[i]/xsize - radius < 0){
					radius = displace[i]/xsize;
				}
				
				sendcounts[i] = line_rem + radius;
				displace[i] -= (radius*xsize);
				pointer[i] = radius*xsize;	
			
			}else
			if(i>0 && i<np-1){
				
				if(0 + displace[i]/xsize-radius < 0){
					radius = displace[i]/xsize - 0;
				}
				
				sendcounts[i] = line_rem + radius;
				int sofar = displace[i]/xsize;
				displace[i] -= (radius*xsize);
				pointer[i] = radius*xsize;

				radius = original_radius;
			
				if(sofar + line_rem + radius > ysize){
					radius = ysize - (sofar + line_rem);	
				}
				sendcounts[i] += radius;
							
			}
			
			sum += line_rem*xsize;
			sendcounts[i] *= xsize;						
			recvcounts[i] *= xsize;
			
			if(me == MASTER)
				printf("Process %d. \t Area to compute: %d . \t starting from: %d \t Displ recv: %d\n\n  ",
				 i, sendcounts[i], (displace[i]/xsize),(recvdisplace[i]/xsize));	
		}
	}else{
		sendcounts[0] = xsize*ysize;
		recvcounts[0] = xsize*ysize;
		displace[0] = 0;
		recvdisplace[0] = 0;
		pointer[0] = 0;
		rag[0] = ysize;

	}
	
    pixel buffer_receiver[sendcounts[me]];

	MPI_Scatterv( &src, sendcounts , displace, mpi_pixel_type , &buffer_receiver, sendcounts[me], mpi_pixel_type , 0, MPI_COMM_WORLD );
	
    clock_gettime(CLOCK_REALTIME, &stime);
	blurfilter(xsize, sendcounts[me]/xsize, buffer_receiver, original_radius, w);
	
	
	pixel * p ;
	p= &buffer_receiver[pointer[me]];


	MPI_Gatherv ( p, recvcounts[me], mpi_pixel_type, &src, recvcounts, recvdisplace, mpi_pixel_type, 0 , MPI_COMM_WORLD);
    clock_gettime(CLOCK_REALTIME, &etime);
    
    char filename[5];
	sprintf(filename, "file%d.ppm", me);
	
	if(me == MASTER){
		printf("Main Master Filtering took: %g secs\n", (etime.tv_sec  - stime.tv_sec) +
		   1e-9*(etime.tv_nsec  - stime.tv_nsec)) ;

		/* write result */
		printf("Writing output file\n");
		if(write_ppm (argv[3], xsize, ysize,  (char *)src) != 0)
			exit(1);
	 	printf("Image written on %s\n",argv[3]);

	}else{
			if (write_ppm (filename, xsize, recvcounts[me]/xsize, (char *)&buffer_receiver[pointer[me]]) != 0)
		 exit(1);
	}

    MPI_Finalize();
    return(0);
}
Exemple #18
0
int main (int argc, char ** argv) {
   int taskid, ntasks;

    int xsize, ysize, colmax;
    pixel src[MAX_PIXELS];
    double w[MAX_RAD];

    struct timespec stime, etime;
    struct timespec tstime, tetime;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
    MPI_Comm_size(MPI_COMM_WORLD, &ntasks);

    // Create a custom MPI datatype for pixel
    pixel item;
    MPI_Datatype pixel_mpi;
    MPI_Datatype type[3] = { MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR };
    int blocklen[] = { 1, 1, 1 };
    MPI_Aint start, disp[3];

    MPI_Address( &item, &start );
    MPI_Address( &item.r, &disp[0] );
    MPI_Address( &item.g, &disp[1] );
    MPI_Address( &item.b, &disp[2] );

    disp[0] -= start;
    disp[1] -= start;
    disp[2] -= start;

    MPI_Type_struct(3, blocklen, disp, type, &pixel_mpi);
    MPI_Type_commit(&pixel_mpi);

    int buffsize, radius, startY, endY;

    /* Take care of the arguments */
    if (argc != 4) {
        fprintf(stderr, "Usage: %s radius infile outfile\n", argv[0]);
        exit(1);
    }
    radius = atoi(argv[1]);
    if((radius > MAX_RAD) || (radius < 1)) {
        fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\n", radius, MAX_RAD);
        exit(1);
    }

    if (taskid == ROOT) {
        /* read file */
        if(read_ppm (argv[2], &xsize, &ysize, &colmax, (char *) src) != 0)
            exit(1);

        if (colmax > 255) {
            fprintf(stderr, "Too large maximum color-component value\n");
            exit(1);
        }

        /* filter */
        printf("Has read the image, generating coefficients\n");
        get_gauss_weights(radius, w);
    }

    // Broadcast the gaussian weight vector
    MPI_Bcast(w, MAX_RAD, MPI_DOUBLE, ROOT, MPI_COMM_WORLD);
    // Broadcast image dimensions
    MPI_Bcast(&xsize, 1, MPI_INT, ROOT, MPI_COMM_WORLD);
    MPI_Bcast(&ysize, 1, MPI_INT, ROOT, MPI_COMM_WORLD);

    // Calculate chunk size
    buffsize = ceil((float)ysize / (float)ntasks) * xsize;
    pixel recvbuff[MAX_PIXELS];

    int sendcnts[ntasks], displs[ntasks], result_write_starts[ntasks], recievecounts[ntasks];
    int i;
    // Generate sendcount and displacement vectors for Scatterv
    for (i = 0; i < ntasks; i++) {
        // Send enought neighbors to make it possible to also calculate
        // blur in the edges of the chunk
        sendcnts[i] = buffsize + 2 * radius * xsize;
        displs[i] = max(0, i * buffsize);
    }

    clock_gettime(CLOCK_REALTIME, &tstime);

    // Send the image in chunks to all nodes
    MPI_Scatterv(src, sendcnts, displs,
                 pixel_mpi, recvbuff, buffsize + 2 * radius * xsize,
                 pixel_mpi, ROOT, MPI_COMM_WORLD);

    clock_gettime(CLOCK_REALTIME, &stime);

    // Run the filter on the recieved chunk
    blurfilter(xsize, (ysize / ntasks) + 2 * radius, recvbuff, radius, w, taskid);

    clock_gettime(CLOCK_REALTIME, &etime);
    printf("Filtering at %i took: %g secs\n", taskid, (etime.tv_sec  - stime.tv_sec) +
        1e-9*(etime.tv_nsec  - stime.tv_nsec));

    // Generate sendcount and displacement vectors for Scatterv
    for (i = 0; i < ntasks; i++) {
        result_write_starts[i] = i * buffsize + xsize * radius;
        // Only send as much of the chunk that is really useful data
        recievecounts[i] = buffsize;
    }

    // Start writing from the beginning of the buffer if root
    result_write_starts[0] = 0;

    // Since the root node has no overlap in the beginning, we need to
    // send a little bit more from that node than from the rest.
    recievecounts[0] = buffsize + xsize * radius;

    pixel* result_read_start;
    if(taskid==ROOT) {
        // Root-node has no duplicated data in the beginning
        result_read_start = recvbuff;
    } else {
        // Jump over the duplicated data in the beginning of each chunk
        result_read_start = recvbuff + xsize * radius;
    }

    MPI_Gatherv(result_read_start, recievecounts[taskid], pixel_mpi,
                src, recievecounts, result_write_starts,
                pixel_mpi, ROOT, MPI_COMM_WORLD);

    clock_gettime(CLOCK_REALTIME, &tetime);

    MPI_Finalize();


    /* write result */
    if (taskid == ROOT) {
        printf("Everything took: %g secs\n", (tetime.tv_sec  - tstime.tv_sec) +
           1e-9*(tetime.tv_nsec  - tstime.tv_nsec));


        printf("Writing output file\n");

        if(write_ppm (argv[3], xsize, ysize, (char *)src) != 0)
          exit(1);
    }

    return(0);
}
Exemple #19
0
int main (int argc, char ** argv) {
	int radius, ret;
	int xsize, ysize, colmax, i;
	struct timespec stime, etime;

	double w[MAX_RAD];

	pixel *src = (pixel*) malloc(sizeof(pixel)*MAX_PIXELS);
	pixel *dst = (pixel*) malloc(sizeof(pixel)*MAX_PIXELS);
	/* Take care of the arguments */
	if (argc != 5) {
		fprintf(stderr, "Usage: %s num_threads radius infile outfile\n", argv[0]);
		exit_prog(src, dst, 1);
	}

	int num_threads = atoi(argv[1]);
	radius = atoi(argv[2]);
	if((radius > MAX_RAD) || (radius < 1)) {
		fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\n",
				radius, MAX_RAD);
		exit_prog(src, dst, 1);
	}

	/* read file */
	if(read_ppm (argv[3], &xsize, &ysize, &colmax, (char *) src) != 0){
		exit_prog(src, dst, 1);
	}

	if( num_threads < 1 || num_threads > ysize){
		fprintf(stderr, "Number of threads needs to be bigger than 0 and smaller than ysize of image\n");
		exit_prog(src, dst, 1);
	}

	if (colmax > 255) {
		fprintf(stderr, "Too large maximum color-component value\n");
		exit_prog(src, dst, 1);
	}

	pthread_t threads[num_threads];
	blur_data *pdata[num_threads];

	int l_ysize = ysize/num_threads;

	// Calculate gauss weights
	get_gauss_weights(radius, w);

	printf("Calling filter\n");

	clock_gettime(CLOCK_REALTIME, &stime);

	for(i=0;i<num_threads;i++){
		pdata[i] = malloc(sizeof(blur_data));
		pdata[i]->xsize = xsize;
		pdata[i]->ysize = l_ysize;
		if(i == num_threads - 1){
			pdata[i]->ysize += ysize - l_ysize*num_threads;
		}
		pdata[i]->src = src + i*l_ysize*xsize;
		pdata[i]->dst = dst + i*l_ysize*xsize;
		pdata[i]->radius = radius;
		pdata[i]->w = w;
		// Number of rows above the threads part of the image
		pdata[i]->rows_up = i*l_ysize;
		// Number of rows below the threads part of the image
		pdata[i]->rows_down = ysize - l_ysize - pdata[i]->rows_up;
		ret = pthread_create(&threads[i], NULL, blurfilter_x, (void*)pdata[i]);
		if(ret){
			fprintf(stderr, "ERROR creating thread\n");
                        free(pdata[i]);
			exit_prog(src, dst, 1);
		}
	}

        for(i=0;i<num_threads;i++){
                pthread_join(threads[i], NULL);
        }

        for(i=0;i<num_threads;i++){
		ret = pthread_create(&threads[i], NULL, blurfilter_y, (void*)pdata[i]);
		if(ret){
			fprintf(stderr, "ERROR creating thread\n");
                        free(pdata[i]);
			exit_prog(src, dst, 1);
		}
        }

        for(i=0;i<num_threads;i++){
                pthread_join(threads[i], NULL);
        }

	clock_gettime(CLOCK_REALTIME, &etime);

	printf("Filtering took: %g secs\n", (etime.tv_sec  - stime.tv_sec) +
			1e-9*(etime.tv_nsec  - stime.tv_nsec)) ;

	/* write result */
	printf("Writing output file\n");

	if(write_ppm (argv[4], xsize, ysize, (char *)src) != 0){
		exit_prog(src, dst, 1);
	}

	free(src);
	free(dst);

	return 0;
}
Exemple #20
0
int main(int argc, char **argv) {

    int ret, tmp;
    img_t img;
    char *output_dir;
    FILE *out_file;

    if (argc < 5) {
        printf("Usage:\npacked_tilegen <input> <output_dir> <tileX> <tileY> [cardinal direction N|E|S|W\n");
        exit(1);
    }

    printf("Read file \"%s\"\n", argv[1]);
    if (strstr(argv[1], ".png"))
        ret = read_png(argv[1], &img);
    else if (strstr(argv[1], ".ppm"))
        ret = read_ppm(argv[1], &img);
    else {
        printf("Unknown format!\n");
        exit(2);
    }

    output_dir = argv[2];

    if (ret) {
        printf("Could not read png input file! %d\n", ret);
        exit(ret);
    }

    img.tileX = atoi(argv[3]);
    img.tileY = atoi(argv[4]);

    if (argc > 5) {
        switch(argv[5][0]) {
        case 'n':
        case 'N':
            // keep defaults
            break;
        case 'e':
        case 'E':
            tmp = img.tileX;
            img.tileX = img.tileY;
            img.tileY = (2<<12) - 1 - tmp;
            break;
        case 's':
        case 'S':
            img.tileX = (2<<12) - 1 - img.tileX;
            img.tileY = (2<<12) - 1 - img.tileY;
            break;
        case 'w':
        case 'W':
            tmp = img.tileX;
            img.tileX = (2<<12) - 1 - img.tileY;
            img.tileY = tmp;
            break;
        default:
            fprintf(stderr, "Unknown cardinal direction \"%s\". Default to north\n", argv[5]);
        }
    }

    // create pack file for writing
    out_file = open_packed_file(output_dir, img.tileX, img.tileY);
    tmp = 0;

    while (1) {

        // crop image at given zoom level..
        crop_image(&img, tmp++, out_file);

        scale_image(&img);

        if (img.sizeX == TILE_SIZE) {
            save_image(&img, output_dir);
            break;
        }
    }

    close_packed_file(out_file);

    return 0;
}
Exemple #21
0
int main (int argc, char ** argv) {

  int error = 0;
  int* displacements;
  int* sendCounts;
  pixel* workData;
  MPI_Datatype pixelType;
  int workDataSize;

  /* MPI INIT*/
  int ierr = MPI_Init(&argc, &argv);
  int myId, numberProc;
  
  MPI_Comm_size(MPI_COMM_WORLD, &numberProc);
  MPI_Comm_rank(MPI_COMM_WORLD, &myId);
  
  int xsize, ysize, colmax;
  pixel* src = (pixel*) malloc(MAX_PIXELS*sizeof(pixel));
  double stime, etime;

  if (myId == 0)
        printf("MPI thres Threads: %d, file: %s\n", numberProc, argv[1]);

  /* Take care of the arguments */

  if (argc != 3) {
    fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
    MPI_Finalize();
    exit(1);
  }

  /* read file */
  if(myId == 0)
  {
    if(read_ppm (argv[1], &xsize, &ysize, &colmax, (char *) src) != 0)
  	{
  	  error = 1;
  	}

    if (colmax > 255) {
      error = 1;
    }
  }

  //start time measure
  if(myId == 0)  
    stime = MPI_Wtime();

  MPI_Bcast(&error, 1, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&xsize, 1, MPI_INT, 0, MPI_COMM_WORLD);  
  MPI_Bcast(&ysize, 1, MPI_INT, 0, MPI_COMM_WORLD);

  if (error == 1) {
    fprintf(stderr, "Too large maximum color-component value\n");
    MPI_Finalize();
    exit(1);
  }

  /* Scatter the data */
  workDataSize = ysize * xsize / numberProc + 1;
  displacements = (int*) malloc(numberProc * sizeof(int));
  sendCounts = (int*) malloc(numberProc * sizeof(int));
  workData = (pixel*) malloc(workDataSize * sizeof(pixel));
  memset(workData, 0, workDataSize * sizeof(pixel));
  
  calcDispls(xsize, ysize, numberProc, displacements, sendCounts);
  constructPixelDataType(&pixelType);

  MPI_Scatterv(src, sendCounts, displacements, pixelType, workData, sendCounts[myId], pixelType, 0, MPI_COMM_WORLD);

  thresfilter(sendCounts[myId], workData, numberProc, myId, xsize * ysize);

  MPI_Gatherv(workData, sendCounts[myId], pixelType, src, sendCounts, displacements, pixelType, 0, MPI_COMM_WORLD);

  if(myId == 0){
    etime = MPI_Wtime();
    printf("Total time: %.6f\n", etime - stime);
  
    /* write result */
    printf("Writing output file\n");
    
    if(write_ppm (argv[2], xsize, ysize, (char *)src) != 0)
      {
	MPI_Finalize();
	exit(1);
      }
  }

  free(displacements);
  free(sendCounts);
  free(src);
  free(workData);

  MPI_Finalize();
  return(0);
}
Exemple #22
0
int main (int argc, char ** argv)
{
    int radius;
    int xsize, ysize, colmax, np, me;
    pixel * src = malloc (MAX_PIXELS * sizeof(pixel));
    double w[MAX_RAD];
    
    /* MPI INITIALIZATION */
    MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &np );
    MPI_Comm_rank( MPI_COMM_WORLD, &me );
    
    /* Take care of the arguments */
    if(me ==  MASTER){
        if (argc != 4) {
            fprintf(stderr, "Usage: %s radius infile outfile\n", argv[0]);
            exit(1);
        }
        radius = atoi(argv[1]);
        if((radius > MAX_RAD) || (radius < 1)) {
            fprintf(stderr, "Radius (%d) must be greater than zero and less then %d\n", radius, MAX_RAD);
            exit(1);
        }
        /* read file */
        if(read_ppm (argv[2], &xsize, &ysize, &colmax, (char *) src) != 0)
            exit(1);

        if (colmax > 255) {
            fprintf(stderr, "Too large maximum color-component value\n");
            exit(1);
        }
        /* filter */
        get_gauss_weights(radius, w);

        printf("Has read the image and generated Coefficients\n");
    }

    // BROADCASTING RADIUS
    MPI_Bcast( &radius, 1, MPI_INT, MASTER, MPI_COMM_WORLD );
    // BROADCASTING W
    MPI_Bcast( w, MAX_RAD, MPI_DOUBLE, MASTER, MPI_COMM_WORLD );
    // BROADCASTING XSIZE
    MPI_Bcast( &xsize, 1, MPI_INT, MASTER, MPI_COMM_WORLD );
    // BROADCASTING YSIZE
    MPI_Bcast( &ysize, 1, MPI_INT, MASTER, MPI_COMM_WORLD );
    
    /* MPI_DATATYPE : mpi_pixel_type */
    const int nitems=3;
    int          blocklengths[3] = {1,1,1};
    MPI_Datatype types[3] = {MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR, MPI_UNSIGNED_CHAR};
    MPI_Datatype mpi_pixel_type;
    MPI_Aint     offsets[3];

    offsets[0] = 0;
    offsets[1] = 1;
    offsets[2] = 2;
    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_pixel_type);
    MPI_Type_commit(&mpi_pixel_type);


    /* COMPUTE THE AREA TO BE EXECUTED BY EACH PROCESSOR*/
    int * sendcounts, * displace;

    sendcounts = malloc(sizeof(int)*np);
    displace = malloc(sizeof(int)*np);


    int * line_starts      = malloc (np * sizeof(int)),
        * line_ends        = malloc (np * sizeof(int)),
        * line_send_starts = malloc (np * sizeof(int)),
        * line_send_ends   = malloc (np * sizeof(int)),
        * sizes            = malloc (np * sizeof(int)),
        * n_starts         = malloc (np * sizeof(int)),
        * n_sizes          = malloc (np * sizeof(int));

    int line, rem, line_sum = 0;

    int i;

    line = ysize / np;
    rem  = ysize % np;

    for (i = 0; i < np; i++) {

        sizes       [i] = (rem > i) ? line + 1: line;
        line_starts [i] = line_sum;
        line_ends   [i] = line_sum + sizes [i];
        n_starts    [i] = xsize * line_starts [i];
        n_sizes     [i] = xsize * sizes [i];

        line_send_starts [i] = ((line_starts [i] - radius) < 0)     ? 0     : line_starts [i] - radius;
        line_send_ends   [i] = ((line_ends   [i] + radius) > ysize) ? ysize : line_ends   [i] + radius;

        sendcounts [i] = (line_send_ends [i] - line_send_starts [i]) * xsize;

        displace [i] = line_send_starts [i] * xsize;

        line_sum += sizes [i];

        if (me == MASTER) {
            printf("P%d: starting from line %d to line %d (%d lines) and sending from line %d to %d (%d lines)\n",
                   i, line_starts [i],     line_ends[i],      line_ends[i]      - line_starts [i],
                      line_send_starts[i], line_send_ends[i], line_send_ends[i] - line_send_starts[i]);
        }
    }

    pixel * buffer_receiver = malloc (sizeof(pixel) * sendcounts[me]);
    
    double start, end;

    start = MPI_Wtime();
    /* DIVIDE THE IMAGE FOR THE COMPUTATION BY EACH PROCESSOR */
    MPI_Scatterv( src, sendcounts , displace, mpi_pixel_type , buffer_receiver, sendcounts[me], mpi_pixel_type , MASTER, MPI_COMM_WORLD );

    int local_ysize = line_send_ends [me] - line_send_starts [me],
        local_start = line_starts    [me] - line_send_starts [me],
        local_end   = local_start + sizes [me];

    /* COMPUTE THE BLUR FILTER */
    blurfilter_bordered(xsize, local_ysize, local_start, local_end, buffer_receiver, radius, w);

    /* GET THE PROCESSED SUBIMAGES AND MERGE THEM */
    MPI_Gatherv (buffer_receiver + local_start * xsize, n_sizes [me],
                 mpi_pixel_type, src, n_sizes, n_starts, mpi_pixel_type, MASTER , MPI_COMM_WORLD);

    end = MPI_Wtime()-start;
    
    if (me == MASTER){
		//printf("Main Master Filtering took: %g sec, s\n", (etime.tv_sec  - stime.tv_sec) + 1e-9*(etime.tv_nsec  - stime.tv_nsec)) ;
		end = MPI_Wtime()-start;
		printf("MASTER mpi time: %g sec\n",end);
		
		//print the time on the file
		FILE * fp;
		char * f;
		f = "measures.csv";
		fp = fopen(f, "a");// "w" means that we are going to write on this file, "a" appends
		fprintf(fp,"%g\n",end); // just write down the elapsed seconds: we'll make only copy&paste to the excel :)
		fclose(fp);
		
		
		/* write result */
		printf("Writing output file\n");
		if(write_ppm (argv[3], xsize, ysize,  (char *)src) != 0)
			exit(1);
	 	printf("Image written on %s\n",argv[3]);
	}

    MPI_Finalize();
    return(0);
}
Exemple #23
0
int main(int argc, char **argv)
{
	init_spus();
	srand((unsigned)time(NULL));
	char *fis_in, *fis_out;
	int zoom, rows, cols, i, j,
	overlap_spu, overlap_ppu,
	patch_w, patch_h, nr_patches;	

	if (argc < 8) {
		fprintf(stderr, "Error: Missing some parameters.\n");
		fprintf(stderr, "Run: ./program fis_in fis_out zoom nr_bucati_dim1 nr_bucati_dim2 banda_de_suprapunere_dim1 banda_de_suprapunere_dim2\n");
		return -1;
	}

	fis_in  = argv[1];
	fis_out = argv[2];
	zoom    = atoi(argv[3]);
	rows = atoi(argv[4]);
	cols = atoi(argv[5]);
	overlap_spu = atoi(argv[6]);
	overlap_ppu = atoi(argv[7]);

	
	image img_src = read_ppm(fis_in);
	if (img_src == NULL) {
		fprintf(stderr, "Error reading image file.\n");
		return -1;
	}

	patch_w = (zoom * img_src->width)  / cols;
	patch_h = (zoom * img_src->height) / rows;
	nr_patches = rows * cols;
	printf("PPU: NR PATCHES NECESARY = %d\n", nr_patches);

	int **spu_patch_id_vector = alloc_patch_id_vector(rows);
	if (spu_patch_id_vector == NULL)
		return -1;

	printf("PPU: ZOOM=%d ROWS=%d COLS=%d img->width=%d img->height=%d patch_w=%d patch_h=%d\n", zoom, rows, cols, img_src->width, img_src->height, patch_w, patch_h);

	int* rand_seed = make_seed_vector();
	if (rand_seed == NULL)
		return -1;
	int ***min_borders = malloc_align(SPU_THREADS * sizeof(int**), 4);
	if (min_borders == NULL) {
		perror("PPU: malloc_align failed in main");
		return -1;
	}
	for (i = 0; i < SPU_THREADS; i++) {
		min_borders[i] = alloc_aligned_matrix((rows-1), overlap_spu);
		if (min_borders[i] == NULL)
			return -1;
	}

	pixel_t **patches_to_send = make_patches(img_src, patch_w, patch_h, nr_patches);

	send_patch_info(&patch_w, &patch_h, &rows, &nr_patches, spu_patch_id_vector, patches_to_send, rand_seed, &overlap_spu, min_borders);

	stop_spus();

	int out_img_width = zoom * img_src->width;
	int out_img_height = zoom * img_src->height;
	image img_dst = alloc_img(out_img_width, out_img_height);

	for (i = 0; i < SPU_THREADS; i++) {
		printf("PPU: spu[%d]: ID= ", i);
		for (j = 0; j < rows; j++)
			printf("%d ", spu_patch_id_vector[i][j]);
		printf("\n");
	}

	make_final_image(img_dst, patch_w, patch_h, spu_patch_id_vector, rows, patches_to_send);
	write_ppm(fis_out, img_dst);

	free_img(img_src);
	free_img(img_dst);
	free_seed_vector(rand_seed);
	free_patch_id_vector(spu_patch_id_vector);
	for (i = 0; i < SPU_THREADS; i++)
		free_aligned_matrix(min_borders[i], rows-1);
	return 0;
}
Exemple #24
0
void sprite_init() {
    /* Sets State_Array to Background image */
    read_ppm(1,0,0);
}
Exemple #25
0
ppm* init_ppm_read(char filename, FILE *fp){
 ppm *p=init_ppm();
	read_ppm(p,filename,fp);
	return p;
}
Exemple #26
0
int main (int argc, char ** argv) {
  int xsize, ysize, colmax, workload, work2, i, offset, np, me;
  pixel src[MAX_PIXELS], recvbuff[MAX_PIXELS];

  struct timespec stime, etime, rootstime, rootetime;

  /* Take care of the arguments */

  if (argc != 3) {
    fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
    exit(1);
  }
    
  MPI_Comm com = MPI_COMM_WORLD;
  MPI_Init( &argc, &argv );
  MPI_Comm_size( com, &np );
  MPI_Comm_rank( com, &me );

  int scounts[np], displs[np];


  MPI_Aint offsets[1] = {0};
  MPI_Datatype oldtypes[1] = {MPI_CHAR};
  int blockcounts[1] = {3};
  MPI_Datatype MPI_PIXEL;

  MPI_Type_struct(1, blockcounts,offsets, oldtypes,&MPI_PIXEL);
  MPI_Type_commit(&MPI_PIXEL);




  if(me==0)
    {		      
      clock_gettime(CLOCK_REALTIME, &rootstime);

      read_ppm(argv[1], &xsize, &ysize, &colmax, (char*)src);
      workload = (ysize/np)*xsize;
      work2= ysize%np;
      int offset = 0;
      for(i=0; i<np; i++)
	{
	  displs[i]=offset;
	  if(i<work2)
	    {
	      scounts[i] = workload+xsize;	
	    }
	  else{
	    scounts[i] = workload;
	  }
	  offset += scounts[i];
	}
      if (colmax > 255) {
	fprintf(stderr, "Too large maximum color-component value\n");
	exit(1);
      }
      clock_gettime(CLOCK_REALTIME, &rootetime);
	
      printf("Root reading and calculating work took: %2g secs\n", (rootetime.tv_sec  - rootstime.tv_sec) +
	     1e-9*(rootetime.tv_nsec  - rootstime.tv_nsec)) ;
    }


  clock_gettime(CLOCK_REALTIME, &stime);

  MPI_Bcast(&ysize, 1, MPI_INT, 0, com);
  MPI_Bcast(&xsize, 1, MPI_INT, 0, com);
  MPI_Bcast(scounts, np, MPI_INT, 0, com);
  MPI_Bcast(displs, np, MPI_INT, 0, com);
  // printf("Processor %d has scounts: %d and displs %d \n", me, scounts[me], displs[me]);


  
  MPI_Scatterv( src, scounts, displs, MPI_PIXEL, recvbuff, scounts[me], MPI_PIXEL, 0, com);  

  
  uint sum;
  for(i = 0, sum = 0; i < scounts[me]; i++) {
    sum += (uint)recvbuff[i].r + (uint)recvbuff[i].g + (uint)recvbuff[i].b;
  }
  sum /= scounts[me];

  uint globalsum;

  //printf("Processor %d has sum %d\n", me, sum);
  MPI_Reduce(&sum, &globalsum, 1, MPI_UNSIGNED , MPI_SUM, 0, com); 
  

    
    

  if(me==0)
    { 
      globalsum /= np;
      // printf("Processor %d has reduced sum %d\n", me, globalsum);
      
      // 
     
    }
  MPI_Bcast(&globalsum, 1, MPI_UNSIGNED, 0, com);

  thresfilter(xsize, scounts[me]/xsize, recvbuff, globalsum);
  
  MPI_Gatherv(recvbuff, scounts[me], MPI_PIXEL , src, scounts, displs, MPI_PIXEL, 0, com);
  clock_gettime(CLOCK_REALTIME, &etime);


  if(me == 0){
    write_ppm (argv[2], xsize, ysize, (char *)src);
  
  }


  
  printf("Filtering for process %d took: %2g secs\n", me ,(etime.tv_sec  - stime.tv_sec) +
	 1e-9*(etime.tv_nsec  - stime.tv_nsec)) ;


  MPI_Finalize();
  






}