将PPM图像旋转90度(以C为单位)

时间:2016-02-24 01:28:37

标签: c

我正在努力弄清楚为什么这不起作用。我在PPM图像中读取并且必须将其旋转90度但我尝试过的任何东西都无法工作。我很确定我的大多数问题都源于指针的不正确使用,尤其是在1d数组迭代上下文中。

/** 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);
}

1 个答案:

答案 0 :(得分: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)];

        }
... 

    }