PhenoCapture Scripting API Sample Programs

Select a scripting language below to browse its sample programs, or use Expand All for full viewing and PDF export.

1. VBScript (ClearScript) 9 Samples
▶

Native Windows & ClearScript VBScript automation sample programs (.vbs).

1. Clear Document Clear Document.vbs
▶
Sub Main()
    Call Action.GrayScaling()
    Call Action.CorrectUnevenIllumination(4)
    Call Action.BrightContrast(0,255,true)
    Call Action.BrightContrast(0,255,true)
End Sub
2. Create Video Create Video.vbs
▶
Sub Main()
    ' 1. Create and configure FolderBrowserDialog to select a source image folder
    Dim dlg
    Set dlg = host.newObj(Forms.FolderBrowserDialog)
    dlg.Description = "Select a folder containing images for video encoding"
    dlg.ShowNewFolderButton = False

    ' Check if the user clicked OK (using .ToString() for ClearScript Enum compatibility)
    If dlg.ShowDialog().ToString() <> "OK" Then
        dlg.Dispose()
        Exit Sub
    End If

    Dim sourceFolder, outputVideoPath
    sourceFolder = CStr(dlg.SelectedPath)
    dlg.Dispose()

    ' Set default destination video file path inside the selected folder
    If Right(sourceFolder, 1) = "\" Then
        outputVideoPath = sourceFolder & "Output_Encoded.mp4"
    Else
        outputVideoPath = sourceFolder & "\Output_Encoded.mp4"
    End If

    ' 2. Initialize folder encoding with default options (10 FPS, MP4, 4000 kbps, step = 1)
    Dim totalFrames
    totalFrames = VideoWriter.BeginFolderEncoding(CStr(sourceFolder), CStr(outputVideoPath), CInt(10), "MP4", CInt(4000), CInt(1))

    If totalFrames <= 0 Then
        Call UI.MsgBox("Failed to start video encoding: " & VideoWriter.GetLastError(), 16, "Video Encoder Error")
        Exit Sub
    End If

    ' 3. Encode each frame while displaying thumbnail and frame counter in the dedicated mini window
    Dim i, encodedCount
    encodedCount = 0

    For i = 1 To totalFrames
        ' Check if script cancellation was requested by the user
        If UI.IsCancelled Then
            Exit For
        End If

        ' Pass True to show and update the dedicated compact thumbnail & progress window
        If Not VideoWriter.EncodeNextFolderFrame(True) Then
            Call UI.MsgBox("Failed to encode frame #" & i & ": " & VideoWriter.GetLastError(), 48, "Encoding Error")
            Exit For
        End If

        encodedCount = encodedCount + 1

        ' Allow UI and the preview window to refresh smoothly
        Call UI.YieldEvents()
    Next

    ' 4. Finalize video file and automatically close the preview window
    VideoWriter.CloseVideo()

    ' 5. Show completion message
    If UI.IsCancelled Then
        Call UI.MsgBox("Encoding was cancelled by user (" & encodedCount & " / " & totalFrames & " frames encoded)." & _
                       vbCrLf & "Saved File: " & outputVideoPath, 48, "Encoding Cancelled")
    Else
        Call UI.MsgBox(encodedCount & " / " & totalFrames & " images have been successfully encoded!" & _
                       vbCrLf & vbCrLf & "Output File: " & outputVideoPath, 64, "Encoding Complete")
    End If
End Sub
3. Extract Frames Extract Frames.vbs
▶
Sub Main()
    ' 1. Create and configure OpenFileDialog to select a video file
    Dim dlg
    Set dlg = host.newObj(Forms.OpenFileDialog)
    dlg.Title = "Select a video file for frame extraction"
    dlg.Filter = "Video Files|*.mp4;*.m4v;*.mov;*.wmv;*.asf;*.mkv;*.avi;*.mpeg;*.mpg;*.ts|All Files|*.*"
    dlg.FilterIndex = 1
    dlg.CheckFileExists = True

    ' Check if the user clicked OK (using .ToString() for ClearScript Enum compatibility)
    If dlg.ShowDialog().ToString() <> "OK" Then
        dlg.Dispose()
        Exit Sub
    End If

    Dim videoPath
    videoPath = dlg.FileName
    dlg.Dispose()

    ' 2. Open the selected video file using VideoExtractor
    If Not VideoExtractor.OpenVideo(CStr(videoPath)) Then
        Call UI.MsgBox("Failed to open video: " & VideoExtractor.GetLastError(), 16, "Video Error")
        Exit Sub
    End If

    ' 3. Extract 10 frames at 1-second intervals (0s to 9s), send to Workspace, and store in Image Buffer (1 to 10)
    Dim i, targetTimeSec, frameBmp, extractedCount
    extractedCount = 0

    For i = 1 To 10
        ' Check if script cancellation was requested by the user
        If UI.IsCancelled Then
            Exit For
        End If

        ' Calculate timestamp in seconds: 0.0s, 1.0s, 2.0s, ..., 9.0s
        targetTimeSec = CDbl((i - 1) * 1.0)

        ' Extract the frame as a Bitmap object
        Set frameBmp = VideoExtractor.ExtractFrameAt(targetTimeSec)

        If frameBmp Is Nothing Then
            Call UI.MsgBox("Failed to extract frame at " & targetTimeSec & "s: " & VideoExtractor.GetLastError(), 48, "Extraction Error")
            Exit For
        End If

        ' Step A: Send the extracted frame to PhenoCapture Workspace (targetLocation = 0)
        Action.SetImage frameBmp, CInt(0)

        ' Step B: Send the current Workspace image to Image Buffer slot i (1 to 10)
        Call Action.PutToImageBuffer(CInt(i))

        ' Release the temporary Bitmap in script and allow UI to refresh
        frameBmp.Dispose()
        Call UI.YieldEvents()

        extractedCount = extractedCount + 1
    Next

    ' 4. Close the video file and release Media Foundation resources
    VideoExtractor.CloseVideo()

    ' 5. Show completion message
    Call UI.MsgBox(extractedCount & " frames have been extracted to the Workspace and stored in the Image Buffer.", 64, "Extraction Complete")
End Sub
4. Hello Hello.vbs
▶
Sub main()
   Call MsgBox("Great!", vbOKOnly, "Results")
End Sub
5. Invert Invert.vbs
▶
Sub Main()
    Dim SourceImage
    Dim OutputImage
    SourceImage = Action.GetImage(0)
    If SourceImage Is Nothing Then
        MsgBox "No image is available."
        Exit Sub
    End If
    OutputImage = ImgProc.Invert(SourceImage)
    Action.SetImage OutputImage, 0
End Sub
6. OCR Text Extraction OCR Text Extraction.vbs
▶
Sub main()  
   Dim Ret 
   Ret = Action.OCRTextExtraction() 
   
   Call UI.CopyToClipboard(Ret)
   Call UI.MsgBox(Ret, vbOKOnly, "Results")
End Sub
7. Random Lines Random Lines.vbs
▶
' Declare bmp globally so the event handler can access the generated image
Dim bmp

' Main entry point required by the ClearScript engine
Sub main()
    ' Initialize the VBScript random number generator
    Randomize

    ' 1. Create a 500x500 Bitmap and Graphics context
    Dim width, height
    width = 500
    height = 500
    
    ' Use CInt to ensure exact type matching for .NET Interop
    Set bmp = host.newObj(Drawing.Bitmap, CInt(width), CInt(height))
    
    Dim g
    Set g = Drawing.Graphics.FromImage(bmp)

    ' 2. Clear the background to White
    g.Clear Drawing.Color.White

    ' 3. Draw 100 random colored lines
    Dim i, x1, y1, x2, y2, r, g_val, b, random_color, pen
    For i = 1 To 100
        ' Generate random start and end coordinates
        x1 = CInt(width * Rnd())
        y1 = CInt(height * Rnd())
        x2 = CInt(width * Rnd())
        y2 = CInt(height * Rnd())

        ' Generate random RGB colors (0 to 255)
        r = CInt(255 * Rnd())
        g_val = CInt(255 * Rnd())
        b = CInt(255 * Rnd())
        
        Set random_color = Drawing.Color.FromArgb(r, g_val, b)

        ' Use CInt for the pen width
        Set pen = host.newObj(Drawing.Pen, random_color, CInt(1))
        g.DrawLine pen, x1, y1, x2, y2
        
        ' Dispose Pen to release GDI resources
        pen.Dispose()
    Next

    ' Dispose Graphics object after drawing is complete
    g.Dispose()

    ' =====================================================================
    ' 4. [NEW] Send the generated image directly to PhenoCapture's Workspace
    ' targetLocation = 0 represents the Workspace
    ' =====================================================================
    Action.SetImage bmp, CInt(0)

    ' 5. Create WinForms Window (Form)
    Dim form
    Set form = host.newObj(Forms.Form)
    form.Text = "PhenoCapture Script Result"
    form.Width = 550
    form.Height = 600
    form.StartPosition = Forms.FormStartPosition.CenterScreen

    ' 6. Create Copy Button and Event Handler
    Dim copy_btn
    Set copy_btn = host.newObj(Forms.Button)
    copy_btn.Text = "Copy to Clipboard"
    copy_btn.Height = 40
    copy_btn.Dock = Forms.DockStyle.Bottom

    ' Use .connect instead of .Add for VBScript event binding
    copy_btn.Click.connect GetRef("on_copy_click")

    ' 7. Create PictureBox to display the generated image
    Dim pb
    Set pb = host.newObj(Forms.PictureBox)
    pb.Image = bmp
    pb.Dock = Forms.DockStyle.Fill
    pb.SizeMode = Forms.PictureBoxSizeMode.CenterImage

    ' Add controls to the Form
    form.Controls.Add copy_btn
    form.Controls.Add pb

    ' 8. Display the Window (Modal)
    form.ShowDialog()

    ' 9. Dispose resources after closing the window
    form.Dispose()
    bmp.Dispose()
End Sub

' =========================================================
' Event Handler Definition
' =========================================================
Sub on_copy_click(sender, event_args)
    ' Enable VBScript error handling
    On Error Resume Next
    
    ' Copy the globally declared Bitmap to the Windows Clipboard
    Forms.Clipboard.SetImage bmp
    
    ' Check if any error occurred during the clipboard operation
    If Err.Number <> 0 Then
        Forms.MessageBox.Show "Failed to copy image: " & Err.Description, "Error", Forms.MessageBoxButtons.OK, Forms.MessageBoxIcon.Error
        Err.Clear
    Else
        Forms.MessageBox.Show "The image has been successfully copied to the clipboard.", "Copy Success", Forms.MessageBoxButtons.OK, Forms.MessageBoxIcon.Information
    End If
    
    ' Disable error handling
    On Error GoTo 0
End Sub
8. TestDNNClassification TestDNNClassification.vbs
▶
Sub main()
    Dim Ret
    Dim SrcImage
    
    Ret = DNNClassifier.LoadModel("C elegans Model (Mobilenet).zip")
    
    SrcImage = Action.GetImage(0)  'o indicates Workspace image
    Ret      = DNNClassifier.Predict(SrcImage)
    
    UI.MsgBox("The classified result is: " & Ret)
End Sub
9. TestObjectDetection TestObjectDetection.vbs
▶
Sub main()
    Dim Ret
    Dim SrcImage
    Dim TotalObjects
    Dim RenderedImage
    Dim CatCount
    Dim ResultMsg
    Dim success
    
    ' 1. Initialize Object Detector
    Ret = ObjectDetector.Initialize()
    If Ret = False Then
        UI.MsgBox("Error loading model: " & ObjectDetector.GetLastError())
        Exit Sub
    End If
    
    ' 2. Get Workspace image
    SrcImage = Action.GetImage(0)
    
    ' 3. Detect objects (Returns the total count)
    TotalObjects = ObjectDetector.Detect(SrcImage, 0.5, 0.4, False)
    
    If TotalObjects > 0 Then
        ' 4. Get the image with bounding boxes drawn (Image, ShowConfidence, Color)
        RenderedImage = ObjectDetector.GetRenderedImage(SrcImage, True, "Lime")
        
        If Not RenderedImage Is Nothing Then
            ' 5. Put the rendered image back into the Workspace
            success = Action.SetImage(RenderedImage, 0)
            
            ' 6. Check for specific classes and build the message
            ResultMsg = "Detection applied! Total objects drawn: " & TotalObjects & vbCrLf & vbCrLf
            
            If ObjectDetector.HasClass("cat") Then
                CatCount = ObjectDetector.GetClassCount("cat")
                ResultMsg = ResultMsg & "Success: Found " & CatCount & " cat(s) in the image."
            Else
                ResultMsg = ResultMsg & "Result: No cats were found in the image."
            End If
            
            UI.MsgBox(ResultMsg)
        Else
            UI.MsgBox("Failed to render image: " & ObjectDetector.GetLastError())
        End If
    Else
        UI.MsgBox("Detection complete! No objects were found.")
    End If
End Sub
2. JavaScript (ClearScript) 9 Samples
▶

Modern ClearScript V8 JavaScript automation sample programs (.js).

1. Clear Document Clear Document.js
▶
function main() {
    Action.GrayScaling();
    Action.CorrectUnevenIllumination(4);
    Action.BrightContrast(0, 255, true);
    Action.BrightContrast(0, 255, true);
}
2. Create Video Create Video.js
▶
function main() {
    // 1. Create and configure FolderBrowserDialog to select a source image folder
    var dlg = host.newObj(Forms.FolderBrowserDialog);
    dlg.Description = "Select a folder containing images for video encoding";
    dlg.ShowNewFolderButton = false;

    // Check if the user clicked OK (using .ToString() for ClearScript Enum compatibility)
    if (dlg.ShowDialog().ToString() !== "OK") {
        dlg.Dispose();
        return;
    }

    var sourceFolder = String(dlg.SelectedPath);
    dlg.Dispose();

    // Set default destination video file path inside the selected folder
    var outputVideoPath;
    if (sourceFolder.endsWith("\\")) {
        outputVideoPath = sourceFolder + "Output_Encoded.mp4";
    } else {
        outputVideoPath = sourceFolder + "\\Output_Encoded.mp4";
    }

    // 2. Initialize folder encoding with default options (10 FPS, MP4, 4000 kbps, step = 1)
    var totalFrames = VideoWriter.BeginFolderEncoding(
        sourceFolder,
        outputVideoPath,
        10,
        "MP4",
        4000,
        1
    );

    if (totalFrames <= 0) {
        UI.MsgBox("Failed to start video encoding: " + VideoWriter.GetLastError(), 16, "Video Encoder Error");
        return;
    }

    // 3. Encode each frame while displaying thumbnail and frame counter in the dedicated mini window
    var encodedCount = 0;

    for (var i = 1; i <= totalFrames; i++) {
        // Check if script cancellation was requested by the user
        if (UI.IsCancelled) {
            break;
        }

        // Pass true to show and update the dedicated compact thumbnail & progress window
        if (!VideoWriter.EncodeNextFolderFrame(true)) {
            UI.MsgBox("Failed to encode frame #" + i + ": " + VideoWriter.GetLastError(), 48, "Encoding Error");
            break;
        }

        encodedCount++;

        // Allow UI and the preview window to refresh smoothly
        UI.YieldEvents();
    }

    // 4. Finalize video file and automatically close the preview window
    VideoWriter.CloseVideo();

    // 5. Show completion message
    if (UI.IsCancelled) {
        UI.MsgBox(
            "Encoding was cancelled by user (" + encodedCount + " / " + totalFrames + " frames encoded).\r\n" +
            "Saved File: " + outputVideoPath,
            48,
            "Encoding Cancelled"
        );
    } else {
        UI.MsgBox(
            encodedCount + " / " + totalFrames + " images have been successfully encoded!\r\n\r\n" +
            "Output File: " + outputVideoPath,
            64,
            "Encoding Complete"
        );
    }
}
3. Extract Frames Extract Frames.js
▶
function main() {
    // 1. Create and configure OpenFileDialog to select a video file
    var dlg = host.newObj(Forms.OpenFileDialog);
    dlg.Title = "Select a video file for frame extraction";
    dlg.Filter = "Video Files|*.mp4;*.m4v;*.mov;*.wmv;*.asf;*.mkv;*.avi;*.mpeg;*.mpg;*.ts|All Files|*.*";
    dlg.FilterIndex = 1;
    dlg.CheckFileExists = true;

    // Show the dialog and check if the user clicked OK
    if (dlg.ShowDialog().ToString() !== "OK") {
        dlg.Dispose();
        return;
    }

    var videoPath = dlg.FileName;
    dlg.Dispose();

    // 2. Open the selected video file using VideoExtractor
    if (!VideoExtractor.OpenVideo(videoPath)) {
        UI.MsgBox("Failed to open video: " + VideoExtractor.GetLastError(), 16, "Video Error");
        return;
    }

    // 3. Extract 10 frames at 1-second intervals (0s to 9s), send to Workspace, and store in Image Buffer
    var extractedCount = 0;

    for (var i = 1; i <= 10; i++) {
        // Check if script cancellation was requested by the user
        if (UI.IsCancelled) {
            break;
        }

        // Calculate timestamp in seconds: 0.0s, 1.0s, 2.0s, ..., 9.0s
        var targetTimeSec = (i - 1) * 1.0;

        // Extract the frame as a Bitmap object
        var frameBmp = VideoExtractor.ExtractFrameAt(targetTimeSec);

        if (frameBmp === null) {
            UI.MsgBox("Failed to extract frame at " + targetTimeSec + "s: " + VideoExtractor.GetLastError(), 48, "Extraction Error");
            break;
        }

        // Step A: Send the extracted frame to PhenoCapture Workspace (targetLocation = 0)
        Action.SetImage(frameBmp, 0);

        // Step B: Send the current Workspace image to Image Buffer slot i (1 to 10)
        Action.PutToImageBuffer(i);

        // Release the temporary Bitmap in script and allow UI to refresh
        frameBmp.Dispose();
        UI.YieldEvents();

        extractedCount++;
    }

    // 4. Close the video file and release Media Foundation resources
    VideoExtractor.CloseVideo();

    // 5. Show completion message
    UI.MsgBox(extractedCount + " frames have been extracted to the Workspace and stored in the Image Buffer.", 64, "Extraction Complete");
}
4. Hello Hello.js
▶
function main() {
    UI.MsgBox("Hello JavaScript!");
}
5. Invert Invert.js
▶
function main() {
    const sourceImage = Action.GetImage(0);
    if (!sourceImage) {
        UI.MsgBox("No image is available.");
        return;
    }
    const outputImage = ImgProc.Invert(sourceImage);
    Action.SetImage(outputImage, 0);
}
6. OCR Text Extraction OCR Text Extraction.js
▶
function main() {
    const ret = Action.OCRTextExtraction();
    UI.CopyToClipboard(ret);
    UI.MsgBox(ret, 0, "Results"); 
}
7. Random Lines Random Lines.js
▶
function main() {
    // 1. Create a 500x500 Bitmap and Graphics context
    const width = 500;
    const height = 500;
    
    const bmp = new Drawing.Bitmap(width, height);
    const g = Drawing.Graphics.FromImage(bmp);
    
    // 2. Clear the background to White
    g.Clear(Drawing.Color.White);
    
    // 3. Draw 100 random colored lines
    for (let i = 0; i < 100; i++) {
        const x1 = Math.floor(Math.random() * width);
        const y1 = Math.floor(Math.random() * height);
        const x2 = Math.floor(Math.random() * width);
        const y2 = Math.floor(Math.random() * height);
        
        // Generate random RGB colors (0 to 255)
        const r = Math.floor(Math.random() * 256);
        const g_val = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        
        const random_color = Drawing.Color.FromArgb(r, g_val, b);
        const pen = new Drawing.Pen(random_color, 1);
        
        g.DrawLine(pen, x1, y1, x2, y2);
        
        // Dispose Pen to release GDI resources
        pen.Dispose();
    }
    
    // Dispose Graphics object
    g.Dispose();
    
    // =====================================================================
    // 4. Send the generated image directly to PhenoCapture's Workspace
    // =====================================================================
    Action.SetImage(bmp, 0);
    
    // 5. Create WinForms Window (Form)
    const form = new Forms.Form();
    form.Text = "PhenoCapture Script Result";
    form.Width = 550;
    form.Height = 600;
    form.StartPosition = Forms.FormStartPosition.CenterScreen;
    
    // 6. Create Copy Button and Event Handler
    const copy_btn = new Forms.Button();
    copy_btn.Text = "Copy to Clipboard";
    copy_btn.Height = 40;
    copy_btn.Dock = Forms.DockStyle.Bottom;
    
    copy_btn.Click.connect((sender, args) => {
        try {
            Forms.Clipboard.SetImage(bmp);
            Forms.MessageBox.Show(
                "The image has been successfully copied to the clipboard.", 
                "Copy Success", 
                Forms.MessageBoxButtons.OK, 
                Forms.MessageBoxIcon.Information
            );
        } catch (err) {
            Forms.MessageBox.Show(
                "Failed to copy image: " + err.message, 
                "Error", 
                Forms.MessageBoxButtons.OK, 
                Forms.MessageBoxIcon.Error
            );
        }
    });
    
    // 7. Create PictureBox to display the generated image
    const pb = new Forms.PictureBox();
    pb.Image = bmp;
    pb.Dock = Forms.DockStyle.Fill;
    pb.SizeMode = Forms.PictureBoxSizeMode.CenterImage;
    
    // Add controls to the Form
    form.Controls.Add(copy_btn);
    form.Controls.Add(pb);
    
    // 8. Display the Window (Modal)
    form.ShowDialog();
    
    // 9. Dispose resources after closing the window
    form.Dispose();
    bmp.Dispose();
}
8. TestDNNClassification TestDNNClassification.js
▶
function main() {
    // Load the trained model
    var isLoaded = DNNClassifier.LoadModel("C elegans Model (Mobilenet).zip");
        
    // Retrieve the image from the workspace (0 indicates Workspace image)
    var srcImage = Action.GetImage(0);

    // Predict the class of the image
    var predictedClass = DNNClassifier.Predict(srcImage);

    // Display the result to the user
    UI.MsgBox("The classified result is: " + predictedClass);
}
9. TestObjectDetection TestObjectDetection.js
▶
function main() {
    // 1. Initialize Object Detector
    var ret = ObjectDetector.Initialize();
    if (ret === false) {
        UI.MsgBox("Error loading model: " + ObjectDetector.GetLastError());
        return; // Exit function
    }
    
    // 2. Get Workspace image
    var srcImage = Action.GetImage(0);
    
    // 3. Detect objects (Returns the total count)
    var totalObjects = ObjectDetector.Detect(srcImage, 0.5, 0.4, false);
    
    if (totalObjects > 0) {
        // 4. Get the image with bounding boxes drawn (Image, ShowConfidence, Color)
        var renderedImage = ObjectDetector.GetRenderedImage(srcImage, true, "Lime");
        
        if (renderedImage !== null) {
            // 5. Put the rendered image back into the Workspace
            var success = Action.SetImage(renderedImage, 0);
            
            // 6. Check for specific classes and build the message
            var resultMsg = "Detection applied! Total objects drawn: " + totalObjects + "\n\n";
            
            if (ObjectDetector.HasClass("cat")) {
                var catCount = ObjectDetector.GetClassCount("cat");
                resultMsg += "Success: Found " + catCount + " cat(s) in the image.";
            } else {
                resultMsg += "Result: No cats were found in the image.";
            }
            
            UI.MsgBox(resultMsg);
        } else {
            UI.MsgBox("Failed to render image: " + ObjectDetector.GetLastError());
        }
    } else {
        UI.MsgBox("Detection complete! No objects were found.");
    }
}
3. Python (Python.NET) 9 Samples
▶

Python.NET scientific image processing and automation sample programs (.py).

1. Clear Document Clear Document.py
▶
def main():
     Action.GrayScaling()
     Action.CorrectUnevenIllumination(4)
     Action.BrightContrast(0,255,True)
     Action.BrightContrast(0,255,True)
2. Create Video Create Video.py
▶
import os
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import FolderBrowserDialog, DialogResult

def main():
    # 1. Create and configure FolderBrowserDialog to select a source image folder
    dlg = FolderBrowserDialog()
    dlg.Description = "Select a folder containing images for video encoding"
    dlg.ShowNewFolderButton = False

    # Check if the user clicked OK (supports both DialogResult.OK and .ToString() check)
    if dlg.ShowDialog().ToString() != "OK":
        dlg.Dispose()
        return

    source_folder = str(dlg.SelectedPath)
    dlg.Dispose()

    # Set default destination video file path inside the selected folder
    output_video_path = os.path.join(source_folder, "Output_Encoded.mp4")

    # 2. Initialize folder encoding with default options (10 FPS, MP4, 4000 kbps, step = 1)
    total_frames = VideoWriter.BeginFolderEncoding(
        source_folder,
        output_video_path,
        10,
        "MP4",
        4000,
        1
    )

    if total_frames <= 0:
        UI.MsgBox(
            "Failed to start video encoding: " + str(VideoWriter.GetLastError()),
            16,
            "Video Encoder Error"
        )
        return

    # 3. Encode each frame while displaying thumbnail and frame counter in the dedicated mini window
    encoded_count = 0

    for i in range(1, total_frames + 1):
        # Check if script cancellation was requested by the user
        if UI.IsCancelled:
            break

        # Pass True to show and update the dedicated compact thumbnail & progress window
        if not VideoWriter.EncodeNextFolderFrame(True):
            UI.MsgBox(
                f"Failed to encode frame #{i}: {VideoWriter.GetLastError()}",
                48,
                "Encoding Error"
            )
            break

        encoded_count += 1

        # Allow UI and the preview window to refresh smoothly
        UI.YieldEvents()

    # 4. Finalize video file and automatically close the preview window
    VideoWriter.CloseVideo()

    # 5. Show completion message
    if UI.IsCancelled:
        UI.MsgBox(
            f"Encoding was cancelled by user ({encoded_count} / {total_frames} frames encoded).\r\n"
            f"Saved File: {output_video_path}",
            48,
            "Encoding Cancelled"
        )
    else:
        UI.MsgBox(
            f"{encoded_count} / {total_frames} images have been successfully encoded!\r\n\r\n"
            f"Output File: {output_video_path}",
            64,
            "Encoding Complete"
        )
