2015-07-20 143 views
-2

我想问一下关于如何将所有像素值导出/写入txt文件或其他可由记事本打开的格式的问题。在节目下面。opencv将二进制图像的像素值写入文件

感谢,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; 
} 
+4

btw,请**不要**使用opencv的没有更多维护的c-api。 – berak

+0

首先看std :: ofstream的一些例子 – Miki

回答

2

OpenCV的C++ API优于IplImage,因为它简化了你的代码的类Matread 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; 
} 
+0

我想知道opencv如何通过使用contourArea和arcLength来计算图像像素的面积和长度,请参阅快照文件中的示例以及这些值的含义。 – harfbuzz

+0

如果你想问另一个问题,请提出一个新问题。 – enzom83