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?