Skip to content

Instantly share code, notes, and snippets.

@llandsmeer
Created May 28, 2022 11:25
Show Gist options
  • Save llandsmeer/f0dd5c8e56afdf2202b73f78e170fa6f to your computer and use it in GitHub Desktop.
Save llandsmeer/f0dd5c8e56afdf2202b73f78e170fa6f to your computer and use it in GitHub Desktop.
pyqt5 show numpy arrays in a loop
import sys
import numpy as np
from PyQt5 import QtGui, QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.imshow = Grayscale()
self.setCentralWidget(self.imshow)
self.update_timer = QtCore.QTimer()
self.update_timer.timeout.connect(self.on_update)
self.update_timer.start(100)
def on_update(self):
x = np.random.random((100, 100))
self.imshow.imshow(x)
class Grayscale(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.data = None
self.imshow(np.random.random((100, 100)))
self.setGeometry(100, 100, 800, 800)
def imshow(self, x, vmin=None, vmax=None):
if vmin is None:
vmin = x.min()
if vmax is None:
vmax = x.max()
if self.data is None or x.shape != self.data.shape:
self.data = np.empty((x.shape[0], x.shape[1], 3), dtype=np.uint8)
x = (255 * (x - vmin) / (vmax - vmin)).astype(np.uint8)
self.data[:,:,0] = x
self.data[:,:,1] = x
self.data[:,:,2] = x
self.img = QtGui.QImage(self.data.data,
self.data.shape[0],
self.data.shape[1],
3*self.data.shape[1],
QtGui.QImage.Format_RGB888)
self.update()
def paintEvent(self, event):
geom = self.frameGeometry()
w, h = geom.width(), geom.height()
if w < h:
rect = QtCore.QRect(0, (h - w)//2, w, w)
else:
rect = QtCore.QRect((w - h)//2, 0, h, h)
painter = QtGui.QPainter(self)
painter.drawImage(rect, self.img)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment