opencv读取彩色/灰度图片像素值并存储在本地文件中c++代码实例及运行结果

c++代码彩色图片


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

int main(int argc, char* argv[])
{
	Mat img = imread("1.jpg");
	if (img.empty())
	{
		cout << "图片读取错误,请检查" << endl;
		exit(1);
	}
	int pixelR, pixelG, pixelB;//像素rgb的值
	ofstream output("pixelValue.txt");//没有此文件则重新创建,在项目中
	output << "此图片一共" << img.rows << "行," << img.cols << "列,三个值得顺序分别为R,G,B的值" << endl;
	for (int r = 0; r < img.rows; r++)
	{
		for (int c = 0; c < img.cols; c++)
		{
			pixelB = img.at<Vec3b>(r, c)[0];
			pixelG = img.at<Vec3b>(r, c)[1];
			pixelR = img.at<Vec3b>(r, c)[2];
			output << r << "行," << c << "列:" << pixelR << " " << pixelG << " " << pixelB<<"  ";
		}
		output << endl<<endl;
	}
}

运行结果


c++代码灰度图片

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

int main(int argc, char* argv[])
{
	Mat img = imread("4.jpg");
	cvtColor(img, img, CV_BGR2GRAY);
	if (img.empty())
	{
		cout << "图片读取错误,请检查" << endl;
		exit(1);
	}
	int grayValue;
	ofstream output("4.txt");//没有此文件则重新创建,在项目中
	output << "此灰度图片一共" << img.rows << "行," <<img.cols<<"列" << endl;
	for (int r = 0; r < img.rows; r++)
	{
		output << "第" << r+1 << "行的灰度值为:" << endl;
		for (int c = 0; c < img.cols; c++)
		{
			grayValue = (int)img.at<uchar>(r,c);
			output << grayValue<<" ";
		}
		output << endl << endl;
	}
}

运行结果




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值