Frame timestamp from Python

Discussions on extending SharpCap using the built in Python scripting functionality
Post Reply
mcamilleri
Posts: 50
Joined: Thu Mar 02, 2023 12:02 am

Frame timestamp from Python

#1

Post by mcamilleri »

How can I read the current frame timestamp from Python?

I am creating a tool to measure camera line delays using GPS LED and need the timestamp of the frame. I can get the time from Python or the System but that will be after the frame has been received so won't be as accurate as the actual frame timestamp.

Thanks
Michael
User avatar
admin
Site Admin
Posts: 17595
Joined: Sat Feb 11, 2017 3:52 pm
Location: Vale of the White Horse, UK
Contact:

Re: Frame timestamp from Python

#2

Post by admin »

Hi Michael,

presumably you are getting the frames from one of the events like the FrameCapturedEvent. Once you have the frame object itself, get the FrameInfo (frame.Info), then you can get various properties of the frame info, including

* EndTimeStamp (which will always be available - it defaults to the time that SharpCap received the frame)
* FrameStartTime (which will almost always be available - it is the end time minus the exposure)
* GPS related timestamps if you are using a GPS camera

If you do

Code: Select all

from SharpCap.Base import FrameInfo
help(FrameInfo)
you will get some help about all the properties on the FrameInfo type.

cheers,

Robin
mcamilleri
Posts: 50
Joined: Thu Mar 02, 2023 12:02 am

Re: Frame timestamp from Python

#3

Post by mcamilleri »

Thanks. I have got it working now with live capture.

I'm also doing a version that analyses from ADV video files. A bit of a hassled having to use the ADV .NET dll rather than the Python code as the library is not IronPython compatible.
Jean-Francois
Posts: 858
Joined: Sun Oct 13, 2019 10:52 am
Location: Germany

Re: Frame timestamp from Python

#4

Post by Jean-Francois »

Hello Michael and Robin,

I have the following script for some monitoring of a light source with a camera sensor (but can be used for other purpose).

Code: Select all

# *******************************************************************************************
# 
# SharpCap script "FrameTimestamp.py"
# 2026/02/14 Jean-Francois
#
# Version: 1.0.0:   First version
#
# The script works only with a SharpCap PRO version.
#
# *******************************************************************************************

import os
import time
import datetime
import math
import statistics
import clr
clr.AddReference("Oxyplot")
clr.AddReference("OxyPlot.WindowsForms ")
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")

import OxyPlot
import System.Drawing
#import System.Drawing.Drawing2D
import System.Windows.Forms

from datetime import datetime, timedelta, date
from System import Array
from System.Drawing import *
from System.Windows.Forms import *
from System.Threading import Thread, ThreadStart, ApartmentState, ParameterizedThreadStart

from SharpCap.Base import FrameInfo


Time_meas = []
Mean_meas = []
dumpdata  = False
t0 = datetime.now()

SharpCap.Transforms.SelectTransform("ROI Selection")


def framehandler(sender, args):
    global dumpdata, Time_meas, Mean_meas, t0
    if (dumpdata):
        cutout = args.Frame.CutROI(SharpCap.Transforms.SelectionRect)
#        print(FrameInfo.EndTimeStamp.GetValue(Frame))
        Stat = cutout.GetStats()
        Time_meas.append((datetime.now() - t0).total_seconds())
        Mean_meas.append(Stat.Item1)
        cutout.Release()


# *****************************************************************************
def Timestamp_measurement(self):
    global dumpdata, Time_meas, Mean_meas, t0

    self.Timestamp.Text = "Monitoring running"
    self.Timestamp.BackColor = Color.Red
    self.Timestamp.Enabled = False


    SharpCap.SelectedCamera.FrameCaptured += framehandler
    dumpdata = True

    expos_ms = SharpCap.SelectedCamera.Controls.Exposure.ExposureMs

    wait_time = 0.5       # wainting time between two refresh of OxyPlot
    print("Waiting Time: %5.3f" % (wait_time))

    print()
    print("Frame Timestamp :")
    print("*****************")
    Time_meas = []
    Mean_meas = []

    if (int(self.textBoxTime.Text) > 0.0):
        Max_time = int(self.textBoxTime.Text)

        t0 = datetime.now()
        dt = 0

        while  (dt < Max_time):
            dt = (datetime.now() - t0).total_seconds()
            time.sleep(wait_time)
