繁体   English   中英

在C中翻转PPM图像

[英]Flipping a PPM Image in C

较早前,我遇到的一个问题只是一个简单的错误,因此我希望大家对此一视同仁。

这是在C中

我必须水平翻转PPM图像,但是我当前的代码要么绘制了Segmentation Fault,要么实际上没有翻转任何东西。

我使用的绘制细分错误的代码是:

int a, b, x, y;
x = 3 * myPic->rows;
y = 3 * myPic->cols;
for(a = 0; a < (y / 2); a++) {
    for(b = 0; b < x; b++) {
        Pixel temp = myPic->pixels[a][b];
        myPic->pixels[a][b] = myPic->pixels[y - a - 1][b];
        myPic->pixels[y - a - 1][b] = temp;
    }
}
return myPic;

}

不返回任何更改的代码是:

int a, b, x, y;
for(a = 0; a < myPic->rows; a++) {
    for(b = 0; b < myPic->cols; b++) {
        Pixel temp = myPic->pixels[a][b];
        myPic->pixels[a][b] = myPic->pixels[myPic->cols - a - 1][b];
        myPic->pixels[myPic->cols - a - 1][b] = temp;
    }
}
return myPic;

因为PPM图像具有RGB值,所以我假设行和列的值应乘以3。 而且我认为,一路过关将导致它回到原始状态,因此我将宽度(列)除以二。 我被困住了,希望这是一个小错误,有人可以帮忙吗?

您的第一个代码是错误的,它超出了其边界访问数组。 您的第二个代码更好,尽管它可以翻转图像然后将其重新反射回去。

为了简单起见,行数是图片高度,列数是图片宽度,二维数组中的第一个索引是行选择(高度索引),第二个索引是列选择(宽度索引)。 水平翻转从左到右交换像素。 垂直翻转从上到下交换像素。

有了它,这应该是一个水平翻转

int row, col;
for(row = 0; row < myPic->rows; row++) {
    for(col = 0; col < myPic->cols / 2 ; col++) { /*notice the division with 2*/
        Pixel temp = myPic->pixels[row][col];
        myPic->pixels[row][col] = myPic->pixels[row][myPic->cols - col -1];
        myPic->pixels[row][myPic->cols - col -1] = temp;
    }
}
return myPic;

在内存中修改图像后,需要将其保存,或使用您正在使用的图形库重新绘制修改后的图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM