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) 快许多,因为它直接操作数据缓冲区,避免了函数调用开销。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |