Important: Please read the Qt Code of Conduct -

Numpy array (gray scale) to QPixmap

  • My input image is at grayscale, i.e., cv_image_array, which is a numpy array.
    I can successfully save it at as

    cv2.imwrite('gray.jpg', cv_image_array)

    or display it as

    cv2.imshow("Image", cv_image_array)

    However, I want to display it directly on the UI

    I did:

    h, w = 320, 240
    q_img = QImage(cv_image_array, w, h, w, QImage.Format_Grayscale8)
    q_pixmap = QPixmap.fromImage(gray_img).scaled(h,w)

    However, the displayed image is broken and different from the one using cv2 commands
    I tried a lot of time but I cannot find a solution.
    Could someone please suggest some ideas to solve this?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Are you sure the image is stored as a single channel and not RGB with only gray colors ?

  • Hi, i recently get into same problem also, what i did to solve is i changed the grayscale to color and replace frame.flatten() with and add bytesPerLine

    I write it down here just in case someone need this. : - )

    if len(cv_img.shape)<3:
        frame = cv2.cvtColor(cv_img, cv2.COLOR_GRAY2RGB)
        frame = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
    h, w = cv_img.shape[:2]
    bytesPerLine = 3 * w
    qimage = QImage(, w, h, bytesPerLine, QImage.Format.Format_RGB888) 
    #qimage = QImage(frame.flatten(), w, h, QImage.Format_RGB888)

Log in to reply