pyqt 视频流同时生成直方图
时间: 2023-07-23 19:34:56 浏览: 162
实时获取视频直方图
3星 · 编辑精心推荐
可以使用OpenCV库来读取视频流并生成直方图,然后再使用PyQt来显示视频和直方图。以下是示例代码:
```python
import cv2
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
import numpy as np
class VideoWidget(QWidget):
def __init__(self):
super().__init__()
# 创建用于显示视频和直方图的标签
self.video_label = QLabel()
self.hist_label = QLabel()
# 创建垂直布局并将标签添加到其中
layout = QVBoxLayout()
layout.addWidget(self.video_label)
layout.addWidget(self.hist_label)
self.setLayout(layout)
# 打开视频流
self.cap = cv2.VideoCapture(0)
def update(self):
# 从视频流中读取帧
ret, frame = self.cap.read()
if ret:
# 将帧转换为Qt图像
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
height, width, channels = frame.shape
bytes_per_line = channels * width
qt_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
# 显示视频
self.video_label.setPixmap(QPixmap.fromImage(qt_image))
self.video_label.setAlignment(Qt.AlignCenter)
# 生成直方图
hist, bins = np.histogram(frame.ravel(), 256, [0,256])
hist_image = np.zeros((256, 256, 3), dtype=np.uint8)
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
hist = np.int32(np.around(hist))
for i in range(256):
cv2.line(hist_image, (i, 255), (i, 255 - hist[i]), (255, 0, 0), 1)
# 将直方图转换为Qt图像
hist_image = cv2.cvtColor(hist_image, cv2.COLOR_BGR2RGB)
height, width, channels = hist_image.shape
bytes_per_line = channels * width
qt_hist = QImage(hist_image.data, width, height, bytes_per_line, QImage.Format_RGB888)
# 显示直方图
self.hist_label.setPixmap(QPixmap.fromImage(qt_hist))
self.hist_label.setAlignment(Qt.AlignCenter)
# 每隔10毫秒更新一次
QApplication.processEvents()
QTimer.singleShot(10, self.update)
if __name__ == '__main__':
app = QApplication([])
widget = VideoWidget()
widget.resize(800, 600)
widget.show()
widget.update()
app.exec_()
```
此代码将打开默认的摄像头并显示视频和直方图。每隔10毫秒,它将更新一次视频和直方图。请注意,此代码仅适用于Windows操作系统。如果您正在使用其他操作系统,则可能需要对代码进行一些修改。
阅读全文