Why am I not writing anything to my Roller2.raw?

55 Views Asked by At

I got the following code written in C but I have a small issue with this image filter program. The problem complies and everything as usual, but my image roller2.raw is not changing based on the number of iterations (checked in rawpixels.net). It is supposed to read the roller1 and write to roller2. Am I doing the writing in a wrong way? following code is below

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


typedef unsigned char image[251][256];

int main() 
{

 int h,i,j,k,l,sum,iterations;
 image *datain, *dataout;

 FILE *f , *g; 
 f = fopen("/home/osboxes/prestandaoptimering/roller1.raw", "r"); 
 g = fopen("/home/osboxes/prestandaoptimering/roller2.raw", "w"); 

 datain = (image*)malloc(sizeof(image));
 dataout = (image*)malloc(sizeof(image));
 fread(*datain, sizeof(image), 1, f); 


 printf("Enter number of iterations:");
 scanf("%d", &iterations);
 getchar(); 

 printf("Computing result\n");


 for( i = 0; i <= 250; i ++) {
        for( j = 0; j <= 255; j ++) {
                (*dataout) [i][j] = (*datain) [i][j]; 
    }
 }



 for( h = 1; h <= iterations; h ++) {

        for( i = 1; i <= 249; i ++) {

                for( j = 1; j <= 254; j ++) {

                        sum = 0;
                        for( k = -1; k <= 1; k ++) {
                            for( l = -1; l <= 1; l ++) {
                                sum = sum + (*datain)[i+k][j+l];
                }

                        (*dataout)[i][j] = (sum + (*datain)[i][j]*7) / 16;
            }
                }
                for( i = 0; i <= 250; i ++) {
                    for( j = 0; j <= 255; j ++) {
                        (*datain)[i][j] = (*dataout)[i][j];
            }
        }
    }
 }

 printf("Writing result\n");
 fwrite(dataout, sizeof(image), 1, g);
 if (f != NULL) {
    fclose(f); 
 }
 f = NULL;
 if (g != NULL) {
    fclose(g);
 }
 g = NULL;

 free(datain);
 free(dataout);
 return 0; 
}
1

There are 1 best solutions below

3
On

I think the issue is in iterations loop.

for( h = 1; h <= iterations; h ++) 
{
    for( i = 1; i <= 249; i ++) 
    {
        for( j = 1; j <= 254; j ++) 
        {
            sum = 0;
            for( k = -1; k <= 1; k ++) 
            {
                for( l = -1; l <= 1; l ++) 
                {
                    sum = sum + (*datain)[i+k][j+l];
                }
            }

            //This should be outside the k and l loop.
            (*dataout)[i][j] = (sum + (*datain)[i][j]*7) / 16;
        }

        //You should use different variable name instead of i. OR declare 'i' again for `for` loop.
        for(int i2 = 0; i2 <= 250; i2 ++)
        {
            for( j = 0; j <= 255; j ++) 
            {
                (*datain)[i2][j] = (*dataout)[i2][j];
            }
        }
    }
 }