图片处理
获取图片中的像素值
#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