Opencv将二值图像的像素值写入文件
opencv write into a file the pixel values of binary image
我想问关于如何将所有像素值导出/写入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++ API的Mat
类优于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;
}
相关文章:
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- 如何在24位SDL_Surface上设置像素的颜色
- 如何从SDL_Surface获取特定像素的颜色
- 如何使用Imebra库将压缩像素(用我自己的编码器压缩)回到DICOM图像文件中
- 如何使用stb_image将像素颜色数据写入 BMP 图像文件?
- 从位图图像文件读取像素数据值
- C/C++LIBTIFF:需要从BW TIFF文件中读取白色和黑色像素的像素位置
- 从 DICOM 文件 .dcm 获取像素数据
- 使用 boost.gil 逐像素读取.png文件
- 如何使用Imebra库修改DICOM文件中的图像像素
- 从bmp文件读取RGB像素
- 读取bmp文件中的像素值
- 如何显示已保存在文件中的像素图像
- 我需要从一个图像文件中生成一个像素矩阵
- 如何使用c++从png文件中提取像素
- 图像文件到矢量像素与CImg
- Opencv将二值图像的像素值写入文件
- DCMTK C++:如何从dicom文件中获取数据像素
- 裁剪具有定义的宽度、长度和像素位置的视频文件