2015-07-20 70 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