3. Extract Frames Extract Frames.py
▶
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import OpenFileDialog, DialogResult

def main():
    # 1. Create and configure OpenFileDialog to select a video file
    dlg = OpenFileDialog()
    dlg.Title = "Select a video file for frame extraction"
    dlg.Filter = "Video Files|*.mp4;*.m4v;*.mov;*.wmv;*.asf;*.mkv;*.avi;*.mpeg;*.mpg;*.ts|All Files|*.*"
    dlg.FilterIndex = 1
    dlg.CheckFileExists = True

    # Show the dialog and check if the user clicked OK
    if dlg.ShowDialog() != DialogResult.OK:
        dlg.Dispose()
        return

    video_path = dlg.FileName
    dlg.Dispose()

    # 2. Open the selected video file using VideoExtractor
    if not VideoExtractor.OpenVideo(video_path):
        UI.MsgBox("Failed to open video: " + VideoExtractor.GetLastError(), 16, "Video Error")
        return

    # 3. Extract 10 frames at 1-second intervals (0s to 9s), send to Workspace, and store in Image Buffer
    extracted_count = 0

    for i in range(1, 11):
        # Check if script cancellation was requested by the user
        if UI.IsCancelled:
            break

        # Calculate timestamp in seconds: 0.0s, 1.0s, 2.0s, ..., 9.0s
        target_time_sec = float((i - 1) * 1.0)

        # Extract the frame as a Bitmap object
        frame_bmp = VideoExtractor.ExtractFrameAt(target_time_sec)

        if frame_bmp is None:
            UI.MsgBox(f"Failed to extract frame at {target_time_sec}s: {VideoExtractor.GetLastError()}", 48, "Extraction Error")
            break

        # Step A: Send the extracted frame to PhenoCapture Workspace (targetLocation = 0)
        Action.SetImage(frame_bmp, 0)

        # Step B: Send the current Workspace image to Image Buffer slot i (1 to 10)
        Action.PutToImageBuffer(i)

        # Release the temporary Bitmap in script and allow UI to refresh
        frame_bmp.Dispose()
        UI.YieldEvents()

        extracted_count += 1

    # 4. Close the video file and release Media Foundation resources
    VideoExtractor.CloseVideo()

    # 5. Show completion message
    UI.MsgBox(f"{extracted_count} frames have been extracted to the Workspace and stored in the Image Buffer.", 64, "Extraction Complete")
