2015-05-04 67 views
0

當我嘗試創建另一個窗體的窗體對象時,我收到以下錯誤消息。 任何人都可以幫助我,這個錯誤的解決方案是什麼?創建另一個表單問題的表單對象?

enter image description here

這就需要作爲對象要創建的Training_form是:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

using Emgu.CV.UI; 
using Emgu.CV; 
using Emgu.CV.Structure; 
using Emgu.CV.CvEnum; 

using System.IO; 
using System.Drawing.Imaging; 
using System.Xml; 
using System.Threading; 


namespace Face_Recognition 
{ 
    public partial class Training_Form : Form 
    { 
     #region Variables 
     //Camera specific 
     Capture grabber; 

     //Images for finding face 
     Image<Bgr, Byte> currentFrame; 
     Image<Gray, byte> result = null; 
     Image<Gray, byte> gray_frame = null; 

     //Classifier 
     CascadeClassifier Face; 

     //For aquiring 10 images in a row 
     List<Image<Gray, byte>> resultImages = new List<Image<Gray, byte>>(); 
     int results_list_pos = 0; 
     int num_faces_to_aquire = 10; 
     bool RECORD = false; 

     //Saving Jpg 
     List<Image<Gray, byte>> ImagestoWrite = new List<Image<Gray, byte>>(); 
     EncoderParameters ENC_Parameters = new EncoderParameters(1); 
     EncoderParameter ENC = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100); 
     ImageCodecInfo Image_Encoder_JPG; 

     //Saving XAML Data file 
     List<string> NamestoWrite = new List<string>(); 
     List<string> NamesforFile = new List<string>(); 
     XmlDocument docu = new XmlDocument(); 

     //Variables 
     Form1 Parent; 
     #endregion 

