提前约定:
pixmap是QPixmap类型的变量
image是QImage类型的变量
QPixmap=>QImage
image = pixmap.toImage()
QImage=>QPixmap
pixmap=QPixmap.fromImage(image)
Opencv=>Qimage
方法一:
def Opencv2QImage(opencv_img):
width = opencv_img.shape[1] #获取图片宽度
height = opencv_img.shape[0] #获取图片高度
pixmap = QPixmap(width, height) #根据已知的高度和宽度新建一个空的QPixmap,
image = pixmap.toImage() #将pximap转换为QImage类型的qimg
#循环读取cv_image的每个像素的r,g,b值,构成qRgb对象,再设置为qimg内指定位置的像素
for row in range(0, height):
for col in range(0,width):
b = opencv_img[row,col,0]
g = opencv_img[row,col,1]
r = opencv_img[row,col,2]
pix = qRgb(r, g, b)
image.setPixel(col, row, pix)
return image #转换完成,返回
方法二
def OpencvToQImage(data):
# 8-bits unsigned, NO. OF CHANNELS=1
if data.dtype == np.uint8:
channels = 1 if len(data.shape) == 2 else data.shape[2]
if channels == 3: # CV_8UC3
# Copy input Mat
# Create QImage with same dimensions as input Mat
img = QImage(data, data.shape[1], data.shape[0], data.strides[0], QImage.Format_RGB888)
return img.rgbSwapped()
elif channels == 1:
# Copy input Mat
# Create QImage with same dimensions as input Mat
img = QImage(data, data.shape[1], data.shape[0], data.strides[0], QImage.Format_Indexed8)
return img
else:
print("ERROR: numpy.ndarray could not be converted to QImage. Channels = %d" % data.shape[2])
return QImage()
方法三(推荐):
def Opencv2QImage(cvimg):
height, width, depth = cvimg.shape
cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB)
cvimg = QImage(cvimg.data, width, height, width * depth, QImage.Format_RGB888)
return cvimg
Qimage=>Opencv
def QImage2Opencv(qimg):
tmp = qimg
#使用numpy创建空的图象
cv_image = numpy.zeros((tmp.height(), tmp.width(), 3), dtype=numpy.uint8)
for row in range(0, tmp.height()):
for col in range(0,tmp.width()):
r = qRed(tmp.pixel(col, row))
g = qGreen(tmp.pixel(col, row))
b = qBlue(tmp.pixel(col, row))
cv_image[row,col,0] = b
cv_image[row,col,1] = g
cv_image[row,col,2] = r
return cv_image
QPixmap=>Opencv
def QPixmap2Opencv(pixmap):
qimg = pixmap.toImage()
temp_shape = (qimg.height(), qimg.bytesPerLine() * 8 // qimg.depth())
temp_shape += (4,)
ptr = qimg.bits()
ptr.setsize(qimg.byteCount())
result = np.array(ptr, dtype=np.uint8).reshape(temp_shape)
result = result[..., :3]
return result
Opencv=>QPixmap文章来源:https://www.toymoban.com/news/detail-521522.html
可以现将Opencv转Qimage,然后把Qimage转Qpixmap文章来源地址https://www.toymoban.com/news/detail-521522.html
到了这里,关于[pyqt5]opencv QPixmap QImage相互转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!