通过pyqt组件抓图拿到QImage图片对象后,有时候需要传给opencv相关对象进行其他处理,这时候就需要将QImage转换为opencv能够使用的格式,即MAT(numpy ndarray)
找了网上大神的成果,这里记录以下,用于以后温故。
思路是,拿到QImage指针,通过numpy从指针处填充数据:
#拿到指针
ptr = qimg.constBits()
#根据原图片的数据区长度,用setsize()设置区域
ptr.setsize(qimg.byteCount())
#Qimage内部是按照每个像素4个字节的方式组织数据的,即使最后一个alpha通道没有用,也用0xff来填充
mat = np.array(ptr).reshape(qimg.height(), qimg.width(), 4)
cv2.imshow("image", mat)
cv2.waitKey(0)
完毕
以下是别人的MAT转QImage的代码,暂时没用到,没研究,先抄写下来:
qimg=self.showScreenImgLabel.pixmap().toImage() #获取Qlabel图片
mat_img_temp=self.qimage2mat(qimg) #将Qimage转换为mat类型
mat_img=cv2.cvtColor(mat_img_temp, cv2.COLOR_BGR2RGB)#在对图像处理前 先转换为RGB类型 切记
#中值滤波
img_median = cv2.medianBlur(mat_img, 5)
gqimg=QImage(img_median.data, img_median.shape[1], img_median.shape[0],img_median.shape[1] * 3,
QImage.Format_RGB888).scaled(self.showProcessImgLabel.width(),
self.showProcessImgLabel.height())
self.showProcessImgLabel.setPixmap(QPixmap.fromImage(gqimg))