     public Training_Form(Form1 _Parent) 
     { 
      InitializeComponent(); 
      Parent = _Parent; 
      Face = Parent.Face; 
      //Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml"); 
      ENC_Parameters.Param[0] = ENC; 
      Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg); 
      initialise_capture(); 
     } 

     private void Training_Form_FormClosing(object sender, FormClosingEventArgs e) 
     { 
      stop_capture(); 
      Parent.retrain(); 
      Parent.initialise_capture(); 
     } 

     //Camera Start Stop 
     public void initialise_capture() 
     { 
      grabber = new Capture(); 
      grabber.QueryFrame(); 
      //Initialize the FrameGraber event 
      Application.Idle += new EventHandler(FrameGrabber); 
     } 
     private void stop_capture() 
     { 
      Application.Idle -= new EventHandler(FrameGrabber); 
      if (grabber != null) 
      { 
       grabber.Dispose(); 
      } 
      //Initialize the FrameGraber event 
     } 

     //Process Frame 
     void FrameGrabber(object sender, EventArgs e) 
     { 
      //Get the current frame form capture device 
      currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC); 

      //Convert it to Grayscale 
      if (currentFrame != null) 
      { 
       gray_frame = currentFrame.Convert<Gray, Byte>(); 

       //Face Detector 
       //MCvAvgComp[][] facesDetected = gray_frame.DetectHaarCascade(Face, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20)); //old method 
       Rectangle[] facesDetected = Face.DetectMultiScale(gray_frame, 1.2, 10, new Size(50, 50), Size.Empty); 

       //Action for each element detected 
       for(int i = 0; i< facesDetected.Length; i++)// (Rectangle face_found in facesDetected) 
       { 
        //This will focus in on the face from the haar results its not perfect but it will remove a majoriy 
        //of the background noise 
        facesDetected[i].X += (int)(facesDetected[i].Height * 0.15); 
        facesDetected[i].Y += (int)(facesDetected[i].Width * 0.22); 
        facesDetected[i].Height -= (int)(facesDetected[i].Height * 0.3); 
        facesDetected[i].Width -= (int)(facesDetected[i].Width * 0.35); 

        result = currentFrame.Copy(facesDetected[i]).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC); 
        result._EqualizeHist(); 
        face_PICBX.Image = result.ToBitmap(); 
        //draw the face detected in the 0th (gray) channel with blue color 
        currentFrame.Draw(facesDetected[i], new Bgr(Color.Red), 2); 

       } 
       if (RECORD && facesDetected.Length > 0 && resultImages.Count < num_faces_to_aquire) 
       { 
        resultImages.Add(result); 
        count_lbl.Text = "Count: " + resultImages.Count.ToString(); 
        if (resultImages.Count == num_faces_to_aquire) 
        { 
         ADD_BTN.Enabled = true; 
         NEXT_BTN.Visible = true; 
         PREV_btn.Visible = true; 
         count_lbl.Visible = false; 
         Single_btn.Visible = true; 
         ADD_ALL.Visible = true; 
         RECORD = false; 
         Application.Idle -= new EventHandler(FrameGrabber); 
        } 
       } 

       image_PICBX.Image = currentFrame.ToBitmap(); 
      } 
     } 

     //Saving The Data 
     private bool save_training_data(Image face_data) 
     { 
      try 
      { 
       Random rand = new Random(); 
       bool file_create = true; 
       string facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg"; 
       while (file_create) 
       { 

        if (!File.Exists(Application.StartupPath + "/TrainedFaces/" + facename)) 
        { 
         file_create = false; 
        } 
        else 
        { 
         facename = "face_" + NAME_PERSON.Text + "_" + rand.Next().ToString() + ".jpg"; 
        } 
       } 


       if(Directory.Exists(Application.StartupPath + "/TrainedFaces/")) 
       { 
        face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg); 
       } 
       else 
       { 
        Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/"); 
        face_data.Save(Application.StartupPath + "/TrainedFaces/" + facename, ImageFormat.Jpeg); 
       } 
       if (File.Exists(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml")) 
       { 
        //File.AppendAllText(Application.StartupPath + "/TrainedFaces/TrainedLabels.txt", NAME_PERSON.Text + "\n\r"); 
        bool loading = true; 
        while (loading) 
        { 
         try 
         { 
          docu.Load(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"); 
          loading = false; 
         } 
         catch 
         { 
          docu = null; 
          docu = new XmlDocument(); 
          Thread.Sleep(10); 
         } 
        } 

        //Get the root element 
        XmlElement root = docu.DocumentElement; 

        XmlElement face_D = docu.CreateElement("FACE"); 
        XmlElement name_D = docu.CreateElement("NAME"); 
        XmlElement file_D = docu.CreateElement("FILE"); 

        //Add the values for each nodes 
        //name.Value = textBoxName.Text; 
        //age.InnerText = textBoxAge.Text; 
        //gender.InnerText = textBoxGender.Text; 
        name_D.InnerText = NAME_PERSON.Text; 
        file_D.InnerText = facename; 

        //Construct the Person element 
        //person.Attributes.Append(name); 
        face_D.AppendChild(name_D); 
        face_D.AppendChild(file_D); 

        //Add the New person element to the end of the root element 
        root.AppendChild(face_D); 

        //Save the document 
        docu.Save(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"); 
        //XmlElement child_element = docu.CreateElement("FACE"); 
        //docu.AppendChild(child_element); 
        //docu.Save("TrainedLabels.xml"); 
       } 
       else 
       { 
        FileStream FS_Face = File.OpenWrite(Application.StartupPath + "/TrainedFaces/TrainedLabels.xml"); 
        using (XmlWriter writer = XmlWriter.Create(FS_Face)) 
        { 
         writer.WriteStartDocument(); 
         writer.WriteStartElement("Faces_For_Training"); 

         writer.WriteStartElement("FACE"); 
         writer.WriteElementString("NAME", NAME_PERSON.Text); 
         writer.WriteElementString("FILE", facename); 
         writer.WriteEndElement(); 

         writer.WriteEndElement(); 
         writer.WriteEndDocument(); 
        } 
        FS_Face.Close(); 
       } 

       return true; 
      } 
      catch (Exception ex) 
      { 
       return false; 
      } 

     } 
     private ImageCodecInfo GetEncoder(ImageFormat format) 
     { 
      ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); 
      foreach (ImageCodecInfo codec in codecs) 
      { 
       if (codec.FormatID == format.Guid) 
       { 
        return codec; 
       } 
      } 
      return null; 
     } 

     //Delete all the old training data by simply deleting the folder 
     private void Delete_Data_BTN_Click(object sender, EventArgs e) 
     { 
      if (Directory.Exists(Application.StartupPath + "/TrainedFaces/")) 
      { 
       Directory.Delete(Application.StartupPath + "/TrainedFaces/", true); 
       Directory.CreateDirectory(Application.StartupPath + "/TrainedFaces/"); 
      } 
     } 

     //Add the image to training data 
     private void ADD_BTN_Click(object sender, EventArgs e) 
     { 
      if (resultImages.Count == num_faces_to_aquire) 
      { 
       if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      else 
      { 
       stop_capture(); 
       if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error); 
       initialise_capture(); 
      } 
     } 
     private void Single_btn_Click(object sender, EventArgs e) 
     { 
      RECORD = false; 
      resultImages.Clear(); 
      NEXT_BTN.Visible = false; 
      PREV_btn.Visible = false; 
      Application.Idle += new EventHandler(FrameGrabber); 
      Single_btn.Visible = false; 
      count_lbl.Text = "Count: 0"; 
      count_lbl.Visible = true; 
     } 
     //Get 10 image to train 
     private void RECORD_BTN_Click(object sender, EventArgs e) 
     { 
      if (RECORD) 
      { 
       RECORD = false; 
      } 
      else 
      { 
       if (resultImages.Count == 10) 
       { 
        resultImages.Clear(); 
        Application.Idle += new EventHandler(FrameGrabber); 
       } 
       RECORD = true; 
       ADD_BTN.Enabled = false; 
      } 

     } 
     private void NEXT_BTN_Click(object sender, EventArgs e) 
     { 
      if (results_list_pos < resultImages.Count - 1) 
      { 
       face_PICBX.Image = resultImages[results_list_pos].ToBitmap(); 
       results_list_pos++; 
       PREV_btn.Enabled = true; 
      } 
      else 
      { 
       NEXT_BTN.Enabled = false; 
      } 
     } 
     private void PREV_btn_Click(object sender, EventArgs e) 
     { 
      if (results_list_pos > 0) 
      { 
       results_list_pos--; 
       face_PICBX.Image = resultImages[results_list_pos].ToBitmap(); 
       NEXT_BTN.Enabled = true; 
      } 
      else 
      { 
       PREV_btn.Enabled = false; 
      } 
     } 
     private void ADD_ALL_Click(object sender, EventArgs e) 
     { 
      for(int i = 0; i<resultImages.Count;i++) 
      { 
       face_PICBX.Image = resultImages[i].ToBitmap(); 
       if (!save_training_data(face_PICBX.Image)) MessageBox.Show("Error", "Error in saving file info. Training data not saved", MessageBoxButtons.OK, MessageBoxIcon.Error); 
       Thread.Sleep(100); 
      } 
      ADD_ALL.Visible = false; 
      //restart single face detection 
      Single_btn_Click(null, null); 
     } 

     private void Training_Form_Load(object sender, EventArgs e) 
     { 

     } 

    } 
} 

這就需要創建對象的Training_Form是以下形式:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

using System.IO; 
using System.Xml; 
using System.Runtime.InteropServices; 
using System.Threading; 
using System.Security.Principal; 
using System.Threading.Tasks; 
using Microsoft.Win32.SafeHandles; 

namespace Face_Recognition 
{ 
    public partial class mainwindow : Form 
    { 
     public mainwindow() 
     { 
      InitializeComponent(); 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      Form1 childf = new Form1(); 
      childf.ShowDialog(); 
     } 

     private void mainwindow_Load(object sender, EventArgs e) 
     { 

     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      Training_Form TF = new Training_Form(this); 
      TF.Show(); 

     } 
    } 
} 
+0

將錯誤置於您的問題的可讀文本中。您可以從錯誤列表中複製它們。它也很清楚:編譯器只能找到一個'Training_Form(Form1)'重載,其中你想傳遞的'this'顯然不是'Form1'的一個實例;這是一個「主窗口」。 – CodeCaster

回答

0

似乎this不是指Form1的實例,而是不同的Form -type Face_Recognition。但是Training_Form的構造函數只接受Form1作爲參數。因此,如果您有一個或更改構造函數的簽名,則必須傳遞Form1的實例。

也許是足夠使用Form

public Training_Form(Form _Parent) 
{ 
    InitializeComponent(); 
    Parent = _Parent; 
    Face = Parent.Face; 
    //Face = new HaarCascade(Application.StartupPath + "/Cascades/haarcascade_frontalface_alt2.xml"); 
    ENC_Parameters.Param[0] = ENC; 
    Image_Encoder_JPG = GetEncoder(ImageFormat.Jpeg); 
    initialise_capture(); 
} 

如果你需要Form1你必須通過一個實例。你在button2_Click中創建一個,但只是局部變量。你可以將其存儲在一個領域:

Form1 childf = null; 

private void button2_Click(object sender, EventArgs e) 
{ 
    if(childf == null) childf = new Form1(); 
    childf.ShowDialog(); 
} 

private void button3_Click(object sender, EventArgs e) 
{ 
    if(childf == null) childf = new Form1(); 
    Training_Form TF = new Training_Form(childf); 
    TF.Show(); 
} 
+0

謝謝。您的解決方案解決了問題。 – ensberiyu

0

Training_Form預計Form1類型的參數。

在您的代碼中,您嘗試使用關鍵字this來提供它。 this是您當前所在的對象。由於您從mainwindow中調用它,因此您正嘗試在其中放入mainwindow類型,因爲在這種情況下,mainwindow等於this

您可能通過閱讀您的代碼,意味着將childf置於或至少具有正確的類型。 這將工作,但你將不得不更多地聲明childf參數。

或者您應該將您期望在構造函數中的類型更改爲mainwindow,這樣做也可以。

0

您正在從您的程序發送培訓形式爲「this」的參數,該參數是程序的參考,因此您將收到無效參數。您需要調用以在Form1中顯示TrainingForm,或者使Form1成爲該程序的一個私有實例化成員,以便將其傳遞給TrainingForm構造函數。