Skip to content Skip to sidebar Skip to footer

How To Configure Color When Convert Cv2 Numpy Array To Qimage?

The program is based on pyqt and opencv. I plan to read and process image with opencv while using QT as GUI. when I open a gray image, The result is OK. But it will change the col

Solution 1:

You need to convert the image data from BGR to RGB. You also need to swap width and height (see below) -- your code only works for images with same width and height.

self.cv_img = cv2.imread(cvfilename)

ifself.cv_img != None:
    # Notice the dimensions.
    height, width, bytesPerComponent = cv_img.shape
    bytesPerLine = bytesPerComponent * width;

    cv2.imshow("Show Image with Opencv", self.cv_img)

    # Convert to RGB for QImage.
    cv2.cvtColor(self.cv_img, cv.CV_BGR2RGB, self.cv_img)

    self.image = QImage(self.cv_img.data, width, height, bytesPerLine, QImage.Format_RGB888)

Solution 2:

I know this is pretty old thread, but for me cv2.cvtColor works really slow. I found another function that may help those who will need in the future (took me forever to find this remedy):

def cv2_to_qimage(cv_img):

    height, width, bytesPerComponent = cv_img.shape
    bgra = np.zeros([height, width, 4], dtype=np.uint8)
    bgra[:, :, 0:3] = cv_img
    return QtGui.QImage(bgra.data, width, height, QtGui.QImage.Format_RGB32)

Hope you'll find it useful

Solution 3:

Below code has color-filter update for openCV3.x versions. Code example comes from hluk.

import cv2
from cv2 import CV

...<snippet>...

self.cv_img = cv2.imread(cvfilename)

if self.cv_img != None:
    # Notice the dimensions.
    height, width, bytesPerComponent = cv_img.shape
    bytesPerLine = bytesPerComponent * width;

    cv2.imshow("Show Image with Opencv", self.cv_img)

    # Convert to RGB for QImage.
    cv2.cvtColor(self.cv_img, cv2.COlOR_BGR2RGB, self.cv_img)

    self.image = QImage(self.cv_img.data, width, height, bytesPerLine, QImage.Format_RGB888)

Post a Comment for "How To Configure Color When Convert Cv2 Numpy Array To Qimage?"