PyQt/PySide: How do I convert QImage into OpenCV's MAT format

后端 未结 2 552
广开言路
广开言路 2021-01-03 09:04

I\'m looking to create a function for converting a QImage into OpenCV\'s (CV2) Mat format from within the PyQt.

How do I do this? My input images I\'ve been working

相关标签:
2条回答
  • 2021-01-03 09:41

    After much searching on here, I found a gem that got me a working solution. I derived much of my code from this answer to another question: https://stackoverflow.com/a/11399959/1988561

    The key challenge I had was in how to correctly use the pointer. The big thing I think I was missing was the setsize function.

    Here's my imports:

    import cv2
    import numpy as np
    

    Here's my function:

    def convertQImageToMat(incomingImage):
        '''  Converts a QImage into an opencv MAT format  '''
    
        incomingImage = incomingImage.convertToFormat(4)
    
        width = incomingImage.width()
        height = incomingImage.height()
    
        ptr = incomingImage.bits()
        ptr.setsize(incomingImage.byteCount())
        arr = np.array(ptr).reshape(height, width, 4)  #  Copies the data
        return arr
    
    0 讨论(0)
  • 2021-01-03 09:51

    I tried the answer given above, but couldn't get the expected thing. I tried this crude method where i saved the image using the save() method of the QImage class and then used the image file to read it in cv2

    Here is a sample code

    def qimg2cv(q_img):
        q_img.save('temp.png', 'png')
        mat = cv2.imread('temp.png')
        return mat
    

    You could delete the temporary image file generated once you are done with the file. This may not be the right method to do the work, but still does the required job.

    0 讨论(0)
提交回复
热议问题