pyqtgraph scatter plot in PySide2 swaps red and blue

Viewed 14

I'm using a PNG image as a background to a scatter plot, but the import somehow swaps red and blue. I can 'fix' it by swapping red and blue for each pixel, but that's not a proper solution. Does anyone know what goes wrong here?

See code below:

import sys
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout,
)
from PySide2.QtGui import (
    QImage
)
import pyqtgraph as pg


class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("RGB Issue")
        self.setGeometry(100, 100, 600, 200)
        # set up widgets
        self.add_widgets()
        # show widgets
        self.show()

    def add_widgets(self):
        # create a plot window
        plot = pg.plot()
        # add an image
        img = QImage('flowers.png')
        # convert to a format imageToArray accepts
        img = img.convertToFormat(QImage.Format_ARGB32_Premultiplied)
        img_array = pg.imageToArray(img, copy=True)
        # ==> uncomment next line to swap red and blue
        # img_array = self.swap_red_and_blue(img_array)
        img_item = pg.ImageItem(img_array)
        # push image back so it ends up behind the spots in the plot
        img_item.setZValue(-100)
        plot.addItem(img_item)
        # create a layout for our widget
        layout = QVBoxLayout()
        # our central widget
        widget = QWidget()
        # set widget layout
        widget.setLayout(layout)
        layout.addWidget(plot)
        self.setCentralWidget(widget)

    def swap_red_and_blue(self, img_array):
        # swap red and blue for each pixel
        for r in img_array:
            for c in r:
                c0old = c[0]  # get red value
                c1old = c[1]  # get green value
                c2old = c[2]  # get blue value
                c[0] = c2old  # replace red with blue
                c[1] = c1old  # keep green
                c[2] = c0old  # replace blue with red
                # c[3] = 255  # set alpha to opaque
        return img_array


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

This is the original image:

original image

This is the output I get:

imported image

I get the correct output if I call method swap_red_and_blue for each pixel in the code above.

0 Answers
Related