Auto-histogram for high speed capture

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

Auto-histogram for high speed capture

#1

Post by Borodog »

Something I have wanted for a long time is an auto-histogram method for variable transparency under high speed capture, i.e. planetary or lunar. The proper way to do this is to adjust the exposure, not the gain. It can save a variable transparency recording. If you leave the exposure and only increase gain when the transparency drops, you are increasing the histogram, but you are not increasing the SNR, as you are not capturing any more photons. Instead, when transparency drops, you should increase the exposure to preserve the histogram and the SNR. This keeps you in the range where the Variable Transparency Recovery feature of Autostakkert is not fooled into marking the dimmest frames as the highest quality simply because they are the noisiest. As long as the range of variability in the histogram is not too great, VTR does a good job of compensating for it, as long as there is good SNR. But when the frames become too dim, or too noisy because you have only upped the gain and not the exposure, VTR starts marking the worst frames as the highest quality, and the resulting stacks become dominated by the worst frames instead of the best.

So I implemented an auto-histogram script that sets the histogram level of the first frame it sees as the target, and scales the exposure up or down if the histogram falls outside of a given range (* or / by 1.15), up to a maximum allowable exposure (1/30s by default). The minimum allowable exposure is assumed to be the existing exposure when the script is started, but you could change that.

The proper way to use this is in conjunction with VTR downstream in Autostakkert. You may get some frames that are either still too dark or over-exposed, because the algorithm has to detect a frame out of range before it can respond by changing the exposure. That's ok; the too dark frames, if they are marked high quality, should show up near the front of the Quality graph and you can manually reject them with the spacebar. The over-exposed ones should be marked low contrast and put toward the back of the graph.

I have tested the script on a variable transparency SER file and it works to scale the exposure up and down, keeping the histogram in the target range. I can't demonstrate the effect on the final stack of course, because the exposure in the test camera does not actually change the SNR of the frame in the SER file, which was fixed during capture.

Lastly, I really don't know what I am doing when writing these scripts. They seem kludged and inelegant to me. I suspect a lot of this is AI gobbledegook, since I'm using that to try to help me write them. If there are ways to clean the code up, I would appreciate hearing about them. This script also exits with an error when you stop it. I don't know how to avoid that.

Code: Select all

import clr
import time

# State variables
first_frame = True
range_factor = 1.15
intensity_low = 0.0
intensity_high = 1.0e10
max_exposure = 33.333
min_exposure = 0.0

def on_frame_captured(sender, args):
    """Event handler for FrameCaptured event"""
    global first_frame, range_factor, intensity_low, intensity_high, max_esposure, min_exposure
   
    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
        
        # Monitoring mode - check for intensity changes
        if first_frame:
            print ("First frame")
            intensity_target = current_mean
            intensity_high = intensity_target * range_factor
            intensity_low = intensity_target / range_factor
            min_exposure = SharpCap.SelectedCamera.Controls.Exposure.Value
            first_frame = False
            print (intensity_target,intensity_high,intensity_low,max_exposure,min_exposure,first_frame)
        
             # Check if threshold exceeded
        else:
            UpdateExposure = False
                        
            if current_mean < intensity_low:
                UpdateExposure = True
                Current_Exposure = SharpCap.SelectedCamera.Controls.Exposure.Value
                New_Exposure = min(Current_Exposure * range_factor, max_exposure)
                
            elif current_mean > intensity_high:
                UpdateExposure = True
                Current_Exposure = SharpCap.SelectedCamera.Controls.Exposure.Value
                New_Exposure = max(Current_Exposure / range_factor, min_exposure)
            
            if UpdateExposure:
                SharpCap.SelectedCamera.Controls.Exposure.Value = New_Exposure
                #print ("Attempting to adjust exposure . . . ")

    except Exception as e:
        print("Error in frame handler: {}".format(str(e)))
            
def start_monitoring():
    """Start monitoring frames"""
    global last_mean_intensity, range_factor
    
    # Check if a camera is selected
    if SharpCap.SelectedCamera is None:
        print("Error: No camera selected. Please open a camera first.")
        return
    
    print("Starting histogram monitoring...")
    
    # 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()

try:
    while True:
        time.sleep(0.5)  # Sleep to keep script alive but responsive
finally:
    # Always clean up, even if thread is aborted
    try:
        stop_monitoring()
    except:
        pass  # Ignore any errors during cleanup
Post Reply