4. Hello Hello.py
▶
def main():
    UI.MsgBox("Hello Python!")
5. Invert Invert.py
▶
def main():
    source_image = Action.GetImage(0)
    if source_image is None:
        UI.MsgBox("No image is available.")
        return
    output_image = ImgProc.Invert(source_image)
    Action.SetImage(output_image, 0)
6. OCR Text Extraction OCR Text Extraction.py
▶
def main():
    ret = Action.OCRTextExtraction()
    UI.CopyToClipboard(ret)
    UI.MsgBox(ret, 0, "Results")
7. Random Lines Random Lines.py
▶
import random

# Import clr and add necessary .NET references
import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")

# Import required .NET classes
from System.Drawing import Bitmap, Graphics, Color, Pen
from System.Windows.Forms import Form, PictureBox, Button, MessageBox, MessageBoxButtons, MessageBoxIcon
from System.Windows.Forms import DockStyle, FormStartPosition, PictureBoxSizeMode, Clipboard

# 1. Create a 500x500 Bitmap and Graphics context
width, height = 500, 500
bmp = Bitmap(width, height)
g = Graphics.FromImage(bmp)

# 2. Clear the background to White
g.Clear(Color.White)

# 3. Draw 100 random colored lines
for i in range(100):
    # Generate random start and end coordinates
    x1 = random.randint(0, width - 1)
    y1 = random.randint(0, height - 1)
    x2 = random.randint(0, width - 1)
    y2 = random.randint(0, height - 1)

    # Generate random RGB colors
    r = random.randint(0, 255)
    g_val = random.randint(0, 255)
    b = random.randint(0, 255)
    random_color = Color.FromArgb(r, g_val, b)

    # Draw the line with width 1
    pen = Pen(random_color, 1)
    g.DrawLine(pen, x1, y1, x2, y2)
    pen.Dispose()

