C++中OpenCV应用

图片处理

获取图片中的像素值

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main()
{
    Mat img = imread("/home/wang/opencv/project/2/1.jpg");

    Mat img_gray;
    cvtColor(img,img_gray,COLOR_BGR2GRAY);
    
    int x,y;
    int row,col;
    row = img.rows;
    col = img.cols;
    
    Vec3b intensity;
    uchar blue,green,red;
    
    for(int i = 0; i < col; i++)
    {
        for(int j = 0; j < row; j++)
        {
            x = i;
            y = j;
            intensity = img.at<cv::Vec3b>(y,x);
            blue = intensity[0];
            green = intensity[1];
            red = intensity[2];

            cout << "The point(" << x << "," << y <<") rgb_val: "<< (unsigned int)blue 
                     << "," << (unsigned int)green << "," << (unsigned int)red << endl;

            cout << "Gray pixel there is:" << (unsigned int)img_gray.at<uchar>(y,x)  << endl;
        }
    }
    return 0;
}

程序本身的执行逻辑比较简单,也比较容易理解,程序中主要的知识点就是数据结构Vec3b
在OpenCV中,使用imread读取的Mat数据类型统一使用uchar类型的数据存储,对于RGB三通道的图像,每个像素点的数据都是用一个Vec3b类型来存放,数据存放顺序为B、G、R
Vec3b是OpenCV中的一种数据结构,相当于动态数组Vector,于其类似的还有Vec3f(float)、Vec3d(double)
Vec3b中的数据长度为8Bit,存放数据为RGB彩色图像,数据范围为0~255
Vec3b不仅可以用于获取像素值,也可以通过更改相应像素点的Vec3b信息的方式,修改其数据值

例:

img.at< cv:: Vec3b >(x,y) [0]= 255;//B
img.at< cv:: Vec3b >(x,y) [1]= 255;//G
img.at< cv:: Vec3b >(x,y) [2]= 255;//R

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间之里

好东西就应该拿出来大家共享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值