opencv(二):批量预处理图片

来源:互联网 发布:男士保湿爽肤水 知乎 编辑:程序博客网 时间:2024/05/29 15:52

前言

在手写字符识别任务中,我们将MNIST数据集自带数据融合我们自己的数据组成新的测试集和验证集,在这个过程中,需要对其进行预处理以满足我们的要求。由于图片数量巨大,涉及到图片的批量处理。

基本思路

原始图片-》命令行命令得到列表文件-》程序读取列表文件实现图片批量处理

代码实现

生成列表文件1.lst

这里写图片描述

读取列表文件进行图片的批量处理,将图片都处理成白底黑字,字符顶格的形式。

//author: zhimazhimaheng//time: 2017/7/18//E-mail:1439352516@qq.com#include <iostream>#include <fstream>#include<string>#include<opencv2/opencv.hpp>using namespace std;using namespace cv;int main(){    string s1="D:/Mycode/image/1.lst"; //原始图片路径    std::ifstream infile(s1, ios::in);    if (!infile.is_open())    {        return 1;    }    vector<string> imgnamelist;    string line;    while(std::getline(infile, line))    {        imgnamelist.push_back(line);    }    infile.close();    for (int i = 0; i < imgnamelist.size(); ++i)    {        string imgname = imgnamelist[i];        cv::Mat tp1  = cv::imread(imgname, CV_LOAD_IMAGE_GRAYSCALE);        int threshold_type=CV_THRESH_BINARY;        int adaptive_method=CV_ADAPTIVE_THRESH_GAUSSIAN_C;        int blocksize=31;        double offset=15;        Mat tp;        adaptiveThreshold(tp1, tp, 255, adaptive_method, threshold_type, blocksize, offset);        Mat element=getStructuringElement(MORPH_ELLIPSE,Size(5,5), Point(2,2));        dilate(tp, tp, element);        vector<vector<Point>> storage;        vector<Point> contmax;        vector<Vec4i> hierarchy;        Mat sample_tmp=tp.clone();        tp=255-tp; //原始图片是白底黑字,而连通域寻找的是白色区域,所以反色        findContours(tp, storage,hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);        double maxArea=0.0;        Rect rect(0,0,0,0);         for(int i=0; i<storage.size(); i++)        {             double area=fabs(contourArea(storage[i]));            if(area>maxArea)            {                maxArea=area;                contmax=storage[i];                rect=boundingRect(contmax);                std::cout<<"x="<<rect.x<<" y="<<rect.y<<" width="<<rect.width<<" height="<<rect.height<<std::endl;            }         }        cv::Mat sample_roi;        sample_roi=sample_tmp(Rect(rect.x, rect.y, rect.width, rect.height));        string refilename= "D:/Mycode/image1/1/"; //生成图片路径        std::stringstream sstr2;        sstr2<<(i+1);        string str3;        sstr2>>str3;        if(i<10)        {            str3="0x0031_0000"+str3; //生成图片以Unicode码命名            }        else if(i<100)        {            str3="0x0031_000"+str3;        }        else if(i<1000)        {            str3="0x0031_00"+str3;        }        else if(i<10000)        {            str3="0x0031_0"+str3;        }        string str5=refilename+str3+".png";        cv::imwrite(str5, sample_roi);    }}
原创粉丝点击