2014-11-29 2 views
0

Я пытался в течение нескольких дней выяснить, почему моя программа просто перепечатывает входное изображение. Я знаю, что мои другие функции работают, но по какой-то причине это меня толкает, я пробовал все, что мог подумать о перемещении пикселей вокруг, но абсолютно ничего, что я пробовал, работает.Повторное воспроизведение программы после прохождения функции Зеркало

Заголовок:

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

    struct pixel { 
     char r, g, b; 
}; 

int g_width, g_height; 

void parseHeader(FILE *input); 
void parseImage(FILE *input, struct pixel *theArray); 
void print(struct pixel a[]); 
void my_Mirror(struct pixel a[]); 
void rotate(struct pixel a[]); 
void my_Flip(struct pixel a[]); 

главная:

#include "transform.h" 


int main (int argc, char *argv[]) { 

     // declarations here 
    FILE *inFile; 


     // open input file 

    inFile = fopen(argv[2],"r"); 
    if (inFile == NULL) 
    {   
     fprintf(stderr, "File open error. Exiting program\n"); 
     exit(1); 
    } 


     // parseHeader function call here 
    parseHeader(inFile);  

     // malloc space for the array (example given in assignment write-up) 
    struct pixel * image = 
      (struct pixel *) malloc(sizeof(struct pixel) * g_width * g_height); 

     // parseImage function call here 
    parseImage(inFile, image); 

     // close input file 

    fclose(inFile); 

     // manipulate the image according to command-line parameter 
     //    1: mirror image 
     //    2: upside down image 
     //    3: rotate to the right 90 degrees 

    if (atoi(argv[1]) == 1) 
    { 
     my_Mirror(image); 
    } 

    if (atoi(argv[1]) == 2) 
    { 
     my_Flip(image); 
    } 
    if (atoi(argv[1]) ==3) 
    { 
     rotate(image); 
    } 

    print(image); 
    return 0; 
} 

зеркало:

 void my_Mirror(struct pixel a[]) 
{ 
    int i,j,limit = 0; 
    struct pixel temp; 

    for(j = 0; j < g_height; ++j) //move through vertical pixels 
    { 
     for(i = 0; i < (g_width/2); i++) 
     { 
     temp = a[(j * g_width) + i]; 
     a[(j * g_width) + i] = a[((j+1)*g_width) - (1 + i)]; 
     a[((j+1)*g_width) - (1 + i)] = temp; 
     } 
    } 
} 

Это моя горизонтальная функция флип, который работает до тех пор, зеркало вызова, если это помогает:

#include "transform.h" 

void my_Flip(struct pixel a[]) 
{ 
    struct pixel temp; 
    int i; 
    int j = 0; 

    for (i = (g_width * g_height); i >= 0; --i) 
    { 
     temp = a[i]; 
     a[i] = a[(i-i)+j]; //swap values of pixels 
     a[(i-i)+j] = temp; 

     ++j; 

     if(j == (g_width * g_height)/2) 
     { 
     i = 0; 
     } 

    } 
    my_Mirror(a); 
} 

ответ

0

Пиксель не является внутренним типом, поэтому его необходимо скопировать с помощью memcpy , а не как простое назначение.

Код должен подтвердить параметр командной строки , и если параметр не содержит допустимого значения , тогда жалоба перед выходом.

Код должен подтвердить возвращаемое значение от входных функций ввода/вывода , чтобы гарантировать успешную работу.

Так вот возможное решение вашего вопроса:

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

struct pixel 
{ 
     char r, g, b; 
}; 

// global data 
int g_width, g_height; 

//prototypes 
void parseHeader(FILE *input); 
void parseImage(FILE *input, struct pixel *theArray); 
void print(struct pixel a[]); 
void my_Mirror(struct pixel a[]); 
void rotate(struct pixel a[]); 
void my_Flip(struct pixel a[]); 



#include "transform.h" 


int main (int argc, char *argv[]) 
{ 

    // declarations here 
    FILE *inFile; 


    // open input file 
    inFile = fopen(argv[2],"r"); 
    if (inFile == NULL) 
    { 
     fprintf(stderr, "File open error. Exiting program\n"); 
     exit(1); 
    } 

    // implied else, fopen successful 

    // set g_width and g_height 
    parseHeader(inFile); 

    // malloc space for the array (example given in assignment write-up) 
    struct pixel * pImage; 
    if(NULL == (pImage = malloc(sizeof(struct pixel) * g_width * g_height))) 
    { // then, malloc failed 
     perror("malloc failed for image size"); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, malloc successful 

    // parseImage function call here 
    parseImage(inFile, image); 

    fclose(inFile); // cleanup 

    if(2 > arvc) 
    { // then not enough parameters given on command line 
     printf("format is: %s followed by a number in the range 1..3\n", 
       argv[0]); 
     exit(EXIT_FAILURE); 
    } 

    // implied else, valid command line input 

     // manipulate the image according to command-line parameter 
     //    1: mirror image 
     //    2: upside down image 
     //    3: rotate to the right 90 degrees 

    switch(atoi(argv[1])) 
    { 
     case 1: 
      my_Mirror(pImage); 
      break; 

     case 2: 
      my_Flip(pImage); 
      break; 

     case 3: 
      rotate(pImage); 
      break; 

     default: 
      printf("invalid command line parameter\n"); 
      printf("parameter must be in range 1..3 inclusive\n"); 
      printf("exiting\n"); 
      free(pImage); // cleanup 
      exit(EXIT_FAILURE); 
      break; 
    } // end switch 

    print(image); 

    free(pImage); // cleanup 
    return 0; 
} // end function: main 


void my_Mirror(struct pixel a[]) 
{ 
    int col,row; 
    struct pixel temp; 

    // note: following works irregardless if even or odd number of columns 
    for(row = 0; row < g_height; ++row) //step through rows 
    { 
     for(col = 0; col < (g_width/2); col++) // step through first half of columns 
     { 
      // perform swap 
      memcpy(temp, a[(row * g_width) + col], sizeof(struct pixel)); 
      memcpy(a[(row * g_width) + col], a[((row+1)*g_width) - (1 + row)], sizeof(struct pixel)); 
      memcpy(a[((row+1)*g_width) - (1 + col)], temp, sizeof(struct pixel)); 
     } // end for 
    } // end for 
} // end function: my_Mirror 
+0

Вы можете фактически скопировать пиксельные структуры с регулярными назначениями, а не 'тетсра()'. – Dmitri

+0

@ Jongware, я также предоставлял свою функцию горизонтального сдвига, которая работает до вызова функции зеркала, потому что она работает аналогично. Я надеюсь, что это поможет продолжить расследование, потому что я нахожусь в полной потере –

+0

Обновляйте парней, я, будучи глупым, на самом деле не понимал, что функция зеркала работает так, как вызывается в функции флип. Так должно быть что-то не так, как я называю это в моей основной –

Смежные вопросы