Advertisement
anta40

Form1.h

May 8th, 2017
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.72 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <fstream>
  6. #include <sstream>
  7.  
  8. #include "opencv2/core/core.hpp"
  9. #include "opencv2/opencv.hpp"
  10. #include "opencv2/face.hpp"
  11. #include "opencv2/highgui/highgui.hpp"
  12. #include "opencv2/imgproc/imgproc.hpp"
  13. #include "opencv2/objdetect/objdetect.hpp"
  14.  
  15. namespace FaceTracking4 {
  16.  
  17.     using namespace System;
  18.     using namespace System::ComponentModel;
  19.     using namespace System::Collections;
  20.     using namespace System::Windows::Forms;
  21.     using namespace System::Data;
  22.     using namespace System::Drawing;
  23.     using namespace cv;
  24.     using namespace std;
  25.     using namespace System::Runtime::InteropServices;
  26.  
  27.     /// <summary>
  28.     /// Summary for Form1
  29.     /// </summary>
  30.     public ref class Form1 : public System::Windows::Forms::Form
  31.     {
  32.     public:
  33.         Form1(void)
  34.         {
  35.             InitializeComponent();
  36.             //
  37.             //TODO: Add the constructor code here
  38.             //
  39.         }
  40.         static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator)
  41.         {
  42.             std::ifstream file(filename.c_str(), ifstream::in);
  43.             if (!file)
  44.             {
  45.                 string error_message = "No valid input file was given, please check the given filename.";
  46.                 CV_Error(CV_StsBadArg, error_message);
  47.             }
  48.             string line, path, classlabel;
  49.             while (getline(file, line))
  50.             {
  51.                 stringstream liness(line);
  52.                 getline(liness, path, separator);
  53.                 getline(liness, classlabel);
  54.                 if(!path.empty() && !classlabel.empty())
  55.                 {
  56.                     images.push_back(imread(path, 0));
  57.                     labels.push_back(atoi(classlabel.c_str()));
  58.                 }
  59.             }
  60.         }
  61.  
  62.     protected:
  63.         /// <summary>
  64.         /// Clean up any resources being used.
  65.         /// </summary>
  66.         ~Form1()
  67.         {
  68.             if (components)
  69.             {
  70.                 delete components;
  71.             }
  72.         }
  73.  
  74.     protected:
  75.     private: System::Windows::Forms::Panel^  panel1;
  76.     private: System::Windows::Forms::Button^  button1;
  77.     private: System::Windows::Forms::OpenFileDialog^  openFileDialog1;
  78.     private: System::Windows::Forms::PictureBox^  pictureBox1;
  79.  
  80.     private:
  81.         /// <summary>
  82.         /// Required designer variable.
  83.         /// </summary>
  84.         System::ComponentModel::Container ^components;
  85.  
  86. #pragma region Windows Form Designer generated code
  87.         /// <summary>
  88.         /// Required method for Designer support - do not modify
  89.         /// the contents of this method with the code editor.
  90.         /// </summary>
  91.         void InitializeComponent(void)
  92.         {
  93.             this->panel1 = (gcnew System::Windows::Forms::Panel());
  94.             this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
  95.             this->button1 = (gcnew System::Windows::Forms::Button());
  96.             this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
  97.             this->panel1->SuspendLayout();
  98.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();
  99.             this->SuspendLayout();
  100.             //
  101.             // panel1
  102.             //
  103.             this->panel1->AutoScroll = true;
  104.             this->panel1->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
  105.             this->panel1->Controls->Add(this->pictureBox1);
  106.             this->panel1->Location = System::Drawing::Point(16, 15);
  107.             this->panel1->Name = L"panel1";
  108.             this->panel1->Size = System::Drawing::Size(676, 396);
  109.             this->panel1->TabIndex = 3;
  110.             //
  111.             // pictureBox1
  112.             //
  113.             this->pictureBox1->Location = System::Drawing::Point(3, 3);
  114.             this->pictureBox1->Name = L"pictureBox1";
  115.             this->pictureBox1->Size = System::Drawing::Size(668, 388);
  116.             this->pictureBox1->TabIndex = 0;
  117.             this->pictureBox1->TabStop = false;
  118.             //
  119.             // button1
  120.             //
  121.             this->button1->Location = System::Drawing::Point(301, 421);
  122.             this->button1->Name = L"button1";
  123.             this->button1->Size = System::Drawing::Size(103, 23);
  124.             this->button1->TabIndex = 0;
  125.             this->button1->Text = L"Load Video";
  126.             this->button1->UseVisualStyleBackColor = true;
  127.             this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
  128.             //
  129.             // openFileDialog1
  130.             //
  131.             this->openFileDialog1->FileName = L"openFileDialog1";
  132.             //
  133.             // Form1
  134.             //
  135.             this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
  136.             this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
  137.             this->ClientSize = System::Drawing::Size(704, 452);
  138.             this->Controls->Add(this->button1);
  139.             this->Controls->Add(this->panel1);
  140.             this->Name = L"Form1";
  141.             this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
  142.             this->Text = L"Face Tracking";
  143.             this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
  144.             this->Move += gcnew System::EventHandler(this, &Form1::Form1_Move);
  145.             this->panel1->ResumeLayout(false);
  146.             (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();
  147.             this->ResumeLayout(false);
  148.  
  149.         }
  150. #pragma endregion
  151.     private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
  152.              {
  153.                 //pictureBox1->Image=Image::FromFile("5.jpg");
  154.                 if(openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)  
  155.                 {  
  156.                     string fn_csv = "test.txt";
  157.                     vector<Mat> images;
  158.                     vector<int> labels;
  159.                     // Read in the data (fails if no valid input filename is given, but you'll get an error message):
  160.                     try
  161.                     {
  162.                         read_csv(fn_csv, images, labels,';');
  163.                         //images.push_back(imread("person0/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0);
  164.                         //images.push_back(imread("person0/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(0);
  165.                         //images.push_back(imread("person1/0.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1);
  166.                         //images.push_back(imread("person1/1.jpg", CV_LOAD_IMAGE_GRAYSCALE)); labels.push_back(1);
  167.                     }
  168.                     catch (cv::Exception& e)
  169.                     {
  170.                         //cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
  171.                         // nothing more we can do
  172.                         MessageBox::Show("Error opening file");
  173.                         return;
  174.                     }
  175.                     // Get the height from the first image. We'll need this
  176.                     // later in code to reshape the images to their original
  177.                     // size AND we need to reshape incoming faces to this size:
  178.                     int im_width = images[0].cols;
  179.                     int im_height = images[0].rows;
  180.                     // Create a FaceRecognizer and train it on the given images:
  181.                     Ptr<FaceRecognizer> model = createFisherFaceRecognizer();
  182.                     //Ptr<FaceRecognizer> model = createFisherFaceRecognizer(0, DBL_MAX);
  183.                     model->train(images, labels);
  184.  
  185.                     CascadeClassifier haar_cascade;
  186.                     haar_cascade.load("haarcascade_frontalface_default.xml");
  187.  
  188.                     char *fileName = (char*) Marshal::StringToHGlobalAnsi(openFileDialog1->FileName).ToPointer();
  189.                     VideoCapture cap(fileName);
  190.  
  191.                     if(!cap.isOpened())  // if not success, exit program
  192.                     {
  193.                         MessageBox::Show("Cannot open the video file");
  194.                         return;
  195.                     }
  196.  
  197.                     double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
  198.  
  199.                     //MessageBox::Show(fps.ToString());
  200.                    
  201.                     namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
  202.                     moveWindow("MyVideo",this->Left + 40,this->Top + 60);
  203.                     pictureBox1->Width=cap.get(CV_CAP_PROP_FRAME_WIDTH);
  204.                     pictureBox1->Height=cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  205.  
  206.                     double count;
  207.                     count = 1;
  208.  
  209.                     while(1)
  210.                     {
  211.                         //cap.set(CV_CAP_PROP_POS_FRAMES, count); //start the video at 300ms
  212.        
  213.                         Mat frame;
  214.  
  215.                         bool bSuccess = cap.read(frame); // read a new frame from video
  216.  
  217.                         if (!bSuccess) //if not success, break loop
  218.                         {
  219.                             //MessageBox::Show("The end");
  220.                             destroyWindow("MyVideo");
  221.                             break;
  222.                         }
  223.  
  224.                         Mat original = frame.clone();
  225.                         // Convert the current frame to grayscale:
  226.                         Mat gray;
  227.                         cvtColor(original, gray, CV_BGR2GRAY);
  228.                         // Find the faces in the frame:
  229.                         vector< Rect_<int> > faces;
  230.                         haar_cascade.detectMultiScale(gray, faces);
  231.                         // At this point you have the position of the faces in
  232.                         // faces. Now we'll get the faces, make a prediction and
  233.                         // annotate it in the video. Cool or what?
  234.  
  235.                         for(int i = 0; i < faces.size(); i++)
  236.                         {
  237.                             // Process face by face:
  238.                             Rect face_i = faces[i];
  239.                             // Crop the face from the image. So simple with OpenCV C++:
  240.                             Mat face = gray(face_i);
  241.                             // Resizing the face is necessary for Eigenfaces and Fisherfaces. You can easily
  242.                             // verify this, by reading through the face recognition tutorial coming with OpenCV.
  243.                             // Resizing IS NOT NEEDED for Local Binary Patterns Histograms, so preparing the
  244.                             // input data really depends on the algorithm used.
  245.                             //
  246.                             // I strongly encourage you to play around with the algorithms. See which work best
  247.                             // in your scenario, LBPH should always be a contender for robust face recognition.
  248.                             //
  249.                             // Since I am showing the Fisherfaces algorithm here, I also show how to resize the
  250.                             // face you have just found:
  251.                             Mat face_resized;
  252.                             cv::resize(face, face_resized, cv::Size(im_width, im_height), 1.0, 1.0, INTER_CUBIC);
  253.                             // Now perform the prediction, see how easy that is:
  254.                             int prediction = model->predict(face_resized);
  255.                             // And finally write all we've found out to the original image!
  256.                             // First of all draw a green rectangle around the detected face:
  257.                             rectangle(original, face_i, CV_RGB(0, 255,0), 1);
  258.                             // Create the text we will annotate the box with:
  259.                             string box_text = format("Prediction = %d", prediction);
  260.                             //string box_text = format("Prediction");
  261.                             // Calculate the position for annotated text (make sure we don't
  262.                             // put illegal values in there):
  263.                             int pos_x = std::max(face_i.tl().x - 10, 0);
  264.                             int pos_y = std::max(face_i.tl().y - 10, 0);
  265.                             // And now put it into the image:
  266.                             putText(original, box_text,cv::Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.0, CV_RGB(0,255,0), 2.0);
  267.                         }
  268.  
  269.                         //imshow("MyVideo", frame); //show the frame in "MyVideo" window
  270.                         imshow("MyVideo", original); //show the frame in "MyVideo" window
  271.        
  272.                         //pictureBox1->Width=cap.get(CV_CAP_PROP_FRAME_WIDTH);
  273.                         //pictureBox1->Height=cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  274.                        
  275.                         /*System::Drawing::Graphics^ graphics2 = pictureBox1->CreateGraphics();
  276.                         System::IntPtr ptr2(original.ptr());
  277.                         System::Drawing::Bitmap^ b2  = gcnew System::Drawing::Bitmap(original.cols,original.rows,original.step,System::Drawing::Imaging::PixelFormat::Format24bppRgb,ptr2);
  278.                         System::Drawing::RectangleF rect2(0,0, pictureBox1->Width,pictureBox1->Height);
  279.                         //System::Drawing::RectangleF rect2(0,0, original.cols,original.rows);
  280.                         graphics2->DrawImage(b2,rect2);
  281.                         //pictureBox1->Refresh();
  282.                         delete graphics2;*/
  283.  
  284.                         /*assert(original.type() == CV_8UC3);
  285.                         if ((pictureBox1->Image == nullptr) || (pictureBox1->Width != original.cols) || (pictureBox1->Height != original.rows))
  286.                         {
  287.                             pictureBox1->Width = original.cols;
  288.                             pictureBox1->Height = original.rows;
  289.                             pictureBox1->Image = gcnew System::Drawing::Bitmap(original.cols, original.rows);
  290.                         }
  291.                         // Create System::Drawing::Bitmap from cv::Mat
  292.                         System::Drawing::Bitmap^ bmpImage = gcnew Bitmap(original.cols, original.rows, original.step,System::Drawing::Imaging::PixelFormat::Format24bppRgb,System::IntPtr(original.data));
  293.                         // Draw Bitmap over a PictureBox
  294.                         Graphics^ g = Graphics::FromImage(pictureBox1->Image);
  295.                         g->DrawImage(bmpImage, 0, 0, original.cols, original.rows);  
  296.                         pictureBox1->Refresh();
  297.                         delete g;*/
  298.  
  299.                         /*System::Drawing::Graphics^ graphics = pictureBox1->CreateGraphics();
  300.                         System::IntPtr ptr(original.ptr());
  301.                         System::Drawing::Bitmap^ b  = gcnew System::Drawing::Bitmap(original.cols,original.rows,original.step,System::Drawing::Imaging::PixelFormat::Format24bppRgb,ptr);
  302.                         System::Drawing::RectangleF rect(0,0,pictureBox1->Width,pictureBox1->Height);
  303.                         graphics->DrawImage(b,rect);
  304.                         delete graphics;*/
  305.  
  306.                         if(waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
  307.                         {
  308.                                 MessageBox::Show("esc key is pressed by user");
  309.                                 destroyWindow("MyVideo");
  310.                                 destroyAllWindows();
  311.                                 break;
  312.                         }
  313.  
  314.                         //count+=5;
  315.                         count++;
  316.                         //cout <<count<<endl;
  317.                     }
  318.  
  319.  
  320.                     //MessageBox::Show(openFileDialog1->FileName);  
  321.                     //pictureBox1->Image=Image::FromFile(openFileDialog1->FileName);
  322.                     System::Drawing::Image^ img = pictureBox1->Image;
  323.                     pictureBox1->Image = nullptr;
  324.                     delete img;
  325.                 }  
  326.              }
  327.     private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)
  328.              {
  329.              }
  330.     private: System::Void Form1_Move(System::Object^  sender, System::EventArgs^  e)
  331.              {
  332.                 moveWindow("MyVideo",this->Left + 40,this->Top + 60);
  333.                 //updateWindow("MyVideo");
  334.                 //cvGetWindowHandle("MyVideo");
  335.              }
  336. };
  337. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement