1. 程式人生 > >opencv讀取彩色/灰度圖片畫素值並存儲在本地檔案中c++程式碼例項及執行結果

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

執行結果