# Dispose Graphics object after drawing is complete
g.Dispose()

# =====================================================================
# 4. [NEW] Send the generated image directly to PhenoCapture's Workspace
# targetLocation = 0 represents the Workspace
# =====================================================================
Action.SetImage(bmp, 0)

# 5. Create WinForms Window (Form)
form = Form()
form.Text = "PhenoCapture Script Result"
form.Width = 550
form.Height = 600
form.StartPosition = FormStartPosition.CenterScreen

# 6. Create Copy Button and Event Handler
copy_btn = Button()
copy_btn.Text = "Copy to Clipboard"
copy_btn.Height = 40
copy_btn.Dock = DockStyle.Bottom

# Define the click event handler for the button
def on_copy_click(sender, event_args):
    try:
        # Copy the generated Bitmap to the Windows Clipboard
        Clipboard.SetImage(bmp)
        MessageBox.Show("The image has been successfully copied to the clipboard.", 
                        "Copy Success", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Information)
    except Exception as ex:
        MessageBox.Show("Failed to copy image: " + str(ex), 
                        "Error", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Error)

# Attach the event handler to the button
copy_btn.Click += on_copy_click

# 7. Create PictureBox to display the generated image
pb = PictureBox()
pb.Image = bmp
pb.Dock = DockStyle.Fill
pb.SizeMode = PictureBoxSizeMode.CenterImage

# Add controls to the Form (Button at bottom, PictureBox filling the rest)
form.Controls.Add(copy_btn)
form.Controls.Add(pb)

# 8. Display the Window (Modal)
form.ShowDialog()

# 9. Dispose resources after closing the window
form.Dispose()
bmp.Dispose()
8. TestDNNClassification TestDNNClassification.py
▶
def main():
     # Load the trained model
    ret = DNNClassifier.LoadModel("C elegans Model (Mobilenet).zip")
    
    # Retrieve the image from the workspace (0 indicates Workspace image)
    src_image = Action.GetImage(0)
    
    # Predict the class of the image
    predicted_class = DNNClassifier.Predict(src_image)
    
    # Display the result to the user
    UI.MsgBox("The classified result is: " + str(predicted_class))
9. TestObjectDetection TestObjectDetection.py
▶
def main():
    # 1. Initialize Object Detector
    ret = ObjectDetector.Initialize()
    if not ret:
        UI.MsgBox(f"Error loading model: {ObjectDetector.GetLastError()}")
        return
    
    # 2. Get Workspace image
    src_image = Action.GetImage(0)
    
    # 3. Detect objects (Returns the total count)
    total_objects = ObjectDetector.Detect(src_image, 0.5, 0.4, False)
    
    if total_objects > 0:
        # 4. Get the image with bounding boxes drawn (Image, ShowConfidence, Color)
        rendered_image = ObjectDetector.GetRenderedImage(src_image, True, "Lime")
        
        if rendered_image is not None:
            # 5. Put the rendered image back into the Workspace
            success = Action.SetImage(rendered_image, 0)
            
            # 6. Check for specific classes and build the message
            result_msg = f"Detection applied! Total objects drawn: {total_objects}\n\n"
            
            if ObjectDetector.HasClass("cat"):
                cat_count = ObjectDetector.GetClassCount("cat")
                result_msg += f"Success: Found {cat_count} cat(s) in the image."
            else:
                result_msg += "Result: No cats were found in the image."
            
            UI.MsgBox(result_msg)
        else:
            UI.MsgBox(f"Failed to render image: {ObjectDetector.GetLastError()}")
    else:
        UI.MsgBox("Detection complete! No objects were found.")