要在PyQt中显示OpenCV图片,一般上是通过把OpenCV的图像数据转为
QImage数据,之后显示的。首先看一下QImage类一个构造函数:
QImage(const uchar *data,
int width, int height, int bytesPerLine,
Format format,
QImageCleanupFunction cleanupFunction = Q_NULLPTR,
void *cleanupInfo = Q_NULLPTR)
通过这个函数好容易由OpenCV的图像数据转换为QImage
self.qtImage = QImage(self.cvImage.data,
self.w, self.h, self.bytesPerline,
QImage.Format_RGB888
主要代码如下:
self.cvImage = cv.imread("c:/pic/lena.jpg", cv.IMREAD_COLOR)
# 由于Opencv颜色是BGR,而Qt是RGB,所以要转换
self.cvImage = cv.cvtColor(self.cvImage, cv.COLOR_BGR2RGB)
self.w, self.h, self.channel = self.cvImage.shape
# 颜色是三通道的
self.bytesPerline = self.channel * self.w
self.qtImage = QImage(self.cvImage.data,
self.w, self.h, self.bytesPerline,
QImage.Format_RGB888)
之后Paint出来就可以显示Lena了
def paint(self, painter, option, widget):
painter.drawImage(QRectF(QPointF(0, 0), QPointF(self.w, self.h)), self.qtImage)
完整代码如下:
"""
By Linyoubiao
2020-03-23
"""
import numpy as np
import cv2 as cv
from PyQt5.QtWidgets import (QApplication,
QGraphicsView, QGraphicsScene, QGraphicsItem)
from PyQt5.QtGui import (QImage, QPixmap, QPicture, QPainterPath)
from PyQt5.QtCore import (QRect, QRectF, QPoint, QPointF)
import sys
class image_item(QGraphicsItem):
def __init__(self):
super(image_item, self).__init__()
self.cvImage = cv.imread("c:/pic/lena.jpg", cv.IMREAD_COLOR)
# 由于Opencv颜色是BGR,而Qt是RGB,所以要转换
self.cvImage = cv.cvtColor(self.cvImage, cv.COLOR_BGR2RGB)
self.w, self.h, self.channel = self.cvImage.shape
# 颜色是三通道的
self.bytesPerline = self.channel * self.w
self.qtImage = QImage(self.cvImage.data,
self.w, self.h, self.bytesPerline,
QImage.Format_RGB888)
def boundingRect(self):
rect = QRectF(QPointF(0, 0), QPointF(self.w, self.h))
return rect
def paint(self, painter, option, widget):
painter.drawImage(QRectF(QPointF(0, 0), QPointF(self.w, self.h)), self.qtImage)
class image_scene(QGraphicsScene):
def __init__(self):
super(image_scene, self).__init__()
item = image_item()
self.addItem(item)
class image_view(QGraphicsView):
def __init__(self):
super(image_view, self).__init__()
scene = image_scene()
self.setScene(scene)
if __name__ == "__main__":
app = QApplication(sys.argv)
view = image_view()
view.show()
sys.exit(app.exec_())
多谢,美。