如何交换像素以镜像图像c++

How to Swap pixels to mirror an image c++

本文关键字:镜像 图像 c++ 像素 何交换 交换      更新时间:2023-10-16

我有一个灰度图像(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];
        }
    }
}

它围绕中心镜像图像,因此左手侧是原始图像的一半,右手侧是镜像图像的一半。

首先,您对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;
    }
}