def __init__(self, resolution = (320, 240)): """ Create a new instance of a PTCamera which uses PyCapture2's GigECamera API Parameters ---------- resolution: tuple of ints; default: (320, 240) Resolution of desired input video stream; default is 320x240 which will make sure the camera initialization will not error out regardless of the capture mode selected. """ #self._update_count = 0 # Ensure sufficient cameras are found bus = PyCapture2.BusManager() num_cams = bus.getNumOfCameras() print('Number of cameras detected: ', num_cams) if not num_cams: print('Insufficient number of cameras. Exiting...') exit() # Select camera on 0th index self.c = PyCapture2.GigECamera() uid = bus.getCameraFromIndex(0) self.c.connect(uid) self.initialize_camera_settings(resolution) print('Starting image capture...') self.c.startCapture() self._frame_req = True
def init_cam(self): # 1. Start the bus interface # 2. Connect to the camera and start capturin # often the camera throws a bus master failure in the first and a isochronous start failure # in the second connection attempt. These are supposed to be caught in the following. for i in range(100): print("detect bus") try: print("init cam") bus = pc2.BusManager() # test code cams = bus.discoverGigECameras(10) print(cams) # end test code bus.forceAllIPAddressesAutomatically( ) # necessary due to my networking inabilities cam = pc2.GigECamera() cam.connect( bus.getCameraFromSerialNumber( camera_serial_numbers[camera_index])) # set up camera for GigE use gigeconf = cam.getGigEConfig() gigeconf.enablePacketResend = True cam.setGigEConfig(gigeconf) # set up configuration of camera conf = cam.getConfiguration() conf.numBuffers = 4 conf.grabTimeout = self.acquisition_timer_interval conf.grabMode = 1 # BUFFER_FRAMES grab mode, see docs cam.setConfiguration(conf) # start streaming cam.startCapture() time.sleep(.1) print("Started stream for cam {0}".format( camera_serial_numbers[camera_index])) except pc2.Fc2error as e: try: cam.disconnect() except: pass del cam, bus print(e) print("Retrying 1...") else: break self.cam = cam # 3. collect framerates, videomodes, ... fr = pc2.FRAMERATE self.framerates = [f for f in dir(fr) if not f.startswith('__')] vm = pc2.VIDEO_MODE self.video_modes = [v for v in dir(vm) if not v.startswith('__')]
def initialize_cam(self, serial): """ Initializes a camera for a given serial number and bus. The bus should be initialized first. :returns: GigECamera object """ # sometimes the cam has a hard time starting. We catch some # exceptions and just try again. for i in range(20): cam = pc2.GigECamera() try: cam.connect(self.bus.getCameraFromSerialNumber(serial)) print("connected:") # set up camera for GigE use gigeconf = cam.getGigEConfig() gigeconf.enablePacketResend = True cam.setGigEConfig(gigeconf) # set up configuration of camera conf = cam.getConfiguration() conf.numBuffers = 4 conf.grabTimeout = self.acquisition_timer_interval conf.grabMode = 1 # BUFFER_FRAMES grab mode, see docs cam.setConfiguration(conf) # start streaming cam.startCapture() print("Started stream for cam {0}".format(serial)) return cam except pc2.Fc2error as e: try: cam.disconnect() except: pass del cam print(e) print("Retrying 2...") else: break time.sleep(.1) print("No connection to camera established.")
def __init__(self, width=720, height=480): self.width = width self.height = height #Connect to Camera bus = PyCapture2.BusManager() camInfo = bus.discoverGigECameras() self.cam = PyCapture2.GigECamera() uID = bus.getCameraFromIndex(0) self.cam.connect(uID) #Set Up Camera Parameters imgSetInfo = self.cam.getGigEImageSettingsInfo() imgSet = PyCapture2.GigEImageSettings() imgSet.offsetX = (2048 - self.width) / 2 imgSet.offsetY = (2448 - self.height) / 2 imgSet.height = self.height imgSet.width = self.width imgSet.pixelFormat = PyCapture2.PIXEL_FORMAT.RGB self.cam.setGigEImageSettings(imgSet)
def __init__(self, serial_number): """Initialize FlyCapture2 API camera. Searches all cameras reachable by the host using the provided serial number. Fails with API error if camera not found. This function also does a significant amount of default configuration. * It defaults the grab timeout to 1 s * Ensures use of the API's HighPerformanceRetrieveBuffer * Ensures the camera is in Format 7, Mode 0 with full frame readout and MONO8 pixels * If using a GigE camera, automatically maximizes the packet size and warns if Jumbo packets are not enabled on the NIC Args: serial_number (int): serial number of camera to connect to """ global PyCapture2 import PyCapture2 ver = PyCapture2.getLibraryVersion() min_ver = (2, 12, 3, 31) # first release with python 3.6 support if ver < min_ver: raise RuntimeError( f"PyCapture2 version {ver} must be >= {min_ver}") print('Connecting to SN:%d ...' % serial_number) bus = PyCapture2.BusManager() self.camera = PyCapture2.Camera() self.camera.connect(bus.getCameraFromSerialNumber(serial_number)) # set which values of properties to return self.get_props = [ 'present', 'absControl', 'absValue', 'onOff', 'autoManualMode', 'valueA', 'valueB' ] fmts = { prop: getattr(PyCapture2.PIXEL_FORMAT, prop) for prop in dir(PyCapture2.PIXEL_FORMAT) if not prop.startswith('_') } self.pixel_formats = IntEnum('pixel_formats', fmts) self._abort_acquisition = False # check if GigE camera. If so, ensure max packet size is used cam_info = self.camera.getCameraInfo() if cam_info.interfaceType == PyCapture2.INTERFACE_TYPE.GIGE: # need to close generic camera first to avoid strange interactions print('Checking Packet size for GigE Camera...') self.camera.disconnect() gige_camera = PyCapture2.GigECamera() gige_camera.connect(bus.getCameraFromSerialNumber(serial_number)) mtu = gige_camera.discoverGigEPacketSize() if mtu <= 1500: msg = """WARNING: Maximum Transmission Unit (MTU) for ethernet NIC FlyCapture2_Camera SN:%d is connected to is only %d. Reliable operation not expected. Please enable Jumbo frames on NIC.""" print(dedent(msg % (serial_number, mtu))) gige_pkt_size = gige_camera.getGigEProperty( PyCapture2.GIGE_PROPERTY_TYPE.GIGE_PACKET_SIZE) # only set if not already at correct value if gige_pkt_size.value != mtu: gige_pkt_size.value = mtu gige_camera.setGigEProperty(gige_pkt_size) print(' Packet size set to %d' % mtu) else: print(' GigE Packet size is %d' % gige_pkt_size.value) # close GigE handle to camera, re-open standard handle gige_camera.disconnect() self.camera.connect(bus.getCameraFromSerialNumber(serial_number)) # set standard device configuration config = self.camera.getConfiguration() config.grabTimeout = 1000 # in ms config.highPerformanceRetrieveBuffer = True self.camera.setConfiguration(config) # ensure camera is in Format7,Mode 0 custom image mode fmt7_info, supported = self.camera.getFormat7Info(0) if supported: # to ensure Format7, must set custom image settings # defaults to full sensor size and 'MONO8' pixel format print('Initializing to default Format7, Mode 0 configuration...') fmt7_default = PyCapture2.Format7ImageSettings( 0, 0, 0, fmt7_info.maxWidth, fmt7_info.maxHeight, self.pixel_formats['MONO8'].value) self._send_format7_config(fmt7_default) else: msg = """Camera does not support Format7, Mode 0 custom image configuration. This driver is therefore not compatible, as written.""" raise RuntimeError(dedent(msg))
exposureTime = 1 # exposure time in ms timeToSleep = 1000 # time that the computer sleeps between image acquisitions, in ms timeToWait = 1000 # time the camera waits for a new trigger before throwing an error, in ms # Ensures sufficient cameras are found bus = PyCapture2.BusManager() numCams = bus.getNumOfCameras() # serial = getCameraSerialNumberFromIndex(1) #this line not necessary at the moment print "Number of cameras detected: ", numCams if not numCams: print "Insufficient number of cameras. Exiting..." exit() #c = PyCapture2.Camera() c = PyCapture2.GigECamera() # Look up the camera's serial number and pass it to this function: c.connect(bus.getCameraFromSerialNumber(cameraSerial)) # Powers on the Camera cameraPower = 0x610 powerVal = 0x80000000 c.writeRegister(cameraPower, powerVal) # Waits for camera to power up retries = 10 timeToSleep = 0.1 #seconds for i in range(retries): time.sleep(timeToSleep) try:
def initialize(self): # called only once, before calling "update" for the first time # logger.info('Blackfly camera {} is being initialized'.format(self.serial)) # adds an instance of PyCapture2's camera class self.bus = PyCapture2.BusManager() self.camera_instance = PyCapture2.GigECamera() # connects the software camera object to a physical camera self.camera_instance.connect( self.bus.getCameraFromSerialNumber(self.parameters['serial'])) # Powers on the Camera cameraPower = 0x610 powerVal = 0x80000000 try: self.camera_instance.writeRegister(cameraPower, powerVal) except PyCapture2.Fc2error: print "problem" # Waits for camera to power up retries = 10 timeToSleep = 0.1 # seconds for i in range(retries): try: regVal = self.camera_instance.readRegister(cameraPower) # Camera might not respond to register reads during powerup. except PyCapture2.Fc2error: pass awake = True if regVal == powerVal: break awake = False time.sleep(timeToSleep) if not awake: # aborts if Python was unable to wake the camera # logger.info('Could not wake Blackfly camera. Exiting...') exit() # # Use these three lines to check camera info, if desired # self.camInfo = self.camera_instance.getCameraInfo() # resolution_str = self.camInfo.sensorResolution # converts the resolution information to an int list # self.cam_resolution = map(int, resolution_str.split('x')) # # print "Serial number - ", self.camInfo.serialNumber # # print "Camera model - ", self.camInfo.modelName # # Enables the camera's 3.3V, 120mA output on GPIO pin 3 (red jacketed # lead) if needed # output_voltage = 0x19D0 # voltage_mode = 0x00000001 # self.camera[cam_index].writeRegister(output_voltage, voltage_mode) # Configures trigger mode for hardware triggering trigger_mode = self.camera_instance.getTriggerMode() trigger_mode.onOff = True # turns the trigger on trigger_mode.mode = 0 trigger_mode.polarity = 1 trigger_mode.source = 0 # specifies an external hardware trigger self.camera_instance.setTriggerMode(trigger_mode) # # Sets the camera grab mode: # # 0 = The camera retrieves only the newest image from the buffer each time the RetrieveBuffer() function # # is called. Older images will be dropped. See p. 93 in the PyCapture 2 API Reference manual. # # 1 = The camera retrieves the oldest image from the buffer each time RetrieveBuffer() is called. # # Ungrabbed images will accumulated until the buffer is full, after which the oldest will be deleted. PyCapture2.GRAB_MODE = 0 self.isInitialized = True