【问题标题】:How can access to pixel data with PYQt' QImage scanline()如何使用 PYQt' QImage scanline() 访问像素数据
【发布时间】:2012-07-06 18:47:34
【问题描述】:

我需要使用 PyQt4 访问 qimage 对象中的像素数据。

.pixel() 太慢了,所以文档说要使用 scanline() 方法。

在 c++ 中,我可以获取 scanline() 方法返回的指针,并从缓冲区读取/写入像素 RGB 值。

使用 Python,我获得了指向像素缓冲区的 SIP voidptr 对象,因此我只能使用 bytearray 读取像素 RGB 值,但无法更改原始指针中的值。

有什么建议吗?

【问题讨论】:

    标签: pointers pyqt4 pixel qimage python-sip


    【解决方案1】:

    这里有一些例子:

    from PyQt4 import QtGui, QtCore
    img = QtGui.QImage(100, 100, QtGui.QImage.Format_ARGB32)
    img.fill(0xdeadbeef)
    
    ptr = img.bits()
    ptr.setsize(img.byteCount())
    
    ## copy the data out as a string
    strData = ptr.asstring()
    
    ## get a read-only buffer to access the data
    buf = buffer(ptr, 0, img.byteCount())
    
    ## view the data as a read-only numpy array
    import numpy as np
    arr = np.frombuffer(buf, dtype=np.ubyte).reshape(img.height(), img.width(), 4)
    
    ## view the data as a writable numpy array
    arr = np.asarray(ptr).reshape(img.height(), img.width(), 4)
    

    【讨论】:

    • 好问题;在列表中添加了另一个答案。
    • 老兄,你无法想象我在谷歌上搜索了多久。非常感谢。值得一提的是,最后一行创建了一个视图,而不是数据的副本。如果有人想创建 QImage 的副本,请在数组上调用 .copy()。另外,请注意格式。我需要获得 RGB,因此调用 arr[:, :, [0, 2]] = arr[:, :, [2, 0]] 之类的帮助
    • 非常好的解决方案。在 python 3.6 和 PySide6 中,setsizebyteCountasstringbuffer 不可用。可能需要改用img.bytePerLine() * img.height()memoryview
    • @Zézouille 请考虑添加新答案!
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 2015-11-10
    • 2013-11-20
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多