gpt4 book ai didi

c++ - 如何访问呈现在屏幕上的原始小部件像素?

转载 作者:行者123 更新时间:2023-12-03 07:11:57 25 4
gpt4 key购买 nike

我试图从每一帧中提取像素数据,但是当我尝试获取 pixmap 时它返回空值。我认为像素图会返回屏幕上的实际像素数据,类似于 glReadPixels但我想我错了。我认为这是为了访问 setPixmap 结果的像素图.
有没有办法访问屏幕上呈现的原始像素?在下面的示例中,“Hello World”呈现在屏幕上,我想要该标签的实际像素数据。

QWidget window;
window.resize(1280, 720);
window.show();
window.setWindowTitle(QApplication::translate("toplevel", "Top-Level Widget"));

QLabel *label = new QLabel(QApplication::translate("label", "Hello World"), &window);
label->move(500, 500);
label->raise();
label->show();
QPixmap pixmapVal = label->pixmap(Qt::ReturnByValue);

最佳答案

原因
QPixmap :

The QPixmap class is an off-screen image representation that can be used as a paint device


换句话说,它是一个绘图 Canvas ,与任何其他 Canvas 一样,如果您尚未在其上绘图,它将是空的。
另一方面 QLabel用作像素图的 View ,而不是其内容,以及当您尝试访问 label 的像素图时没有设置,它返回 null .
解决方案
当然,有一种方法可以制作小部件、您的案例中的标签、像素图的内容并访问像素数据。我解决这个问题的方法是这样的:
  • 创建一个空 pixmapwidget的大小您要访问的像素内容,例如:
     QPixmap pixmap(widget->size());

    pixmap.fill(Qt::transparent);
  • 使用 QWidget::render 将小部件的内容呈现到像素图上:
     widget->render(&pixmap);
  • 将像素图转换为 QImage并使用 QImage::pixel QImage::pixelColor (pixelX, pixelY) 处访问像素的 rgb 数据像这样:
     pixmap.toImage().pixelColor(pixelX, pixelY);

  • 例子
    这是我为您准备的一个示例,用于演示如何实现建议的解决方案:
    #include "MainWindow.h"
    #include <QApplication>
    #include <QLabel>
    #include <QDebug>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    QWidget w;
    auto *label = new QLabel(QObject::tr("Hello World"), &w);

    label->move(500, 500);
    label->raise();

    w.setWindowTitle(QObject::tr("Top-Level Widget"));
    w.resize(1280, 720);
    w.show();

    QPixmap pixmap(label->size());

    pixmap.fill(Qt::transparent);

    label->render(&pixmap);

    int pixelX = 10;
    int pixelY = 5;

    // Access image pixels
    qDebug() << pixmap.toImage().pixelColor(pixelX, pixelY);

    return a.exec();
    }
    结果
    对于 (10, 5) 处的像素该示例产生以下结果:

    QColor(ARGB 1, 0, 0, 0.156863)

    关于c++ - 如何访问呈现在屏幕上的原始小部件像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64710288/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com