OpenCV 图形API(6)将一个矩阵(或图像)与一个标量值相加的函数addC()

发布于:2025-04-01 ⋅ 阅读:(52) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

addC 函数将给定的标量值加到给定矩阵的每个元素上。该功能可以用矩阵表达式替换:
dst = src1 + c \texttt{dst} = \texttt{src1} + \texttt{c} dst=src1+c
输出矩阵的深度由 ddepth 参数决定。如果 ddepth 设置为默认值 -1,则输出矩阵将具有与输入矩阵相同的深度。 输入矩阵可以是单通道或多个通道的矩阵。输出矩阵必须与输入矩阵具有相同的尺寸和通道数。
支持的矩阵数据类型包括:CV_8UC1 CV_8UC3 CV_16UC1 CV_16SC1 CV_32FC1
注意:
函数的文本ID是 “org.opencv.core.math.addC”

函数原型

GMat cv::gapi::addC 	
(
 	const GMat &  	src1,
	const GScalar &  	c,
	int  	ddepth = -1 
) 	

参数

  • 参数src1:第一个输入矩阵。
  • 参数c:要加到输入矩阵上的标量值。
  • 参数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 );

    if ( img1.empty() )
    {
        std::cerr << "无法加载图像,请检查路径。" << std::endl;
        return -1;
    }

    // 定义标量值
    cv::Scalar scalar_value( 90, 90, 90 );  // BGR颜色空间中的标量值

    // 定义G-API图中的输入和输出
    cv::GMat in1;
    auto out = cv::gapi::addC( in1, cv::GScalar( scalar_value ) );  // 使用默认深度

    // 创建一个计算图
    cv::GComputation add_graph( cv::GIn( in1 ), cv::GOut( out ) );

    // 输出矩阵
    cv::Mat result;

    // 编译并执行计算图
    add_graph.apply( img1, result, cv::GCompileArgs() );

    // 显示结果
    cv::imshow( "原图", img1 );
    cv::imshow( "Result", result );

    // 如果需要指定不同的输出深度,可以这样做:
    int ddepth           = CV_32F;  // 指定为32位浮点数
    auto out_with_ddepth = cv::gapi::addC( in1, cv::GScalar( scalar_value ), ddepth );

    // 创建另一个计算图
    cv::GComputation add_graph_with_ddepth( cv::GIn( in1 ), cv::GOut( out_with_ddepth ) );

    // 输出矩阵(这次是浮点型)
    cv::Mat result_float;

    // 编译并执行计算图
    add_graph_with_ddepth.apply( img1, result_float, cv::GCompileArgs() );

    // 转换回8位图像以便显示
    cv::Mat result_converted;
    result_float.convertTo( result_converted, CV_8U );

    cv::imshow( "Result with specified depth", result_converted );
    cv::waitKey( 0 );

    return 0;
}

运行结果

在这里插入图片描述