Processing PGM files

I have written and modified certain programs in order to copy and transpose pgm images.
First I tested the copy kernel and it seems to copy all the pixels but when it comes to output the image, it fails, the image cannot be seen, although each pixel value is there. What could be the problem ?

/* Copyright (c) 1993-2015, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include<stdio.h>
#include<stdlib.h>
#include <string.h>

const int TILE_DIM = 32;
const int BLOCK_ROWS = 8;

__global__ void copy(int *odata, const int *idata){
  int x = blockIdx.x * TILE_DIM + threadIdx.x;
int y = blockIdx.y * TILE_DIM + threadIdx.y;
int width = gridDim.x * TILE_DIM;
for (int j = 0; j < TILE_DIM; j+= BLOCK_ROWS)
odata[(y+j)*width + x] = idata[(y+j)*width + x];
  }

struct PGMstructure
{
    int maxVal;
    int width;
    int height;
    int data[800][800];
};


int main()
{
    FILE *imagein;
    FILE *imageout;

    cudaError_t cudaStatus;

    int row, col;
    int widthout,heightout;

    int i,j;
    int ch_int;

    struct PGMstructure *imginfo = (PGMstructure*)malloc(sizeof(struct PGMstructure));

    char infpath[500];
    char outfpath[500];

    printf("Enter PGM file path:");
    scanf("%s",infpath);
    
    imagein = fopen(infpath,"r+");

    if(imagein == NULL)
    {
        printf("Error opening first file");
        exit(8);
    }


    while(getc(imagein) != '\n');           

    if (getc(imagein) == '#' )              
        {
        while(getc(imagein) != '\n');
        }
    else
        {
        fseek(imagein, -1, SEEK_CUR);
        }


    fscanf(imagein,"%d", &imginfo->width);
    fscanf(imagein,"%d", &imginfo->height);
    fscanf(imagein,"%d", &imginfo->maxVal);
    printf("\n width  = %d\n",imginfo->width);
    printf("\n height = %d\n",imginfo->height);
    printf("\n maxVal = %d\n",imginfo->maxVal);

    for (row=0; row < imginfo->height; row++){

        for (col=0; col < imginfo->width; col++)
        {
            fscanf(imagein,"%d", &ch_int);
            imginfo->data[row][col] = ch_int;
        }
    }
    

    fclose(imagein);
    
    int x = imginfo->height;
    int y = imginfo->width;
    //int index = 0;
    int *onedimentional = (int* )malloc(sizeof(int) * (x*y));
    int *copydata = (int* )malloc(sizeof(int) * (x*y));
    int widthlimit = y;
    int heightlimit = x;
    dim3 dimGrid(widthlimit/TILE_DIM, heightlimit/TILE_DIM,1);
    dim3 dimBlock(TILE_DIM,BLOCK_ROWS,1);
    int *d_onedimentional, *d_copydata;
    
    cudaStatus = cudaMalloc((void**)&d_onedimentional, sizeof(int) * (x*y));
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not allocate d_onedimentional in the device!\n");
    }
    cudaStatus = cudaMalloc((void**)&d_copydata, sizeof(int) * (x*y));

    if(cudaStatus != cudaSuccess)
    {
        printf("Could not allocate d_onedimentional in the device!\n");
    }

    for(i=0; i < heightlimit; ++i ){
    	for(j=0; j < widthlimit; ++j){
    	onedimentional[i * widthlimit + j] = imginfo->data[i][j];
		//index++;	
    	}
    }

    cudaStatus = cudaMemcpy(d_onedimentional, onedimentional, sizeof(int) * (x * y), cudaMemcpyHostToDevice);
    
    
    copy<<<dimGrid, dimBlock>>>(d_copydata, d_onedimentional);
   
    

    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy onedimentional to d_onedimentional in the device!\n");
    }
    
    

    
    cudaStatus = cudaMemcpy(copydata, d_copydata, sizeof(int) * (x*y), cudaMemcpyDeviceToHost);
    
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy d_copydata from the device\n");
    }
    
     for(i=0; i < heightlimit; ++i ){
    	for(j=0; j < widthlimit; ++j){
    	imginfo->data[i][j] = copydata[i * widthlimit + j];
			
    	}
    }   

     
    
    for ( i = 0 ; i < widthlimit*heightlimit ; i++)
    {
            printf("%d:%d\n", i,copydata[i]);
            //fprintf( imageout,"\n" );
    } 



    printf("Enter path of output file:");

    scanf("%s",outfpath);
    imageout = fopen(outfpath,"w+");
    
    heightout = imginfo->height;
    widthout = imginfo->width;
    fprintf(imageout, "P2\n");
    fprintf(imageout, "%d %d\n", widthout, heightout);
    fprintf(imageout, "255\n");


    for ( i = 0 ; i < imginfo->height ; i++ )
    {
        for ( j = 0 ; j < imginfo->width ; j++ )
        {
        	//printf("%d",imginfo->data[i][j] );
            fprintf( imageout,"%d" , imginfo->data[i][j] );
        }
            //printf("\n");
            fprintf( imageout,"\n" );
    }

    fclose(imageout);
    

    return 0;
}

You don’t read or write PGM files by reading in int:

        fscanf(imagein,"%d", &ch_int);

and writing out int:

        fprintf( imageout,"%d" , imginfo->data[i][j] );

Use fgetc/fputc instead:

         ch_int = fgetc(imagein);

and
fputc(imginfo->data[i][j], imageout);

You might want to study a tutorial:

[url]https://ugurkoltuk.wordpress.com/2010/03/04/an-extreme-simple-pgm-io-api/[/url]

as there are other differences between what you are doing and what is correct.

This has nothing to do with CUDA, of course.

But the author in that link states in a comment “in P2 you have ascii values not pure binary, so instead of fgetc and fputc I guess you’d have to use fscanf and fprintf or that sort of stuff”

You are correct. I thought you were trying to work with P5 files because that is what the CUDA sample codes use, but I see you are writing a P2 file. The P2 PGM format is indeed an ascii format.

The P2 format also requires a space in between adjacent pixels. You don’t have that, so you could try changing this:

fprintf( imageout,"%d" , imginfo->data[i][j] );

to this:

fprintf( imageout,"%d " , imginfo->data[i][j] );
                     ^
                     added space

This describes differences between P2 and P5 PGM:

http://netpbm.sourceforge.net/doc/pgm.html

There is some improvement, although the output is not the expected

/* Copyright (c) 1993-2015, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#include<stdio.h>
#include<stdlib.h>
#include <string.h>

const int TILE_DIM = 32;
const int BLOCK_ROWS = 8;

__global__ void transposeNaive(int *odata, const int *idata, int width, int height){
  int xIndex = blockIdx.x * TILE_DIM + threadIdx.x;
  int yIndex = blockIdx.y * TILE_DIM + threadIdx.y;

  int index_in = xIndex + width * yIndex;
  int index_out = yIndex + height * xIndex;

  for(int i = 0; i<TILE_DIM; i+=BLOCK_ROWS){
    odata[index_out+i] = idata[index_in + i * width];

  }
  }

struct PGMstructure
{
    int maxVal;
    int width;
    int height;
    int data[800][800];
};


int main()
{
    FILE *imagein;
    FILE *imageout;

    cudaError_t cudaStatus;

    int row, col;
    int widthout,heightout;

    int i,j;
    int ch_int;

    struct PGMstructure *imginfo = (PGMstructure*)malloc(sizeof(struct PGMstructure));

    char infpath[500];
    char outfpath[500];

    printf("Enter PGM file path:");
    scanf("%s",infpath);
    
    imagein = fopen(infpath,"r+");

    if(imagein == NULL)
    {
        printf("Error opening first file");
        exit(8);
    }


    while(getc(imagein) != '\n');           

    if (getc(imagein) == '#' )              
        {
        while(getc(imagein) != '\n');
        }
    else
        {
        fseek(imagein, -1, SEEK_CUR);
        }


    fscanf(imagein,"%d", &imginfo->width);
    fscanf(imagein,"%d", &imginfo->height);
    fscanf(imagein,"%d", &imginfo->maxVal);
    printf("\n width  = %d\n",imginfo->width);
    printf("\n height = %d\n",imginfo->height);
    printf("\n maxVal = %d\n",imginfo->maxVal);

    for (row=0; row < imginfo->height; row++){

        for (col=0; col < imginfo->width; col++)
        {
            fscanf(imagein,"%d", &ch_int);
            imginfo->data[row][col] = ch_int;
        }
    }
    

    fclose(imagein);
    
    int x = imginfo->height;
    int y = imginfo->width;
    //int index = 0;
    int *onedimentional = (int* )malloc(sizeof(int) * (x*y));
    int *transposedata = (int* )malloc(sizeof(int) * (x*y));
    int widthlimit = y;
    int heightlimit = x;
    dim3 dimGrid(widthlimit/TILE_DIM, heightlimit/TILE_DIM,1);
    dim3 dimBlock(TILE_DIM,BLOCK_ROWS,1);
    int *d_onedimentional, *d_transposedata;
    
    cudaStatus = cudaMalloc((void**)&d_onedimentional, sizeof(int) * (x*y));
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not allocate d_onedimentional in the device!\n");
    }
    cudaStatus = cudaMalloc((void**)&d_transposedata, sizeof(int) * (x*y));

    if(cudaStatus != cudaSuccess)
    {
        printf("Could not allocate d_onedimentional in the device!\n");
    }

    for(i=0; i < heightlimit; ++i ){
    	for(j=0; j < widthlimit; ++j){
    	onedimentional[i * widthlimit + j] = imginfo->data[i][j];
		//index++;	
    	}
    }

    cudaStatus = cudaMemcpy(d_onedimentional, onedimentional, sizeof(int) * (x * y), cudaMemcpyHostToDevice);
    
    
    transposeNaive<<<dimGrid, dimBlock>>>(d_transposedata, d_onedimentional, y, x);
   
    

    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy onedimentional to d_onedimentional in the device!\n");
    }
    
    

    
    cudaStatus = cudaMemcpy(transposedata, d_transposedata, sizeof(int) * (x*y), cudaMemcpyDeviceToHost);
    
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy d_transposedata from the device\n");
    }
    
     for(i=0; i < heightlimit; ++i ){
    	for(j = 0 ; j < widthlimit; ++j){
    	imginfo->data[i][j] = transposedata[i * widthlimit + j];
			
    	}
    }   

     
    
    for ( i = 0 ; i < widthlimit*heightlimit ; i++)
    {
            printf("%d:%d\n", i,transposedata[i]);
            //fprintf( imageout,"\n" );
    } 

    int index = 0;
    int t_countcol=0;
    j=0;
    i=0;
    for(index = 0; index < widthlimit*heightlimit; index++){
        imginfo->data[i][j]= transposedata[index];
        j++;
        t_countcol++;
        if(t_countcol == heightlimit-1){
           i++;
           j=0;
           t_countcol = 0;
        }
    }


    
    printf("Enter path of output file:");

    scanf("%s",outfpath);
    imageout = fopen(outfpath,"w+");
    
    heightout = imginfo->height;
    widthout = imginfo->width;
    fprintf(imageout, "P2\n");
    fprintf(imageout, "%d %d\n", widthout, heightout);
    fprintf(imageout, "255\n");


    for ( i = 0 ; i < imginfo->height ; i++ )
    {
        for ( j = 0 ; j < imginfo->width ; j++ )
        {
        	//printf("%d",imginfo->data[i][j] );
            fprintf( imageout,"%d " , imginfo->data[i][j] );
        }
            //printf("\n");
            fprintf( imageout,"\n" );
    }

    fclose(imageout);

    free(onedimentional);
    free(transposedata);
    free(imginfo);
    cudaFree(d_onedimentional);
    cudaFree(d_transposedata);
    

    return 0;
}

There is some improvement, although the output is not the expected

/* Copyright (c) 1993-2015, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include<stdio.h>
#include<stdlib.h>
#include <string.h>

const int TILE_DIM = 32;
const int BLOCK_ROWS = 8;

__global__ void transposeNaive(int *odata, const int *idata, int width, int height){
  int xIndex = blockIdx.x * TILE_DIM + threadIdx.x;
  int yIndex = blockIdx.y * TILE_DIM + threadIdx.y;

  int index_in = xIndex + width * yIndex;
  int index_out = yIndex + height * xIndex;

  for(int i = 0; i<TILE_DIM; i+=BLOCK_ROWS){
    odata[index_out+i] = idata[index_in + i * width];

  }
  }

struct PGMstructure
{
    int maxVal;
    int width;
    int height;
    int data[800][800];
};

int main()
{
    FILE *imagein;
    FILE *imageout;

    cudaError_t cudaStatus;

    int row, col;
    int widthout,heightout;

    int i,j;
    int ch_int;

    struct PGMstructure *imginfo = (PGMstructure*)malloc(sizeof(struct PGMstructure));

    char infpath[500];
    char outfpath[500];

    printf("Enter PGM file path:");
    scanf("%s",infpath);
    
    imagein = fopen(infpath,"r+");

    if(imagein == NULL)
    {
        printf("Error opening first file");
        exit(8);
    }

while(getc(imagein) != '\n');           

    if (getc(imagein) == '#' )              
        {
        while(getc(imagein) != '\n');
        }
    else
        {
        fseek(imagein, -1, SEEK_CUR);
        }

fscanf(imagein,"%d", &imginfo->width);
    fscanf(imagein,"%d", &imginfo->height);
    fscanf(imagein,"%d", &imginfo->maxVal);
    printf("\n width  = %d\n",imginfo->width);
    printf("\n height = %d\n",imginfo->height);
    printf("\n maxVal = %d\n",imginfo->maxVal);

    for (row=0; row < imginfo->height; row++){

        for (col=0; col < imginfo->width; col++)
        {
            fscanf(imagein,"%d", &ch_int);
            imginfo->data[row][col] = ch_int;
        }
    }

fclose(imagein);
    
    int x = imginfo->height;
    int y = imginfo->width;
    //int index = 0;
    int *onedimentional = (int* )malloc(sizeof(int) * (x*y));
    int *transposedata = (int* )malloc(sizeof(int) * (x*y));
    int widthlimit = y;
    int heightlimit = x;
    dim3 dimGrid(widthlimit/TILE_DIM, heightlimit/TILE_DIM,1);
    dim3 dimBlock(TILE_DIM,BLOCK_ROWS,1);
    int *d_onedimentional, *d_transposedata;
    
    cudaStatus = cudaMalloc((void**)&d_onedimentional, sizeof(int) * (x*y));
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not allocate d_onedimentional in the device!\n");
    }
    cudaStatus = cudaMalloc((void**)&d_transposedata, sizeof(int) * (x*y));

    if(cudaStatus != cudaSuccess)
    {
        printf("Could not allocate d_onedimentional in the device!\n");
    }

    for(i=0; i < heightlimit; ++i ){
    	for(j=0; j < widthlimit; ++j){
    	onedimentional[i * widthlimit + j] = imginfo->data[i][j];
		//index++;	
    	}
    }

    cudaStatus = cudaMemcpy(d_onedimentional, onedimentional, sizeof(int) * (x * y), cudaMemcpyHostToDevice);

transposeNaive<<<dimGrid, dimBlock>>>(d_transposedata, d_onedimentional, y, x);

if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy onedimentional to d_onedimentional in the device!\n");
    }

cudaStatus = cudaMemcpy(transposedata, d_transposedata, sizeof(int) * (x*y), cudaMemcpyDeviceToHost);
    
    if(cudaStatus != cudaSuccess)
    {
    	printf("Could not copy d_transposedata from the device\n");
    }
    
     for(i=0; i < heightlimit; ++i ){
    	for(j = 0 ; j < widthlimit; ++j){
    	imginfo->data[i][j] = transposedata[i * widthlimit + j];
			
    	}
    }   

for ( i = 0 ; i < widthlimit*heightlimit ; i++)
    {
            printf("%d:%d\n", i,transposedata[i]);
            //fprintf( imageout,"\n" );
    } 

    int index = 0;
    int t_countcol=0;
    j=0;
    i=0;
    for(index = 0; index < widthlimit*heightlimit; index++){
        imginfo->data[i][j]= transposedata[index];
        j++;
        t_countcol++;
        if(t_countcol == heightlimit-1){
           i++;
           j=0;
           t_countcol = 0;
        }
    }

printf("Enter path of output file:");

    scanf("%s",outfpath);
    imageout = fopen(outfpath,"w+");
    
    heightout = imginfo->height;
    widthout = imginfo->width;
    fprintf(imageout, "P2\n");
    fprintf(imageout, "%d %d\n", widthout, heightout);
    fprintf(imageout, "255\n");

for ( i = 0 ; i < imginfo->height ; i++ )
    {
        for ( j = 0 ; j < imginfo->width ; j++ )
        {
        	//printf("%d",imginfo->data[i][j] );
            fprintf( imageout,"%d " , imginfo->data[i][j] );
        }
            //printf("\n");
            fprintf( imageout,"\n" );
    }

    fclose(imageout);

    free(onedimentional);
    free(transposedata);
    free(imginfo);
    cudaFree(d_onedimentional);
    cudaFree(d_transposedata);

return 0;
}