Opencv将二值图像的像素值写入文件

opencv write into a file the pixel values of binary image

本文关键字:文件 像素 二值图像 Opencv      更新时间:2023-10-16

我想问关于如何将所有像素值导出/写入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;
}

新的OpenCV c++ APIMat类优于IplImage,因为它简化了您的代码:阅读更多关于Mat类的信息。有关加载图像的更多信息,您可以阅读加载,修改和保存图像。

为了使用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;
}