I want to colorcode a numpy 2d-Array which contains values from 0-255 (grayscale). E.g. 0-150 colorcoded with rgb red (255,0,0) and 151-255 colorcoded blue (0,0,255).
After i did that the new Array with colorcoding shall be convertet to QImage (that is working) and convert that to QPixmap. The QPixmap then should be displayed with Pyqt.
My Problem, i cant convert the QImage to QPixmap after colorcoding. When i convert the 2d grayscale Array to Qimage to QPixmap it is working that way.
I also looked up if theres a way to use opencv or other libraries to colorcode my array, but didnt find anything.
import sys
import numpy as np
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QImage, QPixmap
def apply_color_coding(ndarray):
height, width = ndarray.shape
color_image = np.zeros((height, width, 3), dtype=np.uint8)
color_image[ndarray <= 100] = [0, 0, 255] # Blau
color_image[(ndarray > 100) & (ndarray <= 200)] = [0, 255, 0] # Grün
color_image[ndarray > 200] = [255, 0, 0] # Rot
return color_image
def array_to_pixmap(array):
try:
height, width, channels = array.shape
bytes_per_line = channels * width
print(f"Picturesize: {width}x{height}, Channels: {channels}, Bytes per line {bytes_per_line}")
qimage = QImage(array.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
if qimage.isNull():
print("Error: QImage is null")
return None
print("QImage done")
pixmap = QPixmap.fromImage(qimage)
if pixmap.isNull():
print("Error: QPixmap is null")
return None
print("QPixmap done")
return pixmap
except Exception as e:
print(f"Error converting: {e}")
return None
class ImageDisplayWidget(QWidget):
def __init__(self, pixmap, parent=None):
super().__init__(parent)
self.setWindowTitle("Farbkodiertes Bild")
self.setGeometry(100, 100, pixmap.width(), pixmap.height())
label = QLabel(self)
label.setPixmap(pixmap)
layout = QVBoxLayout()
layout.addWidget(label)
self.setLayout(layout)
def main():
print("Start Main")
# Beispiel-ndarray erstellen
height, width = 300, 400
ndarray = np.random.randint(0, 256, (height, width), dtype=np.uint8)
print("colorcoding")
color_coded_image = apply_color_coding(ndarray)
print("Generate Pixmap")
pixmap = array_to_pixmap(color_coded_image)
if pixmap is None:
print("Error pixmap")
return
app = QApplication(sys.argv)
display_widget = ImageDisplayWidget(pixmap)
display_widget.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Patrick EpicKeks Rdig is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.