opencv实验二(C++)——RGB图像分割

本文介绍了如何使用OpenCV库对RGB图像进行分割,并展示了如何提取某行R、G、B像素值并绘制曲线图。代码示例展示了处理图像和生成相关视觉输出的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.1 RGB图像分割

#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdio>
#include <filesystem>

using namespace std;
using namespace cv;

int main()
{
    //OpenCV版本号
    cout << "OpenCV_Version: " << CV_VERSION << endl;

    cv::Mat img = imread("C:/Users/Pictures/ScreenShot_20231010083129.jpeg");
    cv::Mat img_temp(img.rows, img.cols, CV_8UC1);

    // B通道:通道0图像  G通道:通道1图像  R通道:通道1图像
    char channel = 0;
    // 遍历原始图像像素点
    for (int i = 0; i < img.rows; i++)
        for (int j = 0; j < img.cols; j++)
            img_temp.at<uchar>(i, j) = img.at<cv::Vec3b>(i, j)[channel]; 

    // 将图像数据类型转换为8位无符号整数
    img_temp.convertTo(img_temp, CV_8UC1);

cv::imshow("channel_0", img_temp);

    while (waitKey(1) != ' ');
cv::destroyAllWindows();

    return 0;
}

2.3 制某行R、G、B像素值的曲线图

在主函数中插入此函数

//*************************************************************************************
// 函数名称     绘制图像某行R、G、B像素值的曲线图。
// 参数说明     img         处理的图像   
// 参数说明     rgb_row     绘制的图像行  
// 返回参数     void
// 备注信息     按空格切换并退出
// 使用示例     draw_rgb_line(img, 50)
//*************************************************************************************
void draw_rgb_line(Mat img, int rgb_row)
{
    cv::Mat rgb[3];
    cv::split(img, rgb);

    // 选中行
    Mat row_B = rgb[0].row(rgb_row);
    Mat row_G = rgb[1].row(rgb_row);
    Mat row_R = rgb[2].row(rgb_row);

    Mat line_img(img.rows, img.cols, CV_8UC3, Scalar(0, 0, 0));

    // 绘制R、G、B曲线
    for (int i = 1; i < img.cols; i++) 
    {
        cv::line(line_img, cv::Point(i - 1, img.rows - row_B.at<uchar>(0, i - 1)), cv::Point(i, img.rows - row_B.at<uchar>(0, i)), cv::Scalar(255, 0, 0), 1);
        cv::line(line_img, cv::Point(i - 1, img.rows - row_G.at<uchar>(0, i - 1)), cv::Point(i, img.rows - row_G.at<uchar>(0, i)), cv::Scalar(0, 255, 0), 1);
        cv::line(line_img, cv::Point(i - 1, img.rows - row_R.at<uchar>(0, i - 1)), cv::Point(i, img.rows - row_R.at<uchar>(0, i)), cv::Scalar(0, 0, 255), 1);
    }
    cv::imshow("RGB Line Img", line_img);
    std::string name = "line_img";

    save_image(line_img, root, name);

    while (waitKey(1) != ' ');
    cv::destroyAllWindows();
    
}

2.2 实验数据记录

图2- 1 原始图像
图2- 1 原始图像
图2- 2 R通道图像
图2- 2 R通道图像
图2-3 G通道图像
图2-3 G通道图像
图2- 3 B通道图像
图2- 3 B通道图像
图2- 4 第50行rgb曲线
图2- 4 第50行rgb曲线

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值