水平翻转数组
Horizontally flipping an array?
我正在尝试将一个 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
那个"乱码"看起来像是用错误的x大小绘制的图像。 您似乎已经交换了 numRows 和 numCols。 PGM 格式首先将大小定义为宽度,然后定义为高度。 您将 WIDTH 表示为图片的列。
负数起作用的原因是您以相同的顺序将像素写回去,所以没关系。 任何你真正关心像素位置的东西都是错误的。
请改为执行以下操作:
pgmIn >> numCols >> numRows >> magicNumber;
从代码行:
tmp = picture[row][col];
picture[row][col] = picture[numRows - 1 - row][col];
picture[numRows -1 - row][col] = tmp;
我会说:你正在用底部像素交换顶部像素,将顶部 1 与底部像素交换,依此类推。你说你想用右像素交换左边的像素。您的行应如下所示:
tmp = picture[row][col];
picture[row][col] = picture[row][numCols - 1 - col];
picture[row][numCols - 1 - col] = tmp;
试试这个,它可以解决你的问题。也许您没有看到它,因为您的图像具有相同的顶部和底部?大多数情况下,当具有图像处理代码时,最好包含图像(结果和输入)。
这个:
picture[row][col] = picture[numRows - 1 - row][col];
picture[numRows -1 - row][col] = tmp;
应该是这样的:
picture[row][col] = picture[row][numCols - 1 - col];
picture[row][numCols - 1 - col] = tmp;
而且您将需要遍历一半的列,否则您将再次切换所有内容。
for (int col = 0; col < numCols / 2; col++)
你只需要遍历数组的一半。否则,您将交换两次元素!
我可能会做这样的事情:
#include <algorithm>
void hflip()
{
for(int row = 0; row < numRows; ++row)
std::reverse(picture[row], picture[row] + numCols);
}
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 如何从上到下翻转 2D 数组?
- 如何翻转数组的一部分
- 如何翻转数组中的某些数字
- 水平翻转数组
- 通过翻转单元格组来用零填充二维数组
- 使用指针翻转数组