Integrating IronPython with a Windows Form Application RRS feed

  • Question

  • As per the title, I am having a hard time getting this code to work. Here is the idea. Browse for a .MP4 file, break it into its component frames, and for each frame, use template detection to look for a paw. I am using a Windows Form Application for C# language.

    The error message is at the very bottom of the C# code, marked with ***. The errorm message is

    Microsoft.Scripting.SyntaxErrorException: 'unexpected token ':''

    I cannot find a single thread that relates to this error token. I have ran the test every which way, removing and moving colons (hehe) every which way to see if it will work, and the tokens are all the same.

    I have included the following NuGet Packages:


    IronPython 2.7.9


    Dynamic Language Runtime

    Here is the C# code

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

    using IronPython.Hosting;
    using Accord.Video.FFMPEG;

    namespace FileScanner
        public partial class Form1 : Form
            public Form1()

            private void Form1_Load(object sender, EventArgs e)
                Button1.Enabled = true;
                Button2.Enabled = false;

            public void Button1_Click(object sender, EventArgs e)
                //references: https://www.c-sharpcorner.com/UploadFile/mahesh/openfiledialog-in-C-Sharp/

                OpenFileDialog finder = new OpenFileDialog()
                    InitialDirectory = @"C:\",
                    Title = "Find .MP4",

                    RestoreDirectory = true,

                    CheckFileExists = true,
                    CheckPathExists = true,

                    Filter = "All files (*.*)|*.*"


                if(finder.ShowDialog() == DialogResult.OK)
                    RichTextBox1.Text = finder.FileName;
                    Button2.Enabled = true;

            private void RichTextBox1_TextChanged(object sender, EventArgs e)


            private void Button2_Click(object sender, EventArgs e)
                //references: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch


            private void CheckFile()
                    string path = RichTextBox1.Text;

                catch (ArgumentException e) when (e.ParamName == "")
                    MessageBox.Show("File Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            private void BreakFile()
                VideoFileReader reader = new VideoFileReader();

                var framesToCheck = reader.FrameCount * reader.FrameRate;

                for (int d = 0; d < framesToCheck; d++)
                    Bitmap videoFrame = reader.ReadVideoFrame(d);



            private void ScanFile(Bitmap img)
                //References: https://www.youtube.com/watch?v=g1VWGdHRkHs
                //            https://documentation.help/IronPython/getting_started.html

                var engine = Python.CreateEngine();
                var script = @"C:\Users\BeckerLab\source\repos\FileScanner\PythonScanner\PythonScanner.py";
                var source = engine.CreateScriptSourceFromString(script);

                // C:\Users\BeckerLab\source\repos\ContingencyTestTwo\PythAnalysis\PythAnalysis.py

                var fling = img;

                //#references:    https://towardsdatascience.com/object-detection-with-less-than-10-lines-of-code-using-python-2d28eebc5b11
                //#               https://github.com/arunponnusamy/cvlib/blob/master/cvlib/object_detection.py
                //#               https://pythonprogramming.net/loading-video-python-opencv-tutorial/?completed=/loading-images-python-opencv-tutorial/

                var eIO = engine.Runtime.IO;
                var errors = new System.IO.MemoryStream();
                eIO.SetErrorOutput(errors, Encoding.Default);

                var results = new System.IO.MemoryStream();
                eIO.SetOutput(results, Encoding.Default);

                var scope = engine.CreateScope();
                engine.GetSysModule().SetVariable("image", fling);
                source.Execute(scope);                                                       *** Here is where error hits

    Here is the Python File

    import os
    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    import cvlib.object_detection

    image = sys.fling

    I = cv2.imread(image)
    Ig = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)

    temp_imgR = cv2.imread('C:\\Users\BeckerLab\source\repos\FileScanner\Right.jpg', 0)  #Step 3. Collect metrics from the analysis
    f,g = temp_imgR.shape[::-1]

    temp_imgL = cv2.imread('C:\\Users\BeckerLab\source\repos\FileScanner\Left.jpg', 0)
    a,b = temp_imgL.shape[::-1]

    thresh = 0.8  

    resR = cv2.matchTemplate(Ig, temp_imgR, cv2.TM_CCOEFF_NORMED)
    resL = cv2.matchTemplate(Ig, temp_imgL, cv2.TM_CCOEFF_NORMED)

    locR = np.where(resR >= thresh)
    locL = np.where(resL >= thresh)

    #for pt in zip(*locR[::-1]):
    #    cv2.rectangle(I, pt, (pt[0]+f, pt[1]+g), (0,0,255), 1)
    #    numR += 1
    #    if numR == 1:
    #        break

    #for qt in zip(*locL[::-1]):
    #   cv2.rectangle(I, qt, (qt[0]+a, qt[1]+b), (255,0,0), 1)
    #   numL += 1
    #   if numL == 1:
    #       break

    #plt.imshow(output_image)    #Step 5. Return the results of the image.

    sys.fling = I


    *Can't show images yet, apparently. Too new to this site.

    Monday, March 30, 2020 5:47 PM

All replies

  • CreateScriptSourceFromString expects you to pass in Python code.  You're giving it a filename, which has a colon as the second character.

    I suspect you want CreateScriptSourceFromFile.

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Monday, March 30, 2020 8:05 PM
  • That was helpful, but it turned out through my studies that IronPython is stuck on 2.7.9, and does not support cv2. This library is essential to my implementation, so i need to move on. Thank you for your help.
    Monday, March 30, 2020 11:54 PM
  • Hi GFK_010,
    Based on your description, it is related to IronPython. So it is recommended to submit an issue on the IronPython GitHub project and you can get more professional answer.
    Thank you for your understanding.
    Best Regards,
    Daniel Zhang

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, March 31, 2020 1:56 AM