您的位置:首页 > 运维架构

opencv从文件中批量读取图像

2016-09-22 17:10 337 查看
用opencv处理图像,特别涉及到机器学习,需要批量地读取图像。

方法1比较简单,唯一的要求就是文件夹下的图片名称是有规律的,如 ***(0)、***(1)、***(2)、***(3)·····

[cpp]
view plain
copy

print?

#include "opencv2/opencv.hpp"  
#include "iostream"  
  
using namespace std;  
using namespace cv;  
  
#define  NUM  100     //读取image的个数  
int main()  
{  
    Mat image;  
    string ImgName;  
    int n=1;  
    while(n<=NUM)   //100  
    {   
        ImgName="woman";  
        //int 转换string  
        stringstream ss;  
        string str;  
        ss<<n;  
        ss>>str;  
  
        ImgName=ImgName+" ("+str+")";    //图像文件明格式:ImgName(n)  
        ImgName = "D:\\Mycode\\imagebank\\woman\\" + ImgName+".png";  
        cout<<"处理:"<<ImgName<<endl;  
        image= imread(ImgName);//读取图片  
        if(image.data ==0)  
        { printf("[error] 没有图片\n");}  
        n++;  
   }  
  
    waitKey(0);  
    system("pause");  
    return 4;  
}  



#include "opencv2/opencv.hpp"
#include "iostream"

using namespace std;
using namespace cv;

#define  NUM  100     //读取image的个数
int main()
{
Mat image;
string ImgName;
int n=1;
while(n<=NUM)   //100
{
ImgName="woman";
//int 转换string
stringstream ss;
string str;
ss<<n;
ss>>str;

ImgName=ImgName+" ("+str+")";    //图像文件明格式:ImgName(n)
ImgName = "D:\\Mycode\\imagebank\\woman\\" + ImgName+".png";
cout<<"处理:"<<ImgName<<endl;
image= imread(ImgName);//读取图片
if(image.data ==0)
{ printf("[error] 没有图片\n");}
n++;
}

waitKey(0);
system("pause");
return 4;
}

方法二需要一个 .txt文件存放文件中待读取图像的名称,每行为一条图像名。

[cpp]
view plain
copy

print?

#include "opencv2/opencv.hpp"  
#include "iostream"  
#include <fstream>  
using namespace std;  
using namespace cv;  
  
int main()  
{  
    Mat image;  
    string ImgName;  
    ifstream fin("woman.txt");//打开原始样本图片文件列表  
    while(getline(fin,ImgName)) //一行一行读取文件列表  
    {    
      cout<<"处理:"<<ImgName<<endl;  
      ImgName = "D:\\Mycode\\woman\\" + ImgName+".png";  
      image= imread(ImgName);//读取图片  
  
     if(image.data ==0)  
      {printf("[error] 没有图片\n");return -5;}  
    }  
        waitKey(0);   
return 4;  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: