- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
将一个矩阵转换为另一种数据深度,并可选择进行缩放。
该方法将源像素值转换为目标数据深度。最终应用 saturate_cast<> 以避免可能出现的数据溢出情况:
m ( x , y ) = s a t u r a t e _ c a s t < r T y p e > ( α ( ∗ t h i s ) ( x , y ) + β ) m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) + \beta ) m(x,y)=saturate_cast<rType>(α(∗this)(x,y)+β)
输出矩阵必须与输入矩阵大小相同。
注意 :
此函数的文本标识符是 "org.opencv.core.transform.convertTo"。
函数原型
cpp
GMat cv::gapi::convertTo
(
const GMat & src,
int rdepth,
double alpha = 1,
double beta = 0
)
参数
- 参数 src: 需要被转换的输入矩阵。
- 参数 rdepth: 目标输出矩阵的数据深度,更确切地说是深度(因为通道数量与输入相同);如果 rdepth 是负数,则输出矩阵将具有与输入相同的深度。
- 参数 alpha: 可选的比例因子。
- 参数 beta: 添加到缩放值的可选增量。
代码示例
cpp
#include <iomanip> // For std::setprecision
#include <iostream>
#include <opencv2/gapi.hpp>
#include <opencv2/gapi/core.hpp>
#include <opencv2/opencv.hpp>
int main()
{
// 创建一个 G-API 图像处理图
cv::GMat in;
// 定义转换操作:例如从 CV_8U 转换到 CV_32F,并应用 alpha 和 beta
int rdepth = CV_32F; // 目标深度,这里是32位浮点数
double alpha = 1.0; // 缩放因子
double beta = 0.0; // 增量值
// 使用 convertTo 方法
cv::GMat dst = cv::gapi::convertTo( in, rdepth, alpha, beta );
// 定义 G-API 图(graph)和编译它
cv::GComputation graph( cv::GIn( in ), cv::GOut( dst ) );
// 准备输入数据:这里以随机生成的数据为例
cv::Mat src_mat = ( cv::Mat_< uchar >( 3, 3 ) << 1, 2, 3, 4, 5, 6, 7, 8, 9 ); // 示例8位无符号整数矩阵
cv::Mat dst_mat;
// 在输入数据上运行 G-API 图像处理图
graph.apply( src_mat, dst_mat, cv::compile_args( cv::gapi::kernels() ) );
// 输出结果
std::cout << "Original matrix (type CV_8U):\n" << src_mat << std::endl;
std::cout << "Converted matrix (type CV_32F):\n";
std::cout << std::fixed << std::setprecision( 1 ); // 设置浮点数输出格式
for ( int i = 0; i < dst_mat.rows; ++i )
{
for ( int j = 0; j < dst_mat.cols; ++j )
{
std::cout << dst_mat.at< float >( i, j ) << " ";
}
std::cout << "\n";
}
return 0;
}
运行结果
bash
Original matrix (type CV_8U):
[ 1, 2, 3;
4, 5, 6;
7, 8, 9]
Converted matrix (type CV_32F):
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0