我有带有 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 异常,因为显然前景 Mat 是从 VideoCapture 中获取的,如下所示:
capture.grab() && capture.retrieve(foregroundMat, -1);
仅检索 RGB 图像并删除 Alpha 通道。
视频文件原本是完美的,它检索到的 mat 应该是 rgba 格式,但事实并非如此。这个问题的原因可能是什么?