1、两种方式获取RGB值
1、Vec3b获取RGB值
Mat img = imread("./img/pic.jpg");
//在Mat数据结构中的图,我们可以通过Mat.at得到矩形像素框中的RGB值
//这个方法返回的是一个Vec3b对象的引用(向量,包括了三个无符号的数据)
Vec3b &pixel = img.at<Vec3b>(0, 0);
printf("B:%d G:%d R:%d", pixel[0], pixel[1], pixel[2]);
2、无符号指针获取RGB值
Mat img = imread("./img/pic.jpg");
uchar *ptr = img.ptr<uchar>(0, 0);
printf("B:%d G:%d R:%d", pixel[0], pixel[1], pixel[2]);
获取到的值均为包含三个维度的向量
2、改变图片的RGB值
因为在Mat中图片是存储在二维数组中的,每个数组元素包括一个RGB值,RGB值又包含R、G、B 这里要特别注意的是在Mat中RGB存储的顺序的BGR 也就是
pixel[0] = B; pixel[1] = G; pixel[2] = R;
1、把30x30的地方变成红色
把30x30的地方变成红色
int DORGB30(Mat &img) {
for (int h = 0; h < 30; h++)
{
for (int w = 0; w < 30; w++) {
Vec3b &pixel = img.at<Vec3b>(h, w);
pixel[0] = 0;
pixel[1] = 0;
pixel[2] = 255;
}
}
return 0;
}
int DORGB30(Mat &img) {
for (int h = 0; h < 30; h++)
{
for (int w = 0; w < 30; w++) {
Vec3b &pixel = img.at<Vec3b>(h, w);
pixel[0] = 0;
pixel[1] = 0;
pixel[2] = 255;
}
}
return 0;
}
2、把一半区域的颜色变为一半
int DORGBHalf(Mat &img) {
for (int h = 0; h < img.rows; h++)
{
for (int w = 0; w < img.cols/2; w++) {
/*
Vec3b &pixel = img.at<Vec3b>(h, w);
pixel[0] = pixel[0]/2;
pixel[1] = pixel[1]/2;
pixel[2] = pixel[2]/2;
*/
uchar *ptr = img.ptr<uchar>(h, w);
ptr[0] = ptr[0] / 2;
ptr[1] = ptr[1] / 2;
ptr[2] = ptr[2] / 2;
}
}
return 0;
}
3、完整源代码
// session_02.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
//把30x30的地方变成红色
int DORGB30(Mat &img) {
for (int h = 0; h < 30; h++)
{
for (int w = 0; w < 30; w++) {
Vec3b &pixel = img.at<Vec3b>(h, w);
pixel[0] = 0;
pixel[1] = 0;
pixel[2] = 255;
}
}
return 0;
}
//把颜色变为一半
int DORGBHalf(Mat &img) {
for (int h = 0; h < img.rows; h++)
{
for (int w = 0; w < img.cols/2; w++) {
/*
Vec3b &pixel = img.at<Vec3b>(h, w);
pixel[0] = pixel[0]/2;
pixel[1] = pixel[1]/2;
pixel[2] = pixel[2]/2;
*/
uchar *ptr = img.ptr<uchar>(h, w);
ptr[0] = ptr[0] / 2;
ptr[1] = ptr[1] / 2;
ptr[2] = ptr[2] / 2;
}
}
return 0;
}
int main()
{
Mat img = imread("./img/pic.jpg");//注意这个路径是自己的路径
//在Mat数据结构中的图,我们可以通过Mat.at得到矩形像素框中的RGB值
//这个方法返回的是一个Vec3b对象的引用(向量,包括了三个无符号的数据)
Vec3b &pixel = img.at<Vec3b>(0, 0);
//获取像素值法二,用指针的方式
uchar *ptr = img.ptr<uchar>(0, 0);
//注意这里不能用cout
printf("B:%d G:%d R:%d", pixel[0], pixel[1], pixel[2]);
DORGB30(img);
namedWindow("img");
imshow("img", img);
waitKey(0);
}