OpenCV VideoCapture 从视频中移除 alpha 通道

OpenCV VideoCapture removes alpha channel from video

我有带 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);
            }
        }
  }

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

capture.grab() && capture.retrieve(foregroundMat, -1);

仅检索 rgb 图像并删除 alpha 通道。 视频文件本来就很好,检索到的mat应该是rgba格式,但不是。这个问题的原因可能是什么?

很遗憾,OpenCV 不支持使用 Alpha 通道获取视频帧。从这个code snippet就可以看出这一点。作者很方便地假设视频文件总是有 RGB 帧。

一个快速的 hack 可能是在相关位置(2-3 个实例)用 AV_PIX_FMT_BGRA 替换 AV_PIX_FMT_BGR24 并重新构建库以使您的代码正常工作。但是这个肮脏的 hack 总是会为所有视频格式生成 RGBA 帧。

我个人打算创建一个PR with this fix,但可能需要一些时间。

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