OpenCV 图形API(47)颜色空间转换-----将 I420(YUV 4:2:0) 格式的图像数据转换为 RGB 格式

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

算法描述

将图像从I420颜色空间转换为BGR颜色空间。
该函数将输入图像从I420颜色空间转换为BGR。B、G和R通道值的常规范围是0到255。

输出图像必须是8位无符号3通道图像(CV_8UC3)。RGB输出图像的宽度必须与输入图像的宽度相同。RGB输出图像的高度必须等于输入图像高度的2/3。

注意:
函数的文本ID是"org.opencv.imgproc.colorconvert.i4202rgb"

函数原型

GMat cv::gapi::I4202RGB 	
(
 	const GMat &  	src
) 	

参数

  • 参数src - 输入图像:8位无符号1通道图像(CV_8UC1)。

代码示例

#include <opencv2/gapi.hpp>
#include <opencv2/gapi/core.hpp>  // 包含G-API的核心功能
#include <opencv2/opencv.hpp>

int main()
{
    int width  = 640;
    int height = 480;

    // 创建I420格式的数据(这里用随机数据填充以显示颜色变化)
    std::vector< uchar > i420_data( ( width * height * 3 ) / 2 );

    // 初始化Y平面
    for ( int i = 0; i < width * height; ++i )
    {
        i420_data[ i ] = rand() % 256;  // Y plane
    }
    // 初始化U平面
    for ( int i = 0; i < width * height / 4; ++i )
    {
        i420_data[ width * height + i ] = rand() % 256;  // U plane
    }
    // 初始化V平面
    for ( int i = 0; i < width * height / 4; ++i )
    {
        i420_data[ width * height + width * height / 4 + i ] = rand() % 256;  // V plane
    }

    // 定义一个cv::Mat来表示整个I420数据流
    cv::Mat i420_mat( height * 3 / 2, width, CV_8UC1, i420_data.data() );

    // 定义G-API图
    cv::GMat in;
    cv::GMat out = cv::gapi::I4202RGB( in );

    // 创建编译后的图(compiled graph)
    cv::GComputation comp( cv::GIn( in ), cv::GOut( out ) );
    cv::Mat rgbImg;

    try
    {
        // 应用到输入图像并获取输出图像
        comp.apply( i420_mat, rgbImg, cv::compile_args( cv::gapi::kernels() ) );

        // 显示结果
        cv::imshow( "RGB image", rgbImg );
        cv::waitKey();
    }
    catch ( const cv::Exception& e )
    {
        std::cerr << "OpenCV exception: " << e.what() << std::endl;
    }
    catch ( const std::exception& e )
    {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

运行结果

在这里插入图片描述