pyqt5 qimage与opencv互转

qimgae和qpix互转

qimg = qtpixmap.toImage()
qtpixmap = QPixmap.fromImage(qImg)

cv_image = cv2.imread(“图片路径”) #此语句会返回一个opencv的图片对象cv_image, 将image转换为QImage的方法如下

def CV2QImage(cv_image):
    
    width = cv_image.shape[1] #获取图片宽度
    height = cv_image.shape[0]  #获取图片高度
    
    pixmap = QPixmap(width, height) #根据已知的高度和宽度新建一个空的QPixmap,
    qimg = 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 = cv_image[row,col,0]
            g = cv_image[row,col,1]
            r = cv_image[row,col,2]
            
            pix = qRgb(r, g, b)
            qimg.setPixel(col, row, pix)
    
    return qimg #转换完成,返回
# 推荐方式    
def cvToQImage(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:
        qDebug("ERROR: numpy.ndarray could not be converted to QImage. Channels = %d" % data.shape[2])
        return QImage()

将QImage对象转换为cv2可以直接处理的图象,方法如下

def QImage2CV(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
    
# 推荐方式    
def qtpixmap_to_cvimg(qtpixmap):

    qimg = qtpixmap.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

下面是测试上述两个函数的完整测试例程

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import numpy as np
import cv2


def QImage2CV(qimg):
    
    tmp = qimg
    
    #使用numpy创建空的图象
    cv_image = np.zeros((tmp.height(), tmp.width(), 3), dtype=np.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
    
def CV2QImage(cv_image):
    
    width = cv_image.shape[1] #获取图片宽度
    height = cv_image.shape[0]  #获取图片高度
    
    pixmap = QPixmap(width, height) #根据已知的高度和宽度新建一个空的QPixmap,
    qimg = 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 = cv_image[row,col,0]
            g = cv_image[row,col,1]
            r = cv_image[row,col,2]
            
            pix = qRgb(r, g, b)
            qimg.setPixel(col, row, pix)
    
    return qimg #转换完成,返回

path = "E:\\Temp\\"  #存放测试图片的路径,请自行定义

qpixmap = QPixmap(500, 300)
qpixmap.fill(Qt.green)

painter = QPainter()
painter.begin(qpixmap)
painter.setPen(Qt.black)
painter.setBrush(Qt.white)
painter.drawEllipse(QRect(50, 100, 50, 100))
painter.drawLine(0,0,200,100)
painter.end()

qimg = qpixmap.toImage()
qimg.save(path + "qimg-origin.bmp")
image = QImage2CV(qimg)

start_point = (0, 0)
end_point = (250, 300)
line_width = 4
line_type = 8
color = (255,255,0)
cv2.line(image, start_point, end_point, color, line_width, line_type)

qimg_2 = CV2QImage(image)
qimg_2.save(path + "qimg-from-cv_img.bmp")

cv2.imshow("line", image)
cv2.waitKey()
cv2.destroyAllWindows()

你可能感兴趣的:(Python,pyqt5,opencv,计算机视觉,qt)