- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
计算两个矩阵的每个元素的和。
add 函数计算两个相同大小和相同通道数的矩阵之和:
dst ( I ) = saturate ( src1 ( I ) + src2 ( I ) ) if mask ( I ) ≠ 0 \texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0 dst(I)=saturate(src1(I)+src2(I))if mask(I)=0
该功能可以用矩阵表达式替换:
dst = src1 + src2 \texttt{dst} = \texttt{src1} + \texttt{src2} dst=src1+src2
输入矩阵和输出矩阵可以具有相同的或不同的深度。例如,您可以将一个16位无符号矩阵与一个8位有符号矩阵相加,并将结果存储为32位浮点矩阵。输出矩阵的深度由 ddepth 参数决定。如果 src1.depth() == src2.depth(),ddepth 可以设置为默认值 -1。在这种情况下,输出矩阵将具有与输入矩阵相同的深度。
支持的矩阵数据类型包括:CV_8UC1, CV_8UC3, CV_16UC1, CV_16SC1, CV_32FC1。
注意:
函数的文本ID是 “org.opencv.core.math.add”
函数原型
GMat cv::gapi::addC
(
const GMat & src1,
const GScalar & c,
int ddepth = -1
)
参数
- 参数src1:第一个输入矩阵。
- 参数src2:第二个输入矩阵。
- 参数ddepth:输出矩阵的可选深度。
代码示例
#include <opencv2/gapi.hpp>
#include <opencv2/gapi/core.hpp> // 包含G-API核心功能
#include <opencv2/opencv.hpp>
int main()
{
// 读取两个输入图像
cv::Mat img1 = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/stich1.png", cv::IMREAD_COLOR );
cv::Mat img2 = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/stich2.png", cv::IMREAD_COLOR );
if ( img1.empty() || img2.empty() )
{
std::cerr << "无法加载图像,请检查路径。" << std::endl;
return -1;
}
cv::resize( img2, img2, img1.size() );
// 确保两幅图像具有相同的尺寸
if ( img1.size() != img2.size() )
{
std::cerr << "两幅图像的尺寸必须相同。" << std::endl;
return -1;
}
// 定义G-API图中的输入和输出
cv::GMat in1, in2;
auto out = cv::gapi::add( in1, in2 ); // 使用默认深度
// 创建一个计算图
cv::GComputation add_graph( cv::GIn( in1, in2 ), cv::GOut( out ) );
// 输出矩阵
cv::Mat result;
// 编译并执行计算图
add_graph.apply( img1, img2, result, cv::GCompileArgs() );
// 显示结果
cv::imshow( "Result", result );
// 如果需要指定不同的输出深度,可以这样做:
int ddepth = CV_32F; // 指定为32位浮点数
auto out_with_ddepth = cv::gapi::add( in1, in2, ddepth );
// 创建另一个计算图
cv::GComputation add_graph_with_ddepth( cv::GIn( in1, in2 ), cv::GOut( out_with_ddepth ) );
// 输出矩阵(这次是浮点型)
cv::Mat result_float;
// 编译并执行计算图
add_graph_with_ddepth.apply( img1, img2, result_float, cv::GCompileArgs() );
// 转换回8位图像以便显示
cv::Mat result_converted;
result_float.convertTo( result_converted, CV_8U );
cv::imshow( "图像1", img1 );
cv::imshow( "图像2", img2 );
cv::imshow( "Result with specified depth", result_converted );
cv::waitKey( 0 );
return 0;
}