PyQt / PySide: How to Convert QImage to OpenCV MAT Format

I am looking to create a function to convert QImage to OpenCV (CV2) Mat format inside PyQt.

How can I do it? My input images that I have worked with so far are PNGs (RGB or RGBA), which have been uploaded as QImage.

Ultimately, I want to take two QImages and use the matchTemplate function to find one image in another, so if there is a better way to do this than I find now, I am also open to it. But the ability to convert back and forth between them would be easy perfectly.

Thank you for your help,

+2
source share
2 answers

After a long search here, I found a gem that gave me a working solution. I got most of my code from this answer to another question: fooobar.com/questions/957834 / ...

The main problem I ran into was using the pointer correctly. The big thing that I think is missing is the setize function.

Here is my import:

import cv2 import numpy as np 

Here is 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 
+2
source

I tried the answer above, but could not get the expected result. I tried this rough 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 can delete the temporary image file created as soon as you are done with the file. This may not be the right method to do the job, but still does the required job.

0
source

Source: https://habr.com/ru/post/957821/


All Articles