Opencv讀取圖片像素值並保存為txt文件


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

using namespace std;
using namespace cv;

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

  //從文件中讀入圖像
  Mat img = imread(imagename);
  ofstream outfile("rgb.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; //單通道是uchar,沒有[0][1][2]
        img.at<Vec3b>(i, j)[1] = 0;
        img.at<Vec3b>(i, j)[2] = 0;
      }
    }
    outfile << endl;
  }

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

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

  return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM