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

后端 未结 2 572
广开言路
广开言路 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
    

提交回复
热议问题