我有一张灰度图像(150 x 200),我需要围绕它的垂直轴镜像。
加载原始图像,然后调用我的函数,然后在ParrotMirror.png下保存新图像。但是,对于我的代码,图像没有镜像,任何人都可以解释我的代码有什么不正确之处吗?我们的想法是像素元素0与149交换,1与148交换,2与147交换...
#include <QCoreApplication>
#include <iostream>
#include "ImageHandle.h"
using namespace std;
int CountBlackPixels (unsigned char PixelGrid[WIDTH][HEIGHT]);
void InvertImage (unsigned char PixelGrid[WIDTH][HEIGHT]);
void ReducePixelLevel (unsigned char PixelGrid[WIDTH][HEIGHT]);
void MirrorImage (unsigned char PixelGrid[WIDTH][HEIGHT]);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
unsigned char PixelGrid[WIDTH][HEIGHT]; // Image loaded from file
// If the file "Parrot.png" cannot be loaded ...
if (!loadImage(PixelGrid, "Parrot.png"))
{
// Display an error message
cout << "Error loading file \"Parrot.png\"" << endl;
}
MirrorImage(PixelGrid);
{
if (saveImage(PixelGrid, "ParrotMirror.png"))
{
cout << "\nFile \"ParrotMirror.png\" saved successfully" << endl;
}
else
{
cout << "\nCould not save \"ParrotMirror.png\"" << endl;
}
}
return a.exec();
}
void MirrorImage (unsigned char PixelGrid[WIDTH][HEIGHT])
{
for (int row = 0; row < WIDTH; ++row)
{
int swapRow = WIDTH - 1 - row; // Mirror pixel
int col = 0;
PixelGrid[row][col] = PixelGrid[swapRow][col];
}
}
我只显示了与问题相关的部分代码,原始图像必须重新加载的原因是因为还有其他功能修改图像并保存。
编辑:这就是我现在的功能......
void MirrorImage (unsigned char PixelGrid[WIDTH][HEIGHT])
{
for (int row = 0; row < WIDTH; row++)
{
for (int col = 0; col < HEIGHT / 2; col++)
{
int swapRow = WIDTH - 1 - row; // Mirror pixel
unsigned char temp = PixelGrid[row][col];
PixelGrid[row][col] = PixelGrid[swapRow][col];
temp = PixelGrid[swapRow][col];
}
}
}
反映了关于中心的图像,因此左侧是原始图像的一半和镜像图像的右侧一半。
答案 0 :(得分:1)
首先,您对PixelGrid
的声明有点违反直觉。通常当你声明一个二维数组时,你会这样说:
unsigned char array[MAX_ROWS][MAX_COLUMNS];
这表明在你的情况下,声明会更直观地写成:
unsigned char PixelGrid[HEIGHT][WIDTH];
因此您可能希望查看这些维度或loadImage()
函数填充该数组的方式。
在垂直轴上镜像二维数组意味着交换每行的相应列,如下所示:
unsigned char arr[MAX_ROWS][MAX_COLUMNS];
for(int row = 0; row < MAX_ROWS; ++row) // go through all rows
{
for(int column = 0; column < MAX_COLUMNS / 2; ++column)
{
// each column from the first half is swapped
// with it correspondent from the second half
unsigned char tmp = arr[row][column];
arr[row][column] = arr[row][MAX_COLUMNS - column - 1];
arr[row][MAX_COLUMNS - column - 1] = tmp;
}
}