Scripting

SharpCap has a scripting language built in that allows simple programs to be written that can perform just about any action that can be performed when controlling SharpCap with the keyboard and mouse.  The scripting language is based on a language called IronPython which is a Microsoft port of the Python Programming Language to the .NET framework.

The Scripting Console

The Scripting console can be shown by selecting Show Console from the scripting menu.  The scripting console is an Integrated Development Environment (IDE).  This allows for the creation, execution and debugging of code using the IronPython programming language and its integration into SharpCap.

image

Typing help() and <ENTER>  into the IronPython Console window gives the following basic help output:

image

Some examples are displayed.  One of these is code to list the cameras available to SharpCap.

#List the cameras available
print SharpCap.Cameras

 

Lines beginning with # are comment lines, meaning they are ignored by the computer.

Code can be typed directly into the console or pasted into the IronPython Pad in the lower part of the console window. If code is typed into the upper part of the window, it will be run when the <Enter> key is pressed.  Longer sections of code should be typed into the lower editor area where they are not run until the ‘Run’ button is pressed.

Controlling SharpCap is handled using the SharpCap object which is automatically loaded into each script session. Some simple commands would be...

SharpCap.SelectedCamera = None # Close the camera that is currently active

SharpCap.SelectedCamera = SharpCap.Cameras[0] # Open the first camera in the Cameras menu and start previewing it

 

Once a camera is running, adjust its properties like this

SharpCap.SelectedCamera.Controls.Exposure.Value = 1000 # Set the exposure to 1000ms (1s)

 

 In the IronPython Pad, type in the code print SharpCap.Cameras and press the Run button.

image

The following output appears in the IronPython Console.

image

Click the floppy disk icon and save the file as cameras.py for use in the Run Script menu item below.

Exploring the API

The editor automatically shows the possible methods and properties for an object upon typing the '.' – this helps explore the available API.

In the IronPython Console, type the following two lines (the case of the text matters and the ‘.’ matters):

import System

from System.

 

As soon as the ‘.’ is typed, a list appears allowing selection.  This trick can be applied to many parts of the SharpCap API to allow discovery of the methods available and what parameters they require.

image

Run a Script

The Run Script menu item opens a File Explorer window to allow selection of a previously created Python script.

Scripts (programs) can also be created from within Windows using any text editor.  The scripts must be saved with a .py extension.

From the Menu select Scripting > Run Script.

image

Browse to the file something.py and click the Open button.  The script should execute.

Example

1.       From the Menu select Scripting > Show Console.

2.       Drag the Iron Python Console to one side using the mouse.

3.       From the Menu select Scripting > Run Script.

4.       Navigate to the file cameras.py, created in the previous section, and select it.

5.       The script executes and the result (the available cameras) is shown in the IronPython Console.

image  

The above example has no practical use but serves to demonstrate how to use SharpCap functionality.

Scripting Tutorial

Create a Script

This section shows how to:

·         Create a simple script using the IronPython Console.

·         Save the script.

·         Run the script from within the console.

·         Run the saved script directly from the Run Script menu option.

 

Upon selecting Show Console, an Integrated Development Environment (IDE) is displayed.  This allows for the creation, execution and debugging of code using the IronPython programming language.

image

The code below will capture a single PNG image and save it to a file.  The destination d:\capture.png will need to be changed to somewhere convenient on the computer being used.

SharpCap.SelectedCamera.CaptureSingleFrameTo("d:\capture.png")

 

Complete the following steps to test the scripting functionality:

1.       Start SharpCap and from the Menu select Cameras > Test Camera 1 (Deep Sky)

image

The M42 image should be shown in the Capture Display Area.

image

2.       In the Camera Control Panel, change the Output Format to be PNG files…

image

3.       From the Menu select Scripting > Show Console.

image

The IronPython Console will open.

4.       Copy the following code:

SharpCap.SelectedCamera.CaptureSingleFrameTo("d:\capture.png")

and paste it with Ctrl+V  (or type directly) into the IronPython Pad (bottom part of the IronPython Console).  Edit the destination (underlined in red) to be something appropriate on the PC in use.

image

5.       Press the Run icon (or F5).

image

6.       Check the destination which, all being well, should now contain 2 new files called capture.png and capture.png.CameraSettings.txt.

image

7.       Edit the code to change the capture file name to be capture2.png.

