Qt 的QImage 像素操作

QRgb QImage::pixel(const QPoint &position) const
Returns the color of the pixel at the given position.
If the position is not valid, the results are undefined.
Warning: This function is expensive when used for massive pixel manipulations. Use constBits() or constScanLine() when many pixels needs to be read.
See also setPixel(), valid(), constBits(), constScanLine(), and Pixel Manipulation.

⚠️ 警告:性能问题

"Warning: This function is expensive when used for massive pixel manipulations."

⚠️ (警告: 该函数在大规模像素操作时代价昂贵)

为什么 pixel(x, y) 慢?

  • QImage::pixel() 需要内部做格式转换,以适配不同的 QImage 存储格式(如 Format_RGB32, Format_Indexed8)。
  • 它是逐像素操作每次调用都会执行额外的安全检查,因此在循环中大量使用时会变慢

如何优化?
  • 如果你需要访问大量像素(如遍历整个图片),推荐使用 constBits()constScanLine() 直接访问原始数据:

const uchar *data = image.constBits();
int bytesPerLine = image.bytesPerLine();

for (int y = 0; y < image.height(); ++y) {
    const QRgb *line = reinterpret_cast<const QRgb *>(data + y * bytesPerLine);
    for (int x = 0; x < image.width(); ++x) {
        QRgb pixelColor = line[x];  // 直接访问像素
        int r = qRed(pixelColor);
        int g = qGreen(pixelColor);
        int b = qBlue(pixelColor);
    }
}

 这样访问像素比 pixel(x, y) 快很多,因为它直接操作数据缓冲区,避免了函数调用开销。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值