OpenCV VideoCapture 从视频中删除 Alpha 通道

San*_*har 5 java opencv video-capture rgba

我有带有 Alpha 通道的视频,我尝试将其放置在另一个视频上,如下所示:

public static void overlayImage(Mat background, Mat foreground, Mat output, Point location) {
        background.copyTo(output);

        for (int y = (int) Math.max(location.y, 0); y < background.rows(); ++y) {

            int fY = (int) (y - location.y);

            if (fY >= foreground.rows()) {
                break;
            }

            for (int x = (int) Math.max(location.x, 0); x < background.cols(); ++x) {
                int fX = (int) (x - location.x);
                if (fX >= foreground.cols()) {
                    break;
                }

                double opacity;
                double[] finalPixelValue = new double[4];

                opacity = foreground.get(fY, fX)[3];

                finalPixelValue[0] = background.get(y, x)[0];
                finalPixelValue[1] = background.get(y, x)[1];
                finalPixelValue[2] = background.get(y, x)[2];
                finalPixelValue[3] = background.get(y, x)[3];

                for (int c = 0; c < output.channels(); ++c) {
                    if (opacity > 0) {
                        double foregroundPx = foreground.get(fY, fX)[c];
                        double backgroundPx = background.get(y, x)[c];

                        float fOpacity = (float) (opacity / 255);
                        finalPixelValue[c] = ((backgroundPx * (1.0 - fOpacity)) + (foregroundPx * fOpacity));
                        if (c == 3) {
                            finalPixelValue[c] = foreground.get(fY, fX)[3];
                        }
                    }
                }
                output.put(y, x, finalPixelValue);
            }
        }
  }
Run Code Online (Sandbox Code Playgroud)

当我运行这个函数时,我得到 Nullpointer 异常,因为显然前景 Mat 是从 VideoCapture 中获取的,如下所示:

capture.grab() && capture.retrieve(foregroundMat, -1);
Run Code Online (Sandbox Code Playgroud)

仅检索 RGB 图像并删除 Alpha 通道。视频文件原本是完美的,它检索到的 mat 应该是 rgba 格式,但事实并非如此。这个问题的原因可能是什么?

Zda*_*daR 4

不幸的是,OpenCV 不支持使用 Alpha 通道获取视频帧。从这段代码片段中可以明显看出这一点。作者方便地假设视频文件始终具有 RGB 帧。

快速破解可以在相关位置(2-3 个实例)替换AV_PIX_FMT_BGR24AV_PIX_FMT_BGRA重新构建库以使代码正常工作。但这个肮脏的黑客总是会为所有视频格式生成 RGBA 帧。

我个人计划用这个修复程序创建一个 PR,但这可能需要一些时间。

其他可能的解决方案是使用其他第三方库来获取帧.webm.mov格式,然后使用 OpenCV 对其进行处理。