CircAqNumpyArray.py

#############################################################
 # 
 # FILE:        CircAqNumPyArr.py
 # DATE:        04/28/2022
 # AUTHOR:      Arjun Krishna
 # COMPANY:     BitFlow, Inc.
 # DESCRIPTION: Example illustrating the capture of image data
 #              into a Numpy array for further processing in
 #              Python. The image is being displayed using an 
 #              OpenCV imshow window.
 #
#############################################################

import sys

if (sys.version_info.major >= 3 and sys.version_info.minor >= 8):
    import os
    #Following lines specifying, the location of DLLs, are required for Python Versions 3.8 and greater
    os.add_dll_directory("C:\BitFlow SDK 6.5\Bin64")
    os.add_dll_directory("C:\Program Files\CameraLink\Serial")

import BFModule.BufferAcquisition as Buf

import numpy, cv2
import time
import msvcrt

from datetime import datetime

keepUpdating = True

# The main function
def main():
    global keepUpdating

    print('Circular Acquisition Example')
    print('---------------------------------')

    CirAq = Buf.clsCircularAcquisition(Buf.ErrorMode.ErIgnore)

    #Call Open board function by showing the Board select dialog
    CirAq.Open()

    #Get board info parameters to create and open a display surface
    xsize = CirAq.GetBoardInfo(Buf.InquireParams.XSize)
    ysize = CirAq.GetBoardInfo(Buf.InquireParams.YSize)
    dispBitsPerPix = CirAq.GetBoardInfo(Buf.InquireParams.BitsPerPixDisplay) #Number of bits per pixel of the display. Currently this value must = 8, 24, or 32.
    imageBitsPerPix = CirAq.GetBoardInfo(Buf.InquireParams.BitsPerPix)

        # function to display the coordinates of
    # of the points clicked on the image
    def click_event(event, x, y, flags, params):
        nonlocal img
 
        # checking for left mouse clicks
        if event == cv2.EVENT_LBUTTONDOWN: 
            # displaying the coordinates
            # on the Shell
            print('(', x, ', ', y, ')')
            print('Pixel Value = ', img[y,x])
 

    #Get the number of buffers to allocate
    while 1:
        try:
            numBuffers = int(input('\nEnter number of buffers to allocate: '))
        except ValueError:
            print('Invalid entry. Try again.')
        else:
            break

    #Allocate the requested number of buffers
    CirAq.BufferSetup(numBuffers)

    #Setup acquisition using the default options
    CirAq.AqSetup(Buf.SetupOptions.DisableAqErrorSig)


    print("\nPress \'G\' to start Acquisition")
    print("Press \'S\' to Stop Acquisition")
    if(CirAq.GetTriggerMode() != Buf.TriggerModes.FreeRun):
        print("Press \'T\' to issue a SW Trigger")
    print("Press \'R\' to read a register value")
    print("Press \'W\' to write to a register")
    print("Press \'A\' to get Acquisition Status")
    print("\nPress \'X\' to exit test\n")


    while keepUpdating:        
        if (msvcrt.kbhit()):
            try:
                keyPressed = msvcrt.getch().decode('utf-8').upper()
            except Exception as e:
                print(e)
            else:
                try:
                    if (keyPressed == 'X'):
                        print('Exit Program.')
                        keepUpdating = False
                        CirAq.AqCleanup()
                        break
                    elif (keyPressed == 'G'):
                        print('Aquisition Started.')
                         #Start acquisition
                        CirAq.AqControl(Buf.AcqCommands.Start, Buf.AcqControlOptions.Async)
                    elif(keyPressed == 'S'):
                         #Stop acquisition
                        CirAq.AqControl(Buf.AcqCommands.Stop, Buf.AcqControlOptions.Async)
                        print('Aquisition Stopped.')
                        CirAq.GetCaptureStatus()
                    elif(keyPressed == 'T'):
                         #Issue trigger
                        CirAq.IssueSoftwareTrigger()
                        print('Trigger Sent.')                
                    elif(keyPressed == 'R'):
                        print('Reading register value . . .')
                        regName = input('Enter Register Name:')
                        try:
                            regID = CirAq.RegId(regName)
                        except Exception as e:
                            print(e)
                        else:
                            print('Reg ', regName, ' value = ', CirAq.RegPeek(regID))                        
                    elif(keyPressed == 'W'):
                        print('Writing to a register . . .')
                        regName = input('Enter Register Name:')
                        try:
                            regID = CirAq.RegId(regName)
                        except Exception as e:
                            print(e)
                        else:
                            regVal = int(input("Enter value to write: "))
                            CirAq.RegPoke(regID, regVal)
                    elif(keyPressed == 'A'):
                        print('Acquisition Status:')
                        AqStat = CirAq.GetAcqStatus()
                        print('  -Start:\t', AqStat.Start)
                        print('  -Stop:\t', AqStat.Stop)
                        print('  -Abort:\t', AqStat.Abort)
                        print('  -Pause:\t', AqStat.Pause)
                        print('  -Cleanup:\t', AqStat.Cleanup)
                except Exception as e:
                        print(e, '\n')
        else:
            try:
                if(CirAq.GetAcqStatus().Start == True):
                    curBuf = CirAq.WaitForFrame(0)
                    #Get Current buffer data as a numpy array
                    img = CirAq.GetBuffer(curBuf)
                    img = numpy.reshape(img, (ysize, xsize), order='C')
                    #converting to 16 bits, as OpenCV imshow does not support uint32 images
                    img = img.astype(numpy.uint16)
                    cv2.imshow("Image Window", img)
                    cv2.setMouseCallback('Image Window', click_event)
                    cv2.waitKey(1)
            except Exception as e:
                print(e)
                pass
    
    # destroy the OpenCV image window
    cv2.destroyAllWindows()

    #Clean up acquisition
    CirAq.AqCleanup()

    #Free allocated resources
    CirAq.BufferCleanup()

    #Close the board
    CirAq.Close()


if __name__ == "__main__":
    
   main()