c++ - 更快的图像镜像算法

标签 c++ algorithm image-processing nested-loops

我已经知道如何垂直或水平翻转图像。我有以下水平执行此操作的代码。这里的图像数据存储在 QImage 中,因为我在这里使用 Qt。

QImage image(imageFileName);
QImage newImage(image);

if(image.depth() > 8)
{
    for (int idx_Y = 0; idx_Y < image.height(); idx_Y++)
    {
        for (int idx_X = 0; idx_X < image.width(); idx_X++)
        {
            QRgb rgb = image.pixel(image.width() - 1 - idx_X, idx_Y);
            newImage.setPixel(idx_X, idx_Y, rgb);
        }
    }
}

我确信有更快的方法来完成它。但是,我不想在堆上分配任何内存。您能告诉我还有哪些其他更快的算法吗?

谢谢。

最佳答案

详述@Spektres hint

2 nested for loops are not the problem... the setPixel and pixel functions are usually crawlingly slooow on most gfx APIs. Using direct pixel access instead usually boost speed ~1000 times or more ...

这看起来像:

QImage image(imageFileName);
QImage newImage(image);

if (image.depth() >= 8) {
  const int bytesPerPixel = image.depth() / 8;
  for (int y = 0; y < image.height(); ++y) {
    char *dataSrc = image.bits() + y * image.bytesPerLine();
    char *dataDst = newImage.bits() + y * newImage.bytesPerLine()
      + (newImage.width() - 1) * bytesPerPixel;
    for (int i = image.width(); i--;
      dataSrc += bytesPerPixel, dataDst -= bytesPerPixel) {
      for (int i = 0; i < bytesPerPixel; ++i) dataDst[i] = dataSrc[i];
    }
  }
}

请注意,我将 image.depth() > 8 更改为 image.depth() >= 8。 (我认为没有理由排除例如 QImage::Format_Grayscale8。)

用于就地镜像 QImage newImage 的稍微修改的版本(考虑到它已经被复制):

QImage image(imageFileName);
QImage newImage(image);

if (newImage.depth() >= 8) {
  const int bytesPerPixel = newImage.depth() / 8;
  for (int y = 0; y < image.height(); ++y) {
    char *dataL = newImage.bits() + y * newImage.bytesPerLine();
    char *dataR = dataL + (newImage.width() - 1) * bytesPerPixel;
    for (; dataL < dataR; dataL += bytesPerPixel, dataR -= bytesPerPixel) {
      for (int i = 0; i < bytesPerPixel; ++i) std::swap(dataL[i], dataR[i]);
    }
  }
}

关于 QImageqRgb(),您可能还注意到 Qt 支持每个组件 16 位的 QImage(自 Qt 5.12 起) .

我在这方面做了一些改动
SO: Set pixel value of 16 bit grayscale QImage
这可能也很有趣。

关于c++ - 更快的图像镜像算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110505/

相关文章:

python - 高级方形检测(带连接区域)

C++14 constexpr static const std::array 初始化

c++ - CComPtr 和 std::shared_ptr 互操作性

database - BDB,如何按指定顺序获取主键?

python-3.x - Pytorch:图像标签

python - 从图像中的绝对点创建相对点网格

c++ - 如何在不依赖 numpy.i 的情况下使用指针将 numpy 数组传递给 C++/SWIG?

c++ - 单击关闭控制台窗口以结束 C++ 控制台程序是正确的方法吗?

arrays - 多数组的笛卡尔积

c# - 算法:分析网页的标签