我正在尝试将一个 pgm 文件 [只是一个像素矩阵,设置行和设置列] 放入一个数组中,水平翻转它,然后再次输出。这就是我阅读它的方式:
bool PgmPicture::readPgmFile(string inputFile)
{
stringstream ss;
string line = "";
int magicNumber;
ifstream pgmIn;
pgmIn.open(inputFile.c_str());
if (pgmIn.fail()) { //makes sure that itemList opened okay.
perror(inputFile.c_str());
return false;
}
getline(pgmIn,line);
pgmIn >> numRows >> numCols >> magicNumber;
for(int row = 0; row < numRows ; row++) {
for (int col = 0; col < numCols ; col++) {
pgmIn >> picture[row][col]; //this array only contains pixel values, no headers or flags.
}
}
return true;
}
所以基本上,图片的第二行包含 2 个值:行和列。例如,300 和 500 表示图片有 300 行和 500 列。如您所见,上面的函数将该行读入 numRows 和 numCols。
在后面的函数中,我试图通过交换像素对来水平翻转图片(例如,最右边的像素与第一个像素,最右边的像素减去第一个像素 + 1 等到中间。 )
这是我的功能:
void PgmPicture::hflip(){
int tmp;
for(int row = 0; row < numRows ; row++) {
for (int col = 0; col < numCols ; col++) {
tmp = picture[row][col];
picture[row][col] = picture[numRows - 1 - row][col];
picture[numRows -1 - row][col] = tmp;
}
}
}
这有什么问题?它只是输出与原始图片完全相同的图片。它应该像我描述的那样逐行切换每个元素。你们能不能用新鲜的眼光来看看这个?我已经追踪了一段时间,但我无法弄清楚。
编辑: 我将代码更改为:
int tmp;
for(int row = 0; row < numRows ; row++) {
for (int col = 0; col < numCols/2 ; col++) {
tmp = picture[row][col];
picture[row][col] = picture[row][numCols - 1 - col];
picture[row][numCols - 1 - col] = tmp;
}
}
我只是得到一个乱码。这是原件: http: //i493.photobucket.com/albums/rr294/Jamlegend/mammoth_zps31b72d88.png 和后面的图片:http: //i493.photobucket.com/albums/rr294/Jamlegend/after_zpsdf1a8b40.png