Display an image in a separate window

Hello. I am trying to display a grayscale OpenCV image in separate window, but no success so far. The code I am executing is as follows and causes Slicer to crash:

    height, width = image.shape
    qImg = qt.QImage(np.asarray(image), width, height, qt.QImage.Format_Grayscale8)
    pixmap = qt.QPixmap.fromImage(qImg)
    myLabel = qt.QLabel()
    myLabel.setPixmap(pixmap)
    myLabel.show()

Before this, I was successfully displaying the image using OpenCV imshow() method, but it also caused Slicer to crash when I tried to interact with it while maintaining the OpenCV window open.

Any suggestions? I am using Slicer 4.11.0-2019-09-01 r28473.

You can show a proper image viewer outside the view layout as shown here: https://www.slicer.org/wiki/Documentation/Nightly/ScriptRepository#Show_a_slice_view_outside_the_view_layout

If you want to convert a numpy array to QImage then I would recommend to use qimage2ndarray package:

try:
    import qimage2ndarray
except ImportError:
    pip_install('qimage2ndarray')
    import qimage2ndarray

import numpy as np
image = np.fromfunction(lambda i, j: i + j, (100, 100), dtype='uint8')
qImg = qimage2ndarray.array2qimage(image, normalize=True)
pixmap = qt.QPixmap.fromImage(qImg)
myLabel = qt.QLabel()
myLabel.setPixmap(pixmap)
myLabel.show()
1 Like