Triggered Capture - please move to Scripting forum

Discussions on extending SharpCap using the built in Python scripting functionality
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Triggered Capture - please move to Scripting forum

#1

Post by Borodog »

Robin put me onto python scripting in SharpCap to try to build a triggered capture script, but I am immediately having problems:

>>> SharpCap.SelectedCamera.RunCapture()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: No writer object when trying to initialize it

I don't know what this error means. What am I doing wrong? I have Test Camera 2 open and it is previewing frames.

Edit: Nevermind. I see that I have to preface RunCapture() with PrepareToCapture().

I think I will leave this thread here as I develop this script, as I think others might find it useful.

The purpose is to have SharpCap watch the Moon (or Sun) and automatically capture aircraft transits.

Re-edit: Apparently there is a scripting subforum and I have posted in the wrong place. Robin, you may want to move this thread. My apologies.
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#2

Post by Borodog »

I am having quite a bit of trouble trying to figure out SharpCap's python scripting. I'm trying to use Grok to help me out but the documentation and examples available online for it to pull from are fairly sparse. I'm hoping someone here can help me with the correct syntax.

I would like to write a couple of scripts (to start with). The first is the triggered capture script. By "triggered capture" I mean the script should be watching the preview frames and calculating the average value of each frame, and if this changes beyond a certain threshold from one frame to the next (say 1%), then a capture of N frames should be run (say 30 frames), after which it returns to monitoring. The goal is to automatically capture aircraft transits without having to capture hundreds of gigabytes of data that then have to be combed though.

Robin mentioned this in an email regarding this goal:

"If you are interested in the python scripting in SharpCap then you would hook into the FrameCaptured event on the camera, then there is an easy way to get the mean brightness (frame.GetStats().mean) - then start capture based on the value changing."

Because there is a scripting forum (which hopefully this thread will get moved to), I am loathe to pester him personally on this topic.

In any event, it seems like "FrameCaptured" would be referring to captured frames, not previewed frames, no? In any event I can't figure out how to "hook into the FrameCaptured event" regardless, or what the correct syntax/usage of frame.GetStats().mean is. Everything I try that Grok suggests returns errors.

If someone could point me in the right direction here I would greatly appreciate it.
User avatar
admin
Site Admin
Posts: 17609
Joined: Sat Feb 11, 2017 3:52 pm
Location: Vale of the White Horse, UK
Contact:

Re: Triggered Capture - please move to Scripting forum

#3

Post by admin »

Hi Mike,

first some general pointers ...

* You are in 'IronPython' and have access to all of the standard python library, and all of the .NET Framework, and SharpCap's object model. You cannot access additional python libraries if they contain C code (pure python is fine).

* You will get some intellisense as you type in the script console - for instance type 'SharpCap.SelectedCamera.' on a new line and it will suggest all the methods/properties/events available on the camera.

* You can also use the python 'help' function to get more info about SharpCap objects, properties, methods, etc - ie 'help(SharpCap.SelectedCamera)'


To trigger a simple capture of some frames, first set up the 'CaptureConfig' on the camera to specify for instance how many frames to capture, then call 'PrepareToCapture', then 'RunCapture'. If you specified an unlimited capture then you would need to call StopCapture at some point too. For instance an example here - viewtopic.php?t=2025

On the naming of the 'FrameCaptured' event - that is named thinking about the camera, so a captured frame is any frame that the camera sends to the application - the decision of whether to save it or not is made elsewhere in SharpCap and isn't relevant to the naming of the event. Have a look at this thread for someone posting some samples of using this event - viewtopic.php?p=5686 - you don't need to actually access the binary data of the frame, once you have the frame object (after frame = eventargs.Frame), you can call .GetStats() on it.

cheers,

Robin
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#4

Post by Borodog »

Robin,

Thank you for the help, but I'm afraid you will have to be more explicit. I don't actually know much python. I'm trying to use Grok to help, but again, the material available online about IronPython in SharpCap seems too sparse to be of much use.

I tried this:

Code: Select all

SharpCap scripting ready...
>>> SharpCap.SelectedCamera.FrameCaptured
<IronPython.Runtime.Types.ReflectedEvent+BoundEvent object at 0x000000000000002B [IronPython.Runtime.Types.ReflectedEvent+BoundEvent]>
>>> frame = SharpCap.SelectedCamera.FrameCaptured
>>> frame = eventargs.Frame
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'eventargs' is not defined
>>> frame.GetStats()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>>
I don't understand the syntax I'm supposed to be using here. Can you provide the exact syntax to, for example, print out the mean value of the last previewed frame? I think that would get me going.
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#5

Post by Borodog »

Well, I have something that kind of works, sort of, sometimes. It throws a bunch of errors I can't figure out, but it captures the transit in the SER file, mostly.

It seems like you have to use the SharpCap.SelectedCamera.PrepareToCapture(), but only once, because subsequent calls to it cause an error:

Code: Select all

Error in frame handler: Already capturing or already prepared for capture: Capturing:False, _writer:SharpCap.Base.FileWriters.SerFileWriter
It seems like I have to edit the script between running it the first time and and subsequent times to comment out that line or it throws that error and does not capture.

And if you call SharpCap.SelectedCamera.RunCapture() it complains thusly:

Code: Select all

Error in frame handler: Trying to run a sync call to the UI thread from a performance critical thread
But it performs the capture (as long as it hasn't complained that it is already prepared). But if you try to call SharpCap.SelectedCamera.RunCaptureAsync() instead it complains because now it wants an argument:

Code: Select all

Error in frame handler: RunCaptureAsync() takes exactly 1 argument (0 given)
help(SharpCap.SelectedCamera.RunCaptureAsync) yields this:

Code: Select all

>>> help(SharpCap.SelectedCamera.RunCaptureAsync)
Help on built-in function RunCaptureAsync:

RunCaptureAsync(...) method of SharpCap.Models.Camera instance
    RunCaptureAsync(self: ICamera, cancellationToken: CancellationToken) -> Task
    
    Runs the capture operation asynchronously.
    
    cancellationToken: A cancellation token.
    Returns: A task representing the operation.
But I don't know what a "cancellation token" is. Google yielded gobbledegook that was over my head.

Finally, the original version of the script could not be stopped short of closing SharpCap. AI came up with this fix:

Code: Select all

def stop_monitoring():
    """Stop monitoring frames"""
    if SharpCap.SelectedCamera is not None:
        # Unsubscribe from the event
        SharpCap.SelectedCamera.FrameCaptured -= on_frame_captured
        print("Monitoring stopped.")
    else:
        print("No camera to stop monitoring.")

# Keep script running so it can be stopped with the Stop button
try:
    print("Script running. Press 'Stop' or use 'Abort Running Script' to end.")
    while True:
        time.sleep(0.5)  # Sleep to keep script alive but responsive
except:
    # This catches the stop/abort action
    print("Script stopping...")
    stop_monitoring()
    print("Script stopped successfully.")
Which does allow me to stop the script, but it throws this error:

Code: Select all

Script stopping...
Monitoring stopped.
Script stopped successfully.
Traceback (most recent call last):
  File "<string>", line 116, in <module>
SystemError: Thread abort is not supported on this platform.

Here's the whole sordid mess of a script.

Code: Select all

import clr
import time

#---------
clr.AddReference("SharpCap")
from SharpCap.UI import CaptureLimitType

#---------

# Configuration parameters
INTENSITY_THRESHOLD = 0.01  # 1% change threshold
CAPTURE_FRAMES = 10  # Number of frames to capture when triggered
#CHECK_INTERVAL = 0.1  # Time between checks in seconds

# State variables
last_mean_intensity = None
is_capturing = False
capture_count = 0


def on_frame_captured(sender, args):
    """Event handler for FrameCaptured event"""
    global last_mean_intensity, is_capturing, capture_count
    
    try:
        # Get the frame data
        frame = args.Frame
        
        # Get frame statistics (returns tuple of mean, stddev)
        stats = frame.GetStats()
        current_mean = stats[0]  # First element is the mean
        
        # If we're in capture mode, just count frames
        if is_capturing:
            capture_count += 1
            #print("Capturing frame {}/{}".format(capture_count, CAPTURE_FRAMES))
            
            # Check if we've captured enough frames
            if capture_count >= CAPTURE_FRAMES:
                print("Capture complete. Returning to monitoring mode.")
                is_capturing = False
                capture_count = 0
                # Reset baseline to current intensity
                last_mean_intensity = current_mean
            return
        
        # Monitoring mode - check for intensity changes
        if last_mean_intensity is not None:
            # Calculate relative change
            intensity_change = abs(current_mean - last_mean_intensity) / last_mean_intensity
            
            # Check if threshold exceeded
            if intensity_change > INTENSITY_THRESHOLD:
                print("Intensity change detected: {:.2%}".format(intensity_change))
                print("Triggering capture of {} frames...".format(CAPTURE_FRAMES))
                
                # Start capture sequence
                is_capturing = True
                capture_count = 0
                
                # Initiate the capture
                SharpCap.SelectedCamera.CaptureConfig.CaptureLimitType = CaptureLimitType.FrameLimited
                SharpCap.SelectedCamera.CaptureConfig.CaptureLimitCount = 10
                SharpCap.TargetName = "Transit"
                #SharpCap.SelectedCamera.PrepareToCapture()
                SharpCap.SelectedCamera.RunCapture()
        
        # Update the baseline intensity
        if not is_capturing:
            last_mean_intensity = current_mean
            
    except Exception as e:
        print("Error in frame handler: {}".format(str(e)))

def start_monitoring():
    """Start monitoring frames"""
    global last_mean_intensity
    
    # Check if a camera is selected
    if SharpCap.SelectedCamera is None:
        print("Error: No camera selected. Please open a camera first.")
        return
    
    print("Starting frame monitoring...")
    print("Threshold: {:.1%}".format(INTENSITY_THRESHOLD))
    print("Capture frames: {}".format(CAPTURE_FRAMES))
    
    # Subscribe to the FrameCaptured event
    SharpCap.SelectedCamera.FrameCaptured += on_frame_captured
    
    print("Monitoring active. Press 'Stop' to end monitoring.")

def stop_monitoring():
    """Stop monitoring frames"""
    if SharpCap.SelectedCamera is not None:
        # Unsubscribe from the event
        SharpCap.SelectedCamera.FrameCaptured -= on_frame_captured
        print("Monitoring stopped.")
    else:
        print("No camera to stop monitoring.")

# Start the monitoring
start_monitoring()

# Keep script running so it can be stopped with the Stop button
try:
    print("Script running. Press 'Stop' or use 'Abort Running Script' to end.")
    while True:
        time.sleep(0.5)  # Sleep to keep script alive but responsive
except:
    # This catches the stop/abort action
    print("Script stopping...")
    stop_monitoring()
    print("Script stopped successfully.")
    
I suppose this is progress, but perhaps python is not for me. Is there such a thing as IronFortran?
User avatar
admin
Site Admin
Posts: 17609
Joined: Sat Feb 11, 2017 3:52 pm
Location: Vale of the White Horse, UK
Contact:

Re: Triggered Capture - please move to Scripting forum

#6

Post by admin »

Hi Mike,

I think you are mostly fighting with the internal behaviour of SharpCap, which is complex, not Python :) Sadly no fortran version (and I don't suppose Ruby or Lisp are much easier than python from a fortran perspective...).

Two things jump out at me...

1) You can't prepare to capture twice in a row without either running the capture or cancelling it, so valid sequences are...

Prepare
Run
... <capture finishes>
Prepare
Run

or

Prepare
Cancel
Prepare
Run

etc.

2) The performance critical thread thing is basically trying to tell you not to call certain parts of the API from the FrameCaptured event. Well, in fact it's really there to stop me from accidentally introducing code that does that, but it works for Python development too. Essentially it's flagging that the API called could end up waiting for access to other resources, and that's not a thing that we should do inside the time critical parts of the code like those processing frames from the camera.

It's probably the RunCapture call, but it may be others too - commenting bits out will confirm which calls trigger that error and which do not.

The workaround is to make sure that the calls that cause the error are issued from a different thread to the one that is processing the frame statistics in the FrameCapturedEvent. You could have the frame handler set a flag and the main loop check it and then start the capture, or you could start a new thread to run the start capture code in a function - something like this...

Code: Select all

 
>>> def StartCapture():
... 	print("hello")
...  
>>> from System.Threading import Thread, ThreadStart
>>> th = Thread(ThreadStart(StartCapture))
>>> th.Start()
hello


I think the thread approach will work better - low latency in response to the request without the need for the main loop to have a very short sleep...

cheers,

Robin
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#7

Post by Borodog »

Thanks Robin.

It seemed like the PrepareToCapture() call was throwing the error even after the previous RunCapture() had completed successfully, but perhaps I am confused.

I will try your thread workaround.
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#8

Post by Borodog »

Any idea how to fix this:

Code: Select all

def stop_monitoring():
    """Stop monitoring frames"""
    if SharpCap.SelectedCamera is not None:
        # Unsubscribe from the event
        SharpCap.SelectedCamera.FrameCaptured -= on_frame_captured
        print("Monitoring stopped.")
    else:
        print("No camera to stop monitoring.")

# Keep script running so it can be stopped with the Stop button
try:
    print("Script running. Press 'Stop' or use 'Abort Running Script' to end.")
    while True:
        time.sleep(0.5)  # Sleep to keep script alive but responsive
except:
    # This catches the stop/abort action
    print("Script stopping...")
    stop_monitoring()
    print("Script stopped successfully.")
So that I can stop the script without it throwing this error?

Code: Select all

Script stopping...
Monitoring stopped.
Script stopped successfully.
Traceback (most recent call last):
  File "<string>", line 116, in <module>
SystemError: Thread abort is not supported on this platform.
It's bothering my OCD.
Borodog
Posts: 487
Joined: Fri Jan 01, 2021 7:25 pm

Re: Triggered Capture - please move to Scripting forum

#9

Post by Borodog »

Thanks Robin; that worked. I think I have a working script, with the exception that it misses the first frame of the transit. That is probably unavoidable short of retroactive capture using a frame buffer, unless it is somehow trivial to have RunCapture() include the last frame and not begin on the next frame.

Now all I need is to fix the error I get when you stop the script:

Code: Select all

Script stopping...
Monitoring stopped.
Script stopped successfully.
Traceback (most recent call last):
  File "<string>", line 125, in <module>
SystemError: Thread abort is not supported on this platform.
User avatar
admin
Site Admin
Posts: 17609
Joined: Sat Feb 11, 2017 3:52 pm
Location: Vale of the White Horse, UK
Contact:

Re: Triggered Capture - please move to Scripting forum

#10

Post by admin »

Hi Mike,

PrepareToCapture will also give you an error if the camera is still capturing (or finishing a previous capture). You can check the Capturing property on the camera which I think includes the finishing stage too.

The other thing to do with ThreadAbort looks like it is an unexpected interaction between cancellation using the 'Stop' button and the try/except - I will have to look for a better way to cancel as the current implementation is a bit quick and dirty.

cheers,

Robin
Post Reply