Qt 的QImage 像素操作

农民  金牌会员 | 2025-2-16 16:38:24 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 873|帖子 873|积分 2619

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() 直接访问原始数据:
  1. const uchar *data = image.constBits();
  2. int bytesPerLine = image.bytesPerLine();
  3. for (int y = 0; y < image.height(); ++y) {
  4.     const QRgb *line = reinterpret_cast<const QRgb *>(data + y * bytesPerLine);
  5.     for (int x = 0; x < image.width(); ++x) {
  6.         QRgb pixelColor = line[x];  // 直接访问像素
  7.         int r = qRed(pixelColor);
  8.         int g = qGreen(pixelColor);
  9.         int b = qBlue(pixelColor);
  10.     }
  11. }
复制代码
 这样访问像素比 pixel(x, y) 快许多,因为它直接操作数据缓冲区,避免了函数调用开销。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

农民

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表