image

8.       Click on the floppy disk icon and a file explorer window opens. 

image

Save the file as capture2.py (the .py extension is important).

[Note: there is a bug in SharpCap prior to version 2.9.3055 which causes the file to be saved as capture2.py.txt. The file must be renamed to capture2.py (the .txt will not be seen unless File name extensions is checked in File Explorer).]

9.       Close the IronPython Console.

[Note: Of course, the point of scripting is to automate the use of SharpCap, and all of the above steps could be automated by a more complex script – for example:

SharpCap.SelectedCamera = SharpCap.Cameras.Find( lambda x:x.DeviceName == "Test Camera 1 (Deep Sky)")

SharpCap.SelectedCamera.Controls.OutputFormat.Value = "PNG Files (*.png)"

SharpCap.SelectedCamera.CaptureSingleFrameTo("d:\capture.png")

 

 

 

SharpCap Scripting Object Model Reference

The major objects available to control the application are:

SharpCap  

The main application object, all other objects are accessed via this object.

SharpCap.Cameras

A collection of available cameras (as shown in the Cameras menu) 

SharpCap.SelectedCamera    

The camera that is currently open (or 'None' if no camera open)

SharpCap.SelectedCamera.Controls

The controls available on the currently open camera. Many common controls can be access directly, but others will need a check of each item in the array to find the control needed.  

SharpCap.Focusers   

A collection of (ASCOM) focusers detected by SharpCap. SharpCap.Focusers.SelectedFocuser can be used to connect to a specific focuser and then access it via the SelectedCamera.Controls collection.

SharpCap.Mounts, SharpCap.Wheels

Collections of ASCOM mounts and filter wheels, work in the same way as Focusers.

SharpCap.Transforms

A collection of frame transforms that can be applied to the preview window by setting the SharpCap.Transforms.SelectedTransform property (buggy at the moment)

 SharpCap.MainWindow   

The main application window of SharpCap. Take care changing properties or calling methods on this as it may break things.  

 SharpCap.Reticules 

Collection of reticule overlays that may be selected for drawing on the screen (like the transforms, also currently buggy)

 SharpCap.Settings   

All application settings, alter with care and call 'Save()' after any changes to make them take effect

 

In general, the most used objects will be SharpCap.SelectCamera and SharpCap.SelectCamera.Controls.

The Camera Object

The most important methods and properties on the SelectedCamera object are (informational properties will work on other non-selected cameras):

 CanCapture, CanStillCapture

Indicate whether the camera can capture video and still frames, respectively

 CanPause

Can the camera pause a video capture without stopping it?

 CaptureConfig

Settings controlling the type of capture to be performed, including frame limit, etc

 PrepareToCapture()

Must be called to set up a video capture before calling RunCapture()

 RunCapture()

Begins a prepared video capture. The capture will run until any limit is reached or StopCapture() is called. The output file(s) will be named according to the selected naming scheme.

 CancelCapture()   

Cancel a capture that has been prepared (instead of running it using RunCapture).

 CaptureSingleFrame()

Capture a single frame snapshot (the output file will be named according to the selected naming scheme

 CaptureSingleFrameTo(string filePath)

Capture a single frame and save it to the specified output file name. The path will need to be a full path and the extension specified should match that selected in SharpCap.SelectedCameras.Controls.OutputFormat.Value

 Name

The name of the camera used in the application UI

 VideoDeviceId

In internal identifier for the camera (may be empty or rather geeky)

 StartPreview(), StopPreview()

Start and Stop previewing frames on the camera respectively

 RestartPreview()

Stop then re-start previewing frames on the camera

 GetStatus(boolean allStats)

Returns an object describing the status of the camera including frames captured, average frame rate, etc.

 IsOpen, IsPreviewing, CanCountFrames, Capturing

Informational properties, as named

 CapturedFrameCount

The number of frames processed by the camera (including preview frames) since the last time preview was started or capture was started or stopped.

 ApplySelectedTransform()

Reserved, internal use only

 

The following controls may be available directly on the Controls object for the SelectedCamera:

Binning, ColourSpace, Exposure, FilterWheel, Focus, Gain, OutputFormat, Resolution

 

Other controls are likely to be available within the Controls collection and must be searched for by name, for example:

cooler = SharpCap.SelectedCamera.Controls.Find(lambda x: x.Name == "Cooler")

 

Note that the available controls vary from camera to camera, and only ColourSpace, Exposure, Resolution and OutputFormat are always available.

The Control Object

The following properties are available on each Control:

 

 Available

True if the control is actually available to read or write values.

 ReadOnly

True if the control can only be read from (for instance a sensor temperature readout)

 AutoAvailable    

True if the control can be set into Auto mode

 Auto

Switch the control between Auto and Manual mode

 Name

The name of the control as displayed in the UI

 Id

An enumeration of common property types, currently including:   Other, Exposure, FrameRate, Pan, Tilt, Resolution, ColourSpace, OutputFormat, Focus, FilterWheel, FrameFilter, Binning, Gain

 Minimum, Maximum

Retrieve the minimum and maximum values of numeric controls

 Step

Integer controls may have a step value defined - they can only be changed in multiples of this value. This is very rarely encountered.

 Value

The value of the control, which can be retrieved and (if not ReadOnly) changed.

 Type

The type of value that the control has.

Integer

 Numeric, whole number values

Double

 Numeric, whole or decimal values

Boolean

 On/Off value (checkbox)

Command

 A single action, launched by a button in the UI

MultipleChoice

 A list of options, shown as a drop down control in the UI

Custom

 Any other type of control.

 AvailableValues

 In the case of a MultipleChoice control, a list of the choices available.

 

Scripting Samples

Examples of scripting tasks are shown below.

Periodic Capture and Timestamp Image

The code below will capture a single PNG image approximately every 15 seconds and write a timestamp into the image itself before saving it. It would be simple to modify the code to save each timestamped image under a different filename or to remove the timestamping step.

The code relies on a camera already being selected and previewing and that the camera can output to PNG files (i.e. will not work if the camera is in a 12/16-bit mode).

import time

clr.AddReference("System.Drawing")

import System.Drawing

 

SharpCap.SelectedCamera.Controls.OutputFormat.Value = 'PNG files (*.png)'

if (SharpCap.SelectedCamera.Controls.Exposure.AutoAvailable):

   SharpCap.SelectedCamera.Controls.Exposure.Automatic = True

 

while True:

   SharpCap.SelectedCamera.CaptureSingleFrameTo("d:\capture.png")

   time.sleep(1)

   bm = System.Drawing.Bitmap("d:\capture.png")

   g = System.Drawing.Graphics.FromImage(bm)

   f = System.Drawing.Font("Arial", 12)

   g.DrawString(System.DateTime.Now.ToString(), f, System.Drawing.Brushes.Red, System.Drawing.Point(0,0))

   g.Dispose()

   f.Dispose()

   bm.Save("d:\\timestamped.png")

   bm.Dispose()

# do more with png file here

   time.sleep(15)

 

Controlling the Selection Rectangle

Before starting this example, select either a suitable Focus Score method or the Image Histogram to enable the Selection Area generated by the program to be shown.  The Selection Area needs to be turned off via its Tool Bar icon

From Scripting > Show Console, type the following code into the IronPython Console.  Do not copy and paste as this negates the purpose of the exercise. At certain places, when ‘.’ is typed a dropdown will appear showing possible methods and properties.  Select the appropriate text.

import clr
clr.AddReference("System.Drawing")
from System.Drawing import Rectangle
SharpCap.Transforms.AreaSelection = True # turn on selection area
SharpCap.Transforms.SelectionRect = Rectangle(100,200,300,400) # adjust selection rectangle, parameters are (x, y, width, height)

 

The typed in code should look like this.  When run, nothing will appear to happen except an additional >>> will appear in the console.  No errors messages is a good sign. 

image

This enables use of the .NET type System.Drawing.Rectangle which is required to specify the selection area - the first 3 lines, which allow access to the .NET type, are the important ones here as they can be used for other .NET types too.

Example Task to Script

Consider the following non-trivial task.

·         Control a USB filter wheel containing LRGB filters

·         Capture 10x5 minute exposures using L filter

·         Switch to R filter

·         Capture 10x5 minute exposures using R filter

·         Switch to G filter

·         Capture 10x5 minute exposures using G filter

·         Switch to B filter

·         Capture 10x5 minute exposures using B filter

Total capture time = 3h 20m but no intervention is needed if the capture is managed by a script.