PyQt/PySide:如何将QImage转换为OpenCV的MAT格式 [英] PyQt/PySide: How do I convert QImage into OpenCV's MAT format
问题描述
我正在寻求创建一个函数,用于从PyQt内部将QImage转换为OpenCV(CV2)Mat格式.
I'm looking to create a function for converting a QImage into OpenCV's (CV2) Mat format from within the PyQt.
我该怎么做?到目前为止,我一直在使用的输入图像是作为QImage加载的PNG(RGB或RGBA).
How do I do this? My input images I've been working with so far are PNGs (either RGB or RGBA) that were loaded in as a QImage.
最终,我想获取两个QImage并使用matchTemplate函数在另一个图像中查找一个图像,因此,如果有比现在找到的更好的方法,我也很乐意.但是能够轻松地在两者之间来回转换将是理想的.
Ultimately, I want to take two QImages and use the matchTemplate function to find one image in the other, so if there is a better way to do that than I'm finding now, I'm open to that as well. But being able to convert back and forth between the two easily would be ideal.
感谢您的帮助,
推荐答案
在这里进行了大量搜索之后,我发现了一个可以为我提供有效解决方案的宝石.我从这个答案的另一个问题得到了很多代码: https://stackoverflow.com/a/11399959/1988561
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
我遇到的主要挑战是如何正确使用指针.我想我最想念的是setsize函数.
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.
这是我的进口货
import cv2
import numpy as np
这是我的职能:
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
这篇关于PyQt/PySide:如何将QImage转换为OpenCV的MAT格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!