2016-02-24 153 views
-1

我正在努力弄清楚为什么这不起作用。我读了PPM图像,必须将其旋转90度,但没有任何我已经尝试过的。我很确定,我的大部分问题都是由于指针的使用不当造成的,特别是在1d数组迭代上下文中。在C中旋转PPM图像90度

/** 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

[不要在C中投入malloc的结果](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)]; 

     } 
... 

    }