opencv将二进制图像的像素值写入文件

时间:2015-07-20 12:37:35

标签: c++ opencv

我想问一下如何将所有像素值导出/写入txt文件或其他可以由记事本打开的格式的问题。在程序下面。

谢谢,HB

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
#include <stdlib.h>
#include<fstream>


using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
  IplImage *img = cvLoadImage("MyImg.png");
  CvMat *mat = cvCreateMat(img->height,img->width,CV_32FC3 );
  cvConvert( img, mat );
  outFile.open("MyFile.txt");

  for(int i=0;i<10;i++) 
  {
    for(int j=0;j<10;j++)
    {
      /// Get the (i,j) pixel value
      CvScalar scal = cvGet2D( mat,j,i);
      printf( "(%.f,%.f,%.f)",scal.val[0], scal.val[1],scal.val[2] );
    }

    printf("\n");
  }

  waitKey(1);
  return 0;
}

1 个答案:

答案 0 :(得分:2)

OpenCV C ++ API 的类Mat优先于IplImage,因为它简化了您的代码:read more关于类Mat 。有关加载图片的详细信息,请阅读Load, Modify, and Save an Image

为了使用C ++编写文本文件,您可以使用类ofstream

这是源代码。

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

#include <fstream>
using namespace std;


int main( int argc, char** argv )
{
    Mat colorImage = imread("MyImg.png");

    // First convert the image to grayscale.
    Mat grayImage;
    cvtColor(colorImage, grayImage, CV_RGB2GRAY);

    // Then apply thresholding to make it binary.
    Mat binaryImage(grayImage.size(), grayImage.type());
    threshold(grayImage, binaryImage, 128, 255, CV_THRESH_BINARY);

    // Open the file in write mode.
    ofstream outputFile;
    outputFile.open("MyFile.txt");

    // Iterate through pixels.
    for (int r = 0; r < binaryImage.rows; r++)
    {
        for (int c = 0; c < binaryImage.cols; c++)
        {
            int pixel = binaryImage.at<uchar>(r,c);

            outputFile << pixel << '\t';
        }
        outputFile << endl;
    }

    // Close the file.
    outputFile.close();
    return 0;
}