您可以使用Qt的多媒体模块来获取USB摄像头的流。以下是一个示例代码,演示如何通过WebSocket将摄像头流传输给前端,并在前端WebSocket关闭时关闭摄像头:
#include <QApplication>
#include <QtWebSockets/QWebSocketServer>
#include <QtWebSockets/QWebSocket>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 创建摄像头对象
QCamera camera;
camera.setViewfinder(new QCameraViewfinder());
// 创建图像捕获对象,用于从摄像头中捕获图像数据
QCameraImageCapture imageCapture(&camera);
// 打开摄像头
camera.start();
// 创建WebSocket服务器对象并监听指定端口
QWebSocketServer server(QStringLiteral("Video Server"), QWebSocketServer::NonSecureMode);
if (!server.listen(QHostAddress::Any, 1234)) {
qDebug() << "Failed to start server!";
return -1;
}
qDebug() << "Server started on port" << server.serverPort();
QObject::connect(&server, &QWebSocketServer::newConnection, [&]() {
QWebSocket *socket = server.nextPendingConnection();
QObject::connect(socket, &QWebSocket::textMessageReceived, [&](const QString &message) {
if (message == QStringLiteral("close")) { // 接收到前端的关闭消息时,关闭连接和摄像头
socket->close();
camera.stop();
}
});
QObject::connect(&imageCapture, &QCameraImageCapture::imageAvailable, [&](int id, const QVideoFrame &frame) {
if (socket->isValid() && socket->state() == QAbstractSocket::ConnectedState) {
// 将图像数据通过WebSocket发送给前端
QImage image = frame.image().convertToFormat(QImage::Format_RGB888);
QByteArray imageData(reinterpret_cast<const char*>(image.constBits()), image.sizeInBytes());
socket->sendBinaryMessage(imageData);
}
});
QObject::connect(socket, &QWebSocket::disconnected, [&]() {
camera.stop();
});
});
return a.exec();
}
此示例使用Qt的多媒体模块获取USB摄像头的流,并将图像数据以二进制形式通过WebSocket发送给前端。当前端发送 “close” 消息时,服务器会关闭连接并停止摄像头。请根据您的具体需求进行适当调整和修改。
内容由零声教学AI助手提供,问题来源于学员提问