Opencv讀取圖片(三通道和單通道)像素並保存(像素極操作,使用at函數)

三通道:

Mat Class主要包括兩部個數據部分:一個是matrix header(包括matrix的大小尺寸,儲存方法,儲存地址等等..),另一個是指向存儲像素值的矩陣的指針。

 

#include <opencv2/opencv.hpp>

#include<vector>
#include <fstream>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
  const char* imagename = "1.png";

  //從文件中讀入圖像
  Mat img = imread(imagename);
  ofstream outfile("3chn.txt");

  //如果讀入圖像失敗
  if (img.empty())
  {
    fprintf(stderr, "Can not load image %s\n", imagename);
    return -1;
  }


  int i, j;
  int cPointR, cPointG, cPointB, cPoint;//currentPoint;
  for (i = 1; i < img.rows; i++) 
  {
    for (j = 1; j<img.cols; j++)
    {
      cPointB = img.at<Vec3b>(i, j)[0];
      cPointG = img.at<Vec3b>(i, j)[1];
      cPointR = img.at<Vec3b>(i, j)[2];
      cout << "R:"<<cPointR<<" G:"<<cPointG <<" B:"<<cPointB<< endl;
      outfile << i<<"," << j << "," <<cPointR << "," << cPointG << "," << cPointB << " ";
      if (cPointB>100 & cPointR<100 & cPointG<100)
      {
        img.at<Vec3b>(i, j)[0] = 0; 
        img.at<Vec3b>(i, j)[1] = 0;
        img.at<Vec3b>(i, j)[2] = 0;
      }
    }
    outfile << endl;
  }

  //顯示圖像
  imshow("image", img);

  //此函數等待按鍵,按鍵盤任意鍵就返回
  waitKey();

  return 0;
}

單通道:

#include <opencv2/opencv.hpp>
#include<vector>
#include <fstream>


using namespace std;
using namespace cv;


int main(int argc, char* argv[])
{
const char* imagename = "8.png";


//從文件中讀入圖像
Mat img = imread(imagename,IMREAD_UNCHANGED);
ofstream outfile("1chn.txt");


//如果讀入圖像失敗
if (img.empty())
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}


int i, j;
int cPointB, cPoint;//currentPoint;
for (i = 1; i < 80; i++)
{
for (j = 1; j<400; j++)
{
cPointB = img.at<ushort>(i, j);
cout << " B:" << cPointB << endl;
outfile << i << "," << j << ",("  << cPointB << ") ";
//if (cPointB>100)
//{
// img.at<ushort>(i, j) = 0; //單通道是uchar,沒有[0][1][2]

//}
}
outfile << endl;
}
//顯示圖像
imshow("image", img);


//此函數等待按鍵,按鍵盤任意鍵就返回
waitKey();


return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章