我已经知道如何垂直或水平翻转图像。我有以下水平执行此操作的代码。这里的图像数据存储在 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);
}
}
}
我确信有更快的方法来完成它。但是,我不想在堆上分配任何内存。您能告诉我还有哪些其他更快的算法吗?
谢谢。
最佳答案
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]);
}
}
}
关于 QImage
和 qRgb()
,您可能还注意到 Qt 支持每个组件 16 位的 QImage
(自 Qt 5.12 起) .
我在这方面做了一些改动
SO: Set pixel value of 16 bit grayscale QImage
这可能也很有趣。
关于c++ - 更快的图像镜像算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57110505/