#            print("Frame:", len(Time_meas))
            if (len(Time_meas) > 2): self.ShowOxyGraphic()

        print("Time:", Time_meas)
        print("Mean:", Mean_meas)
        print()
    else:
        print("Measurement time need to be larger than 0 s")

    dumpdata = False
    SharpCap.SelectedCamera.FrameCaptured -= framehandler
    print()
    print("Measurement done")

    self.Timestamp.Text = "Start Measurement"
    self.Timestamp.BackColor = Color.Gainsboro
    self.Timestamp.Enabled = True

    file_path = "D:\\Scripts\\FrameTimestamp\\"
    file_name = file_path + "Timestamp_" + str(t0).split()[1].split(".")[0].replace(":","-")
    file_name = file_name + "_" + self.textBoxFileInfo.Text + ".txt"
    file = open(file_name, "w")
    for index in range(len(Time_meas)):
        file.write(str("%.4f" % Time_meas[index]) + " " + str("%.4f" % Mean_meas[index]) + "\n")
    file.close()

    return()

# *****************************************************************************

class TimestampMenuForm(Form):
    def __init__(self):
        self.SuspendLayout()
        self.InitializeComponent()
        self.setupCheckButtons()
        self.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi
        self.AutoScaleDimensions = SizeF(96, 96)
        self.ResumeLayout()

    def InitializeComponent(self):
        self.Text = "Frame Timestamp"
        self.ClientSize = System.Drawing.Size(700, 400)
        self.TopMost = True

        self.labelTime = Label()
        self.textBoxTime = TextBox()
        self.textBoxFileInfo = TextBox()

        self.plot1 = OxyPlot.WindowsForms.PlotView()
        self.plot1.Location = System.Drawing.Point(10, 50)
        self.plot1.Size = System.Drawing.Size(680, 340)
        self.plot1.AutoSize = True

        self.Controls.Add(self.labelTime)
        self.Controls.Add(self.textBoxTime)
        self.Controls.Add(self.textBoxFileInfo)
        self.Controls.Add(self.plot1)

        self.labelTime.AutoSize = True
        self.labelTime.Location = Point(150, 13)
        self.labelTime.Name = "labelTime"
        self.labelTime.Text = "Measurement time [s]:"

        self.textBoxTime.AutoSize = True
        self.textBoxTime.Location = Point(280, 14)
        self.textBoxTime.Name = "textBoxTime"
        self.textBoxTime.Size = Size(30, 20)
        self.textBoxTime.Text = "1"

        self.textBoxFileInfo.AutoSize = True
        self.textBoxFileInfo.Location = Point(330, 13)
        self.textBoxFileInfo.Name = "textBoxTime"
        self.textBoxFileInfo.Size = Size(280, 20)
        self.textBoxFileInfo.Text = ""

    def setupCheckButtons(self):
        self.Timestamp = Button()
        self.Timestamp.Text = "Start Measurement"
        self.Timestamp.Location = Point(20, 10)
        self.Timestamp.Click += self.FrameTimestamp
        self.Timestamp.AutoSize = True

        self.button_Exit = Button()
        self.button_Exit.Text = "Exit"
        self.button_Exit.Location = Point(620, 10)
        self.button_Exit.Click += self.exit
        self.button_Exit.AutoSize = True

        self.AcceptButton = self.Timestamp
        self.CancelButton = self.button_Exit
        self.Controls.Add(self.Timestamp)
        self.Controls.Add(self.button_Exit)

    def ShowOxyGraphic(self):
        self.plotmodel1 = OxyPlot.PlotModel()

        self.YAxis1 = OxyPlot.Axes.LinearAxis(Position = OxyPlot.Axes.AxisPosition.Left, Minimum = 0.9999*min(Mean_meas), Maximum = 1.0001*max(Mean_meas))

        self.points_start = []
        for i in range(0,len(Time_meas)):
            self.points_start.Add(OxyPlot.DataPoint(Time_meas[i],Mean_meas[i]))


        self.serie_1 = OxyPlot.Series.LineSeries()
        self.serie_1.Color  = OxyPlot.OxyColors.Blue
        self.serie_1.MarkerSize = 2
        self.serie_1.MarkerType = OxyPlot.MarkerType.Circle
        self.serie_1.StrokeThickness = 1
        self.serie_1.ItemsSource = self.points_start

        self.plot1.Model = self.plotmodel1

        self.plotmodel1.Axes.Add(self.YAxis1)
        self.plotmodel1.Series.Add(self.serie_1)


    def FrameTimestamp(self, sender, event):
        th = Thread(ParameterizedThreadStart(Timestamp_measurement))
        th.SetApartmentState(ApartmentState.STA)
        th.Start(self)

    def exit(self, sender, event):
        print("Stop Monitoring script")
        SharpCap.Transforms.SelectTransform(None)
        self.Close()


form = TimestampMenuForm()
form.StartPosition = FormStartPosition.CenterScreen
form.TopMost = True
form.Show()
If you want to test the script ... you need first to change the file path on the line 107.
If not, then it will simply crash.

I tried the FrameInfo with different way in the framehandler function ... but it is not working.
How to get the time info of the frame ?

Regards,
Jean-Francois
Post Reply