convert QVideoFrame to QImage

前端 未结 4 1841
北海茫月
北海茫月 2021-01-12 16:06

I want to get every frames from a QMediaPlayer and convert it to QImage (or cv::Mat)

so I used videoFrameProbed

4条回答
  •  灰色年华
    2021-01-12 16:33

    For QCamera output, that method doesn't always work. In particular, QVideoFrame::imageFormatFromPixelFormat() returns QImage::Format_Invalid when given QVideoFrame::Format_Jpeg, which is what's coming out of my QCamera. But this works:

    QImage Camera::imageFromVideoFrame(const QVideoFrame& buffer) const
    {
        QImage img;
        QVideoFrame frame(buffer);  // make a copy we can call map (non-const) on
        frame.map(QAbstractVideoBuffer::ReadOnly);
        QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(
                    frame.pixelFormat());
        // BUT the frame.pixelFormat() is QVideoFrame::Format_Jpeg, and this is
        // mapped to QImage::Format_Invalid by
        // QVideoFrame::imageFormatFromPixelFormat
        if (imageFormat != QImage::Format_Invalid) {
            img = QImage(frame.bits(),
                         frame.width(),
                         frame.height(),
                         // frame.bytesPerLine(),
                         imageFormat);
        } else {
            // e.g. JPEG
            int nbytes = frame.mappedBytes();
            img = QImage::fromData(frame.bits(), nbytes);
        }
        frame.unmap();
        return img;
    }
    

提交回复
热议问题