否,OpenCV 中没有原生提供此功能的 API。另一方面,没有什么能阻止你编写自己的代码来做到这一点。
几周前,我对我在互联网上其他地方看到的一项功能进行了一些更改,以便能够:
- 传递两个输入图像:背景为 BGR,前景为 BGRA;
- 根据简单的透明度规则将它们混合在一起;
(我不记得大部分代码是从哪里来的,抱歉……但谢谢你!)
void overlayImage(const cv::Mat &background, const cv::Mat &foreground, cv::Mat &output, cv::Point2i location, double opacity = 1.0)
{
background.copyTo(output);
// start at the row indicated by location, or at row 0 if location.y is negative.
for (int y = std::max(location.y , 0); y < background.rows; ++y) {
int fY = y - location.y; // because of the translation
// we are done of we have processed all rows of the foreground image.
if (fY >= foreground.rows)
break;
// start at the column indicated by location, or at column 0 if location.x is negative.
for (int x = std::max(location.x, 0); x < background.cols; ++x) {
int fX = x - location.x; // because of the translation.
// we are done with this row if the column is outside of the foreground image.
if (fX >= foreground.cols)
break;
// determine the opacity of the foregrond pixel, using its fourth (alpha) channel.
double opacity_level = ((double)foreground.data[fY * foreground.step + fX * foreground.channels() + 3]) / 255.;
if (opacity >= 0.0 && opacity < 1.0)
opacity_level *= opacity;
// and now combine the background and foreground pixel, using the opacity, but only if opacity > 0.
for (int c = 0; opacity_level > 0 && c < output.channels(); ++c) {
unsigned char foregroundPx = foreground.data[fY * foreground.step + fX * foreground.channels() + c];
unsigned char backgroundPx = background.data[y * background.step + x * background.channels() + c];
output.data[y*output.step + output.channels()*x + c] = backgroundPx * (1.-opacity_level) + foregroundPx * opacity_level;
}
}
}
}
您将在下面找到用于测试的输入图像:左侧是背景,右侧上的图像是前景。
要将前景完全复制到背景上,只需执行以下操作:
cv::Mat background = cv::imread("road.png"); // 3-chan BGR
cv::Mat foreground= cv::imread("tulip.png", -1); // 4-chan BGRA
cv::Point location(0, 0);
cv::Mat output;
overlayImage(input_bkg, input_target, output, location, 1.0);
cv::imwrite("output_alpha1.0.png", output);
并以 50% 的透明度进行复制:
overlayImage(input_bkg, input_target, output, location, 0.5);
cv::imwrite("output_alpha0.5.png", output);
结果如下:
此实现对于生产目的来说不是万无一失的,因此使用它需要您自担风险。