opencv小游戏(02):获取图片的RGB值

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);

}



  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值