2016-02-24 4 views
-1

Я изо всех сил пытаюсь понять, почему это не сработает. Я читал в изображении PPM и должен вращать его на 90 градусов, но ничего, что я пробовал, будет работать. Я почти уверен, что большинство моих проблем связаны с неправильным использованием указателей, особенно в контексте итерации массива 1d.Вращение изображения PPM 90 градусов в C

/** rotate.c 

    CpSc 2100: homework 2 

    Rotate a PPM image right 90 degrees 

**/ 
#include "image.h" 

typedef struct pixel_type 
{ 
    unsigned char red; 
    unsigned char green; 
    unsigned char blue; 
} color_t; 


image_t *rotate(image_t *inImage) 
{ 
    image_t *rotateImage; 
    int rows = inImage->rows; 
    int cols = inImage->columns; 
    color_t *inptr; 
    color_t *outptr; 
    color_t *pixptr; 
    int width = rows; 
    int height = cols; 
    int i, k; 

    /* malloc an image_t struct for the rotated image */ 
    rotateImage = (image_t *) malloc(sizeof(image_t)); 
    if(rotateImage == NULL) 
    { 
     fprintf(stderr, "Could not malloc memory for rotateImage. Exiting\n"); 
    } 



    /* malloc memory for the image itself and assign the 
     address to the image pointer in the image_t struct */ 
    rotateImage -> image = (color_t *) malloc(sizeof(color_t) * rows * cols); 
    if(rotateImage -> image == NULL) 
    { 
     fprintf(stderr, "Could not malloc memory for image. Exiting\n"); 
    } 

    /* assign the appropriate rows, columns, and brightness 
     to the image_t structure created above    */ 
    rotateImage -> rows = cols; 
    rotateImage -> columns = rows; 
    rotateImage -> brightness = inImage -> brightness; 

    inptr = inImage -> image; 
    outptr = rotateImage -> image; 

    /* write the code to create the rotated image   */ 
    for(i = 0; i<height; i++) 
    { 
     for(k = 0; k<width; k++) 
     { 
      outptr[(height * k)+(height-i - 1)] = inptr[(width*i)+k]; 

     } 


    } 
    rotateImage -> image = outptr; 
    return(rotateImage); 
} 
+0

Может быть, вы могли бы описать то, что код делает сейчас и как это зависит от ваших ожиданий. –

+0

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

+0

[не выдавать результат malloc в C] (http://stackoverflow.com/q/605845/995714) –

ответ

0

попробовать это:

#define COORD_INDEX(x ,y , w) (x+ (y*w)) // w for width 

... 

    /* for clarity use x,and y */ 
    for(y = 0; i < height; i++) 
    { 
     for(x = 0; x < width; k++) 
     { 
      outptr[COORD_INDEX(y,x,height) ] = inptr[COORD_INDEX(x,y,width)]; 

     } 
... 

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