用python在qt中显示原始图像

2024-09-30 02:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一个python程序从科学相机上获取图像。这部分没问题,我可以得到一个数组中的16位图像。当我想在qt窗口中显示图像时(我使用的是QGraphicsWindow),图像的显示方式非常奇怪。为了显示图像,我将2d数组转换为pixmap,然后将其分解。我尝试了不同的方法,但以下代码得到了最好的结果:

def array2Pixmap(arr):
arr_uint8 = arr.view(dtype=numpy.uint8)
im8 = Image.fromarray(arr_uint8)
imQt = QtGui.QImage(ImageQt.ImageQt(im8))
pix = QtGui.QPixmap.fromImage(imQt)
return pix

结果如下:enter image description here

还有这个:

^{pr2}$

在完全相同的拍摄条件下(相机曝光时间、光强度等…): enter image description here

所以现在我在寻找一种正确显示图像的方法。你知道我做错了什么吗?在

谢谢

编辑

下面是一个arr的例子,命令print(arr)返回

[[100  94  94 ...  97  98  98]
[ 97 100  98 ...  98 101  99]
[100  95  98 ... 104  98 102]
...
[ 98  98  98 ...  96  98 100]
[ 94 100 102 ...  92  98 104]
[ 97  90  96 ...  96  97 100]]

返回一个print(type(arr))

<class 'numpy.ndarray'>

编辑

好吧,我有一些消息。 我更改了代码,现在转换为8位数组id的过程如下:

arr = numpy.around(arr*(2^8-1)/(2^16-1))
arr_uint8 = arr.astype(numpy.uint8)

如果我使用matplotlib.pyplot.imshow(arr, cmap='gray')显示图像,它可以工作,图像在编辑器中显示如下:

enter image description here

但是当我把它转换成QPixmap时,结果和以前一样。在

奇怪的是,当我使用arr_uint8 = arr.view(dtype=numpy.uint8)转换为8位时,结果是2048*4096的数组,而不是2048*2048。我不明白为什么。。。在


Tags: 方法代码图像numpyview数组arrdtype
2条回答

我找到了解决办法。事实上,@user545424的解决方案不起作用,因为我使用的是PyQt5,并且不支持图像格式\u RGBA64。我试图安装PySide2,但它不起作用,所以经过一番研究,我发现了这篇文章:Convert 16-bit grayscale to QImage 答案中提出的解决方案非常有效。下面是我用来显示16位图像的代码:

from PyQt5 import QtGui
import numpy as np

def array2Pixmap(img):
    img8 = (img/256.0).astype(np.uint8) 
    img8 = ((img8 - img8.min()) / (img8.ptp() / 255.0)).astype(np.uint8)
    img = QtGui.QImage(img8.repeat(4), 2048, 2048, QtGui.QImage.Format_RGB32)

    pix = QtGui.QPixmap(img.scaledToWidth(img.width()*2))
    return pix

这段代码可以工作,我有一个很好的图像,但现在我必须处理32位图像2048*2048像素,因此执行速度在一段时间后会变慢。我会找出原因的。在

所以,尽管你没有在问题中说出来,我还是假设你的图像格式是16位灰度。在

看一下这里的格式类型:https://doc.qt.io/Qt-5/qimage.html#Format-enum这不是一种受支持的格式,因此您必须将其更改为可以显示的格式。在

RGB64格式允许每种颜色16位,这对于您所拥有的值足够分辨率:

from PySide import QtGui, QPixmap

def array_to_pixmap(arr):
    """Returns a QPixmap from a 16 bit greyscale image `arr`."""

    # create a local variable arr which is 64 bit so we can left shift it
    # without overflowing the 16 bit original array
    arr = arr.astype(np.int64)

    # pack the 16 bit values of arr into the red, green, and blue channels
    rgb = arr << 48 | arr << 32 | arr << 16 | 0xffff
    im = QtGui.QImage(rgb, rgb.shape[0], rgb.shape[1], QtGui.QImage.Format_RGBA64)
    return QtGui.QPixmap.fromImage(im)

我还没有测试过,但它应该能给你足够的信息来继续。在

相关问题 更多 >

    热门问题