numpy 数组转 QImage 然后显示到 QLabel

pyqt5不熟,百度看大佬示例,搞了半小时,记录一下

外部链接:
https://blog.csdn.net/qq_32973061/article/details/81139689
https://blog.csdn.net/ccchen706/article/details/71425653

from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtGui import QImage, QPixmap
import numpy as np

if __name__ == '__main__':
    app = QApplication(sys.argv)
    h, w = 300, 600
    im = np.random.randint(0, 255, [h, w, 3], np.uint8)
    a = QLabel()
    a.resize(w, h)
    # 注意下面QtGui.QImage的第四个参数,意思为图像每行有多少个字节,不设定时,图像有时会歪,所以一定要设定
    im = QImage(im.data, im.shape[1], im.shape[0], im.shape[1]*3, QImage.Format_RGB888)
    pix = QPixmap(im).scaled(a.width(), a.height())
    a.setPixmap(pix)
    a.show()
    exit(app.exec_())
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
PyQt5 中,可以使用 QLabel 显示图像,同时使用 OpenCV (cv2) 对图像进行处理。具体步骤如下: 1. 将 QLabel 中的图像换成 OpenCV 中的图像格式: ```python from PyQt5.QtGui import QPixmap import numpy as np # 获取 QLabel 中的图像 pixmap = label.pixmap() qImg = pixmap.toImage() # 将 QImage 换成 numpy 数组 height, width, channel = qImg.height(), qImg.width(), qImg.bytesPerLine() qImg = qImg.convertToFormat(QImage.Format_RGB888) ptr = qImg.constBits() arr = np.array(ptr).reshape(height, width, 3) # 换成 3 通道的 numpy 数组 img = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) # 换成 BGR 格式的图像 ``` 2. 对图像进行 OpenCV 处理: ```python # 进行处理 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) ``` 3. 将处理后的图像换成 QPixmap 格式,显示QLabel 中: ```python # 将处理后的图像换成 QImage 格式 qImg = QImage(blur.data, blur.shape[1], blur.shape[0], QImage.Format_Grayscale8) # 将 QImage 换成 QPixmap 格式 pixmap = QPixmap.fromImage(qImg) # 显示QLabel 中 label.setPixmap(pixmap) ``` 完整代码如下: ```python import cv2 import numpy as np from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QApplication, QLabel # 获取 QLabel 中的图像 pixmap = label.pixmap() qImg = pixmap.toImage() # 将 QImage 换成 numpy 数组 height, width, channel = qImg.height(), qImg.width(), qImg.bytesPerLine() qImg = qImg.convertToFormat(QImage.Format_RGB888) ptr = qImg.constBits() arr = np.array(ptr).reshape(height, width, 3) # 换成 3 通道的 numpy 数组 img = cv2.cvtColor(arr, cv2.COLOR_RGB2BGR) # 换成 BGR 格式的图像 # 进行处理 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5, 5), 0) # 将处理后的图像换成 QImage 格式 qImg = QImage(blur.data, blur.shape[1], blur.shape[0], QImage.Format_Grayscale8) # 将 QImage 换成 QPixmap 格式 pixmap = QPixmap.fromImage(qImg) # 显示QLabel 中 label.setPixmap(pixmap) ``` 注意,由于 OpenCV 和 PyQT5 都使用了 BGR 格式,因此在将图像从 QLabel 换成 numpy 数组时,需要先将 RGB 格式的 QImage 换成 BGR 格式的图像。另外,在将处理后的图像换成 QImage 格式时,需要使用 `QImage.Format_Grayscale8` 格式,否则会出现图像颜色异常的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值