【问题标题】:Rotating a ppm image 90 degrees to the right in C在 C 中将 ppm 图像向右旋转 90 度
【发布时间】:2015-04-14 18:30:15
【问题描述】:

将 PPM 图像向右旋转时出现以下问题 结果图像中的前两行是黑色(或彩虹中的某种颜色)

这是设置图像缓冲区的代码(变量 g_Width 和 g_height 由函数设置)

struct pixel *image = malloc(sizeof(struct pixel) * g_width * g_height);

这是传入指针的函数

void rotate90(struct pixel *img) {
    int i, j, size, th;
    size = sizeof(struct pixel) * g_width * g_height;
    struct pixel *buffer = malloc(size);

    if (buffer == NULL) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < g_height; i++) {
        for (j=0; j < g_width; j++) {
            buffer[(g_height*j)+(g_height-i)] = img[(g_width*i) + j];
        }
    }

    //copy the buffer into the image pointer
    memcpy(img, buffer, size);

    //free the buffer and swap the width and height around
    free(buffer);
    th = g_height;
    g_height = g_width;
    g_width = th;
}

如果我打印图像缓冲区,它会很好,但如果我旋转它,它会像这样(注意前 2 行像素)

https://www.dropbox.com/s/vh8l6s26enbxj42/t3.png?dl=0

好像最后两行根本没有被交换,请帮忙

编辑:我至少解决了第二条黑线,但我仍然需要帮助 最后一行

【问题讨论】:

  • 你必须初始化所有的缓冲区。例如buffer[0]没有设置。也许buffer[(g_height*j)+(g_height-i - 1)]
  • 做得很好,谢谢:)

标签: c image rotation ppm


【解决方案1】:

如前所述,您混合了第一行(并溢出)

void rotate90(struct pixel *img) {
    int i, j, size, th;
    size = sizeof(struct pixel) * g_width * g_height;
    struct pixel *buffer = malloc(size);

    if (buffer == NULL) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < g_height; i++) {
        for (j=0; j < g_width; j++) {
            buffer[(g_height*j)+(g_height-i -- 1)] = img[(g_width*i) + j];
        }
    }

    //copy the buffer into the image pointer
    memcpy(img, buffer, size);

    //free the buffer and swap the width and height around
    free(buffer);
    th = g_height;
    g_height = g_width;
    g_width = th;
}

【讨论】:

    【解决方案2】:

    这会将它旋转一种方式(删除不必要的括号)

    for (i=0; i<g_height; i++) {
        for (j=0; j<g_width; j++) {
            buffer[g_height * j + i] = img[g_width * i + j];
        }
    }
    

    但是您的代码建议您使用另一种方式,并且代码缺少-1,导致在一个边缘剪裁一条线,在另一边缘剪裁一条未定义的线。

    for (i=0; i<g_height; i++) {
        for (j=0; j<g_width; j++) {
            buffer[g_height * j + g_height - i - 1] = img[g_width * i + j];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多