Пример #1
0
void saveModel(int _predictsize, int _neurons)
{
	FileStorage fs;
	fs.open("train/ann_data.xml", FileStorage::READ);

	Mat TrainingData;
	Mat Classes;

	string training;
	if(1)
	{ 
		stringstream ss(stringstream::in | stringstream::out);
		ss << "TrainingDataF" << _predictsize;
		training = ss.str();
	}

	fs[training] >> TrainingData;
	fs["classes"] >> Classes;

	//train the Ann
	cout << "Begin to saveModelChar predictSize:" << _predictsize 
		<< " neurons:" << _neurons << endl;

    double start = cv::getTickCount();
	annTrain(TrainingData, Classes, _neurons);
    double end = cv::getTickCount();
	cout << "GetTickCount:" << (end-start)/1000 << endl;  

	cout << "End the saveModelChar" << endl;

	string model_name = "train/ann.xml";
	//if(1)
	//{ 
	//	stringstream ss(stringstream::in | stringstream::out);
	//	ss << "ann_prd" << _predictsize << "_neu"<< _neurons << ".xml";
	//	model_name = ss.str();
	//}

	FileStorage fsTo(model_name, cv::FileStorage::WRITE);
	ann.write(*fsTo, "ann");
}
void MainWindow::on_pushButton_test_clicked()
{

    QString str = QFileDialog::getExistingDirectory();
    QByteArray ba = str.toLocal8Bit();
    char *c_str = ba.data();
    string slash = "/";

    Mat training;
    Mat response;
    read_num_class_data("train.txt", 4, training, response);

    cout<<training.rows<<endl;
    cout<<response.rows<<endl;

    ofstream output_file;
    output_file.open("Ratio.txt");

        Mat layers = Mat(3,1,CV_32SC1);
        int sz = training.cols ;

        layers.row(0) = Scalar(sz);
        layers.row(1) = Scalar(16);
        layers.row(2) = Scalar(1);

        CvANN_MLP mlp;
        CvANN_MLP_TrainParams params;
        CvTermCriteria criteria;

        criteria.max_iter = 1000;
        criteria.epsilon  = 0.00001f;
        criteria.type     = CV_TERMCRIT_ITER | CV_TERMCRIT_EPS;

        params.train_method    = CvANN_MLP_TrainParams::BACKPROP;
        params.bp_dw_scale     = 0.1f;
        params.bp_moment_scale = 0.1f;
        params.term_crit       = criteria;

        mlp.create(layers,CvANN_MLP::SIGMOID_SYM);
        int i = mlp.train(training, response, Mat(),Mat(),params);                              // Train dataset

        FileStorage fs("mlp.xml",  FileStorage::WRITE); // or xml
        mlp.write(*fs, "mlp"); // don't think too much about the deref, it casts to a FileNode
        ui->label_training->setText("Training finish");
        //mlp.load("mlp.xml","mlp");                                                                //Load ANN weights for each layer


    vector<string> img_name;

    string output_directory = "output_img/";
    img_name = listFile(c_str);

    Mat testing(1, 3, CV_32FC1);
    Mat predict (1 , 1, CV_32F );
    int file_num = 0;

    for(int i = 0; i < img_name.size(); i++)                         //size of the img_name
    {
     ui->progressBar->setValue(i*100/img_name.size());
     string file_name = c_str + slash + img_name[i];

     Mat img_test = imread(file_name);
     Mat img_test_clone = img_test.clone();

     Mat img_thresh, img_thresh_copy, img_HSV, img_gray;
     vector<Mat> img_split;
     cvtColor(img_test_clone, img_HSV, CV_RGB2HSV);
     cvtColor(img_test_clone, img_gray, CV_RGB2GRAY);
     split(img_HSV, img_split);
     threshold(img_split[0], img_thresh, 75, 255, CV_THRESH_BINARY);
     img_thresh_copy = img_thresh.clone();

     Mat hole = img_thresh_copy.clone();
     floodFill(hole, Point(0,0), Scalar(255));
     bitwise_not(hole, hole);
     img_thresh_copy = (img_thresh_copy | hole);

     Mat element = getStructuringElement(MORPH_RECT, Size(15, 15));
     Mat open_result;
     morphologyEx(img_thresh, open_result, MORPH_CLOSE, element );

     int infected_num = 0;
     int total_pixels = 0;

     if(img_test.data)
     {
         file_num++;
            for (int m = 0; m < img_test.rows; m++)
            {
             for (int n = 0; n < img_test.cols; n++)
             {
                 if (img_thresh_copy.at<uchar>(m, n) == 255)
                 {
                  total_pixels++;
                  testing.at<float>(0, 0) = (float)img_test.at<Vec3b>(m, n)[0];
                  testing.at<float>(0, 1) = (float)img_test.at<Vec3b>(m, n)[1];
                  testing.at<float>(0, 2) = (float)img_test.at<Vec3b>(m, n)[2];

                  mlp.predict(testing,predict);
                  float a = predict.at<float>(0,0);


                  if (a < 0.4)     //0.4
                  {
                      img_test.at<Vec3b>(m, n)[0] = 0;
                      img_test.at<Vec3b>(m, n)[1] = 0;
                      img_test.at<Vec3b>(m, n)[2] = 255;
                      infected_num++;
                  }
                 }
             }

            }
     float ratio = (float)infected_num / total_pixels * 100;
     output_file<<img_name[i]<<"          "<<(ratio)<<endl;

     string output_file_name = output_directory + img_name[i];
     cout<<output_file_name<<endl;
     imwrite(output_file_name, img_test);

     QImage img_qt = QImage((const unsigned char*)(img_test_clone.data), img_test_clone.cols, img_test_clone.rows, QImage::Format_RGB888);
     QImage img_qt_result = QImage((const unsigned char*)(img_test.data), img_test.cols, img_test.rows, QImage::Format_RGB888);
     //ui->label_original->setPixmap(QPixmap::fromImage(img_qt.rgbSwapped()));
     //ui->label_resulting->setPixmap(QPixmap::fromImage((img_qt_result.rgbSwapped())));

    // imshow("Ori", img_thresh_copy);
     imshow("split", img_test);
     waitKey(0);
     QThread::msleep(100);
     }
     else
     {
      continue;
     }
    }
    ui->progressBar->setValue(100);
    output_file<<endl<<endl<<"Number of processed images:       "<<file_num<<endl;
    cout<<"Test finished!";
}