[英]raw image display in qt with 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
還有這個:
def array2Pixmap(arr):
arr_uint8 = arr.astype(numpy.uint8)
im8 = Image.fromarray(arr_uint8)
imQt = QtGui.QImage(ImageQt.ImageQt(im8))
pix = QtGui.QPixmap.fromImage(imQt)
return pix
所以現在我正在尋找一種以正確的方式顯示圖像的方法。 你知道我做錯了什么嗎?
謝謝
編輯
這是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')
顯示圖像,它可以工作,圖像在編輯器中顯示如下:
但當我將其轉換為QPixmap時,結果與之前相同。
奇怪的是,當我使用arr_uint8 = arr.view(dtype=numpy.uint8)
轉換為8位時,結果是一個2048 * 4096而不是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)
我沒有測試過這個,但它應該給你足夠的信息繼續。
我找到了解決方案。 實際上,@ user545424的解決方案不起作用,因為我使用的是PyQt5,並且不支持圖像格式Format_RGBA64。 我試圖安裝PySide2,但它沒有用,所以經過一些研究,我發現這篇文章: 將16位灰度轉換為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像素,所以一段時間后執行速度變慢。 我會試着找出原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.