def print_device_info(nodemap, cam_num):
    """
    This function prints the device information of the camera from the transport
    layer; please see NodeMapInfo example for more in-depth comments on printing
    device information from the nodemap.

    :param nodemap: Transport layer device nodemap.
    :param cam_num: Camera number.
    :type nodemap: INodeMap
    :type cam_num: int
    :returns: True if successful, False otherwise.
    :rtype: bool
    """

    print('Printing device information for camera %d... \n' % cam_num)

    try:
        result = True
        node_device_information = PySpin.CCategoryPtr(
            nodemap.GetNode('DeviceInformation'))

        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(
                node_device_information):
            features = node_device_information.GetFeatures()
            for feature in features:
                node_feature = PySpin.CValuePtr(feature)
                print(
                    '%s: %s' %
                    (node_feature.GetName(), node_feature.ToString() if
                     PySpin.IsReadable(node_feature) else 'Node not readable'))

        else:
            print('Device control information not available.')
        print()

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        return False

    return result
Example #2
0
def camera():
    """ Detect all connected FLIR cameras. 
    
    Returns
    -------
    instrs : array of instr objects
        All of the detected Cameras in the system.
    """
    instrs = {}
    system = PySpin.System.GetInstance()
    cam_list = system.GetCameras()
    for i, cam in enumerate(cam_list):
        # Nodes are just properties of the camera
        # TL is the transport layer - never initializes the camera
        nodemap_tl = cam.GetTLDeviceNodeMap()
        node = PySpin.CStringPtr(nodemap_tl.GetNode('DeviceSerialNumber'))
        if PySpin.IsAvailable(node) and PySpin.IsReadable(node):
            serial = node.ToString()
        node = PySpin.CStringPtr(nodemap_tl.GetNode('DeviceModelName'))
        if PySpin.IsAvailable(node) and PySpin.IsReadable(node):
            model = node.ToString()    
        
        instr = instrInfo.Camera(serial)
        instr.model = model
        instrs[serial] = instr
        del cam
    cam_list.Clear()
    system.ReleaseInstance()
    del system
    return instrs
Example #3
0
def listCameras():
    """
    Prints a list of available cameras. This is primarily for informational 
    purposes. You must call pySpinInitialize() first.
    """
    global camera_list

    assert camera_list is not None, "pySpinInitialize() was not called?"

    cam_data = {}
    for cam in camera_list:
        nodemap_tldevice = cam.GetTLDeviceNodeMap()

        # Get serial number.
        node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber'))
        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(node_device_serial_number):
            device_serial_number = node_device_serial_number.GetValue()
        else:
            raise SpinnakerException("Cannot access serial number of device " + str(cam))

        # Get model.
        node_device_model_name = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceModelName'))
        if PySpin.IsAvailable(node_device_model_name) and PySpin.IsReadable(node_device_model_name):
            device_model_name = node_device_model_name.ToString()
        else:
            raise SpinnakerException("Cannot model name of device " + str(cam))

        cam_data[device_serial_number] = device_model_name

    print("Available cameras:")
    for key in sorted(cam_data):
        print(cam_data[key] + " (" + key + ")")
    print()
Example #4
0
def change_height_and_gain(nodemap):
    """
    This function demonstrates the triggering of the nodemap callbacks. First it
    changes height, which executes the callback registered to the height node, and
    then it changes gain, which executes the callback registered to the gain node.

    :param nodemap: Device nodemap.
    :type nodemap: INodeMap
    :return: True if successful, False otherwise.
    :rtype: bool
    """
    print('\n***CHANGE HEIGHT & GAIN ***\n')

    try:
        result = True

        # Change height to trigger height callback
        #
        # *** NOTES ***
        # Notice that changing the height only triggers the callback function
        # registered to the height node.
        node_height = PySpin.CIntegerPtr(nodemap.GetNode('Height'))
        if not PySpin.IsAvailable(node_height) or not PySpin.IsWritable(node_height) \
                or node_height.GetInc() == 0 or node_height.GetMax() == 0:

            print('Unable to retrieve height. Aborting...')
            return False

        height_to_set = node_height.GetMax()

        print(
            'Regular function message:\n\tHeight about to be changed to %i...\n'
            % height_to_set)

        node_height.SetValue(height_to_set)

        # Change gain to trigger gain callback
        #
        # *** NOTES ***
        # The same is true of changing the gain node; changing a node will
        # only ever trigger the callback function (or functions) currently
        # registered to it.
        node_gain = PySpin.CFloatPtr(nodemap.GetNode('Gain'))
        if not PySpin.IsAvailable(node_gain) or not PySpin.IsWritable(
                node_gain) or node_gain.GetMax() == 0:
            print('Unable to retrieve gain...')
            return False

        gain_to_set = node_gain.GetMax() / 2.0

        print(
            'Regular function message:\n\tGain about to be changed to %f...\n'
            % gain_to_set)
        node_gain.SetValue(gain_to_set)

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        result = False

    return result
def print_device_info(nodemap, cam_num):
    """
	This function prints the device information of each camera from the transport layer.

	:param nodemap: Transport layer device nodemap
	:param cam_num: Camera number
	:type nodemap: INodeMap
	:type cam_num: int
	:returns: True if successful, False otherwise
	:rtype: bool
	"""

    print('Printing device information for camera {}'.format(cam_num))

    try:
        result = True
        node_device_information = PySpin.CCategoryPtr(
            nodemap.GetNode('DeviceInformation'))

        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(
                node_device_information):
            features = node_device_information.GetFeatures()

            for feature in features:
                node_feature = PySpin.CValuePtr(feature)
                print('{}: {}'.format(
                    node_feature.GetName(),
                    node_feature.ToString() if PySpin.IsReadable(node_feature)
                    else 'Node not readable'))

            else:
                print('Device control information not available.')
            print()

    except PySpin.SpinnakerException as ex:
        print('Error: {}'.format(ex))
        return False

    return result
Example #6
0
def display_chunk_data_from_nodemap(nodemap):
    """
    This function displays all available chunk data by looping through the
    chunk data category node on the nodemap.

    :param nodemap: Device nodemap to retrieve images from.
    :type nodemap: INodeMap
    :return: True if successful, False otherwise
    :rtype: bool
    """
    print('Printing chunk data from nodemap...')
    try:
        result = True
        # Retrieve chunk data information nodes
        #
        # *** NOTES ***
        # As well as being written into the payload of the image, chunk data is
        # accessible on the GenICam nodemap. When chunk data is enabled, it is
        # made available from both the image payload and the nodemap.
        chunk_data_control = PySpin.CCategoryPtr(
            nodemap.GetNode('ChunkDataControl'))
        if not PySpin.IsAvailable(chunk_data_control) or not PySpin.IsReadable(
                chunk_data_control):
            print('Unable to retrieve chunk data control. Aborting...\n')
            return False

        features = chunk_data_control.GetFeatures()

        # Iterate through children
        for feature in features:
            feature_node = PySpin.CNodePtr(feature)
            feature_display_name = '\t{}:'.format(
                feature_node.GetDisplayName())

            if not PySpin.IsAvailable(feature_node) or not PySpin.IsReadable(
                    feature_node):
                print('{} node not available'.format(feature_display_name))
                result &= False
                continue
            # Print node type value
            #
            # *** NOTES ***
            # All nodes can be cast as value nodes and have their information
            # retrieved as a string using the ToString() method. This is much
            # easier than dealing with each individual node type.
            else:
                feature_value = PySpin.CValuePtr(feature)
                print('{} {}'.format(feature_display_name,
                                     feature_value.ToString()))
    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        result = False

    return result
Example #7
0
    def _set_trigger_mode(self, state='Off'):
        """sets the camera to work with external trigger or turns off external trigger
        state must be strong on or off"""
        if state.lower() not in ['on', 'off']:
            raise ValueError(f'Unknown value {state} must be on or off')
        node_trigger_mode = PySpin.CEnumerationPtr(
            self._nodemap.GetNode('TriggerMode'))
        if not PySpin.IsAvailable(node_trigger_mode) or not PySpin.IsReadable(
                node_trigger_mode):
            logger.error(
                'Unable to disable trigger mode (node retrieval). Aborting...')
            return False

        node_trigger_mode_off = node_trigger_mode.GetEntryByName(state.title())
        if not PySpin.IsAvailable(
                node_trigger_mode_off) or not PySpin.IsReadable(
                    node_trigger_mode_off):
            logger.error(
                'Unable to disable trigger mode (enum entry retrieval). Aborting...'
            )
            return False
        node_trigger_mode.SetIntValue(node_trigger_mode_off.GetValue())
 def printDeviceInfo(self):
     try:
         result = 0
         nodemap = self.camera_.GetTLDeviceNodeMap()
         nodeDeviceInformation = PySpin.CCategoryPtr(
             nodemap.GetNode('DeviceInformation'))
         if PySpin.IsAvailable(nodeDeviceInformation) and PySpin.IsReadable(
                 nodeDeviceInformation):
             print('*** DEVICE INFORMATION ***\n')
             features = nodeDeviceInformation.GetFeatures()
             for feature in features:
                 node_feature = PySpin.CValuePtr(feature)
                 print('%s: %s' %
                       (node_feature.GetName(), node_feature.ToString()
                        if PySpin.IsReadable(node_feature) else
                        'Node not readable'))
         else:
             print('Device control information not available.')
     except PySpin.SpinnakerException as ex:
         print('Error: %s' % ex)
         result = -1
     return result
Example #9
0
def setExposureTime(cam):
    try:
        result = True
        print('Exposure Settings')
        #Step 1: Set Exposure Auto to Off (then the node Exposure Time will bekome Writable )
        node_ExposureAuto = PySpin.CEnumerationPtr(
            cam.GetNodeMap().GetNode('ExposureAuto'))

        if PySpin.IsAvailable(node_ExposureAuto) and PySpin.IsWritable(
                node_ExposureAuto):
            print('Current Value for Exposure Auto: ',
                  node_ExposureAuto.GetCurrentEntry().GetDisplayName())

        node_ExposureAutoOff = node_ExposureAuto.GetEntryByName('Off')
        if not PySpin.IsAvailable(
                node_ExposureAutoOff) or not PySpin.IsReadable(
                    node_ExposureAutoOff):
            print(
                'Unable to set Exposure Mode  to Off (entry retrieval). Aborting...'
            )
            return False
        # Retrieve integer value from entry node
        exposure_autoOff = node_ExposureAutoOff.GetValue()

        node_ExposureAuto.SetIntValue(exposure_autoOff)
        print('Current Value for Exposure Auto: ',
              node_ExposureAuto.GetCurrentEntry().GetDisplayName())

        #Step 2: Set a value for the Exposure Time
        node_ExposureTime = PySpin.CFloatPtr(
            cam.GetNodeMap().GetNode('ExposureTime'))
        if PySpin.IsAvailable(node_ExposureTime) and PySpin.IsWritable(
                node_ExposureTime):
            print('Current Value for Exposure Time: ',
                  node_ExposureTime.GetValue())

        #print('Maximum Value: ', node_ExposureTime.GetMax())
        #print('minimum Value: ', node_ExposureTime.GetMin())
        #example to set a value between the min and max
        #minim=node_ExposureTime.GetMin()
        node_ExposureTime.SetValue(4000)  # 5000 us should generate ~200fps
        print('The Value for Exposure Time is set to: ',
              node_ExposureTime.GetValue())

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        return False

    return result
Example #10
0
 def SetValue(self, val):
     super().SetValue()
     if val in (
             PySpin.TriggerActivation_AnyEdge,
             PySpin.TriggerActivation_LevelHigh,
             PySpin.TriggerActivation_LevelLow,
             PySpin.TriggerActivation_FallingEdge,
             PySpin.TriggerActivation_RisingEdge,
     ):
         self.val = val
     else:
         raise PySpin.SpinnakerException(f'{val} is not a valid value')
     return
Example #11
0
 def SetValue(self, val):
     super().SetValue()
     if val == PySpin.TriggerMode_On:
         if self._streaming:
             self._p.pause()
         self.val = val
     elif val == PySpin.TriggerMode_Off:
         if self._streaming:
             self._p.unpause()
         self.val = val
     else:
         raise PySpin.SpinnakerException(f'{val} is an invalid value')
     return
def print_device_info(cam):
    """
    This function prints the device information of the camera from the transport
    layer; please see NodeMapInfo example for more in-depth comments on printing
    device information from the nodemap.

    :param cam: Camera to get device information from.
    :type cam: CameraPtr
    :return: True if successful, False otherwise.
    :rtype: bool
    """

    print('*** DEVICE INFORMATION ***\n')

    try:
        result = True
        nodemap = cam.GetTLDeviceNodeMap()

        node_device_information = PySpin.CCategoryPtr(
            nodemap.GetNode('DeviceInformation'))

        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(
                node_device_information):
            features = node_device_information.GetFeatures()
            for feature in features:
                node_feature = PySpin.CValuePtr(feature)
                print(
                    '%s: %s' %
                    (node_feature.GetName(), node_feature.ToString() if
                     PySpin.IsReadable(node_feature) else 'Node not readable'))

        else:
            print('Device control information not available.')

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex.message)
        return False

    return result
def print_node_value(nodemap, node_name):
    """
    Print the value of an enumeration node

    :param nodemap:
    :param node_name:
    :return:
    """

    result = True

    node = PySpin.CEnumerationPtr(nodemap.GetNode(node_name))

    if not PySpin.IsAvailable(node) or not PySpin.IsReadable(node):
        print('Unable to read node: {}'.format(node_name))
        return False

    display_name = node.GetName()
    value = node.ToString()
    print('{}: {}'.format(display_name, value))

    return result
Example #14
0
    def start(self):
        '''
        Start the continuous acquisition mode
        '''
        try:
            #get handle for acquisition mode
            node_acquisition_mode = PySpin.CEnumerationPtr(
                self.nodemap.GetNode("AcquisitionMode"))
            if not PySpin.IsAvailable(
                    node_acquisition_mode) or not PySpin.IsWritable(
                        node_acquisition_mode):
                print(
                    "Unable to set acquisition mode to continuous (enum retrieval). Aborting..."
                )
                return False

            # Retrieve entry node from enumeration node
            node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName(
                "Continuous")
            if not PySpin.IsAvailable(
                    node_acquisition_mode_continuous) or not PySpin.IsReadable(
                        node_acquisition_mode_continuous):
                print(
                    "Unable to set acquisition mode to continuous (entry retrieval). Aborting..."
                )
                return False

            # Retrieve integer value from entry node
            acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue(
            )

            # Set integer value from entry node as new value of enumeration node
            node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

            #Begin Acquisition
            self.cam.BeginAcquisition()

        except PySpin.SpinnakerException as ex:
            print("Error: %s" % ex)
    def __init__(self, flir_cam, cam, output_loc, im_passback):

        super(ImageEventHandler, self).__init__()

        nodemap = flir_cam.GetTLDeviceNodeMap()

        # Set internal state
        self.rec_state = constants.STATE_MW_IDLE
        self.recording = False
        self.cam = cam
        self.output_loc = output_loc
        self.output = None
        self.parent_queue = None
        self.im_passback = im_passback
        self.start_time = 0
        self.mutex = QtCore.QMutex()
        self.im_toggle = True
        self.im_callback = None

        # Save dimensions
        self.height = flir_cam.Height()
        self.width = flir_cam.Width()
        self.fps = flir_cam.AcquisitionFrameRate.GetValue()

        self.threadpool = QtCore.QThreadPool()
        self.timer = time.time()

        # Images that will become a saved video
        self.images = []

        # Retrieve device serial number
        node_device_serial_number = PySpin.CStringPtr(
            nodemap.GetNode('DeviceSerialNumber'))

        if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(
                node_device_serial_number):
            self._device_serial_number = node_device_serial_number.GetValue()

        del flir_cam
Example #16
0
 def BeginAcquisition(self):
     if self._initialized is False:
         raise PySpin.SpinnakerException('Camera is not initialized')
     else:
         if self._p is not None:
             self._p.join()
             self._p = None
         framerate = self.AcquisitionFrameRate.GetValue()
         shape = (self.Width.GetValue(), self.Height.GetValue())
         buffersize = self.TLStream.StreamBufferCountManual.GetValue()
         self._p = DummyAcquisitionProcess(buffersize, framerate, shape)
         self._p.start()
         self._streaming = True
Example #17
0
    def GetWhiteBalance(self):
        """ Get White Balance (red, blue)"""
        try:
            wb_auto = PySpin.CEnumerationPtr(
                self.nodemap.GetNode('BalanceWhiteAuto'))
            wb_auto.SetIntValue(wb_auto.GetEntryByName('Off').GetValue())
            wb_ratio = PySpin.CEnumerationPtr(
                self.nodemap.GetNode('BalanceRatioSelector'))

            # Blue
            wb_ratio.SetIntValue(wb_ratio.GetEntryByName('Blue').GetValue())
            blue = PySpin.CFloatPtr(
                self.nodemap.GetNode('BalanceRatioRaw')).GetValue()

            # Red
            wb_ratio.SetIntValue(wb_ratio.GetEntryByName('Red').GetValue())
            red = PySpin.CFloatPtr(
                self.nodemap.GetNode('BalanceRatioRaw')).GetValue()
            return blue, red
        except:
            print("Could not get White Balance ")
            return 1, 1
Example #18
0
 def SetValue(self, val):
     super().SetValue()
     if val not in [
             PySpin.StreamBufferHandlingMode_NewestOnly,
             PySpin.StreamBufferHandlingMode_OldestFirst,
             PySpin.StreamBufferHandlingMode_NewestFirst,
             PySpin.StreamBufferHandlingMode_NewestFirstOverwrite,
             PySpin.StreamBufferHandlingMode_OldestFirstOverwrite,
     ]:
         raise PySpin.SpinnakerException(
             f'{val} is not a valid value')
     else:
         self.val = val
def print_transport_layer_interface_info(interface):
    """
    Prints stream information from the transport layer.

    *** NOTES ***
    In QuickSpin, accessing interface information is accomplished via an
    interface's TLInterface property. The TLInterface property houses
    nodes that hold information about the interface such as the three
    demonstrated below, other general interface information, and
    GEV addressing information. The TLInterface property allows access to
    nodes that would generally be retrieved through the interface nodemap
    in full Spinnaker.

    Interface nodes should also always be checked for availability and
    readability (or writability when applicable). If a node retrieval
    error occurs but remains unhandled, an exception is thrown.

    :param interface: Interface to get information from.
    :type interface: InterfacePtr
    :return: True if successful, False otherwise.
    :rtype: bool
    """
    try:
        result = True

        # Print interface display name
        if interface.TLInterface.InterfaceDisplayName.GetAccessMode() == PySpin.RO:
            print('Interface display name: %s' % interface.TLInterface.InterfaceDisplayName.ToString())
        else:
            print('Interface display name: unavailable')
            result = False

        # Print interface ID
        if interface.TLInterface.InterfaceID.GetAccessMode() == PySpin.RO:
            print('Interface ID: %s' % interface.TLInterface.InterfaceID.ToString())
        else:
            print('Interface ID: unavailable')
            result = False

        # Print interface type
        if PySpin.IsReadable(interface.TLInterface.InterfaceType.GetAccessMode()):
            print('Interface type: %s' % interface.TLInterface.InterfaceType.ToString())
        else:
            print('Interface type: unavailable')
            result = False

    except PySpin.SpinnakerException as ex:
        print('Error: %s' % ex)
        return False

    return result
Example #20
0
    def __init__(self, index):
        """
        Parameters
        ----------
        index : int
            id of the video capturing device to open.
        """
        # Check for 'index' type
        if isinstance(index, (int, str))==False:
            raise TypeError("Argument 'index' is required to be an integer or a string")

        # Cerate system instance and get camera list 
        self._system = PySpin.System.GetInstance()
        self._cam_list = self._system.GetCameras()
        num_cam = self._cam_list.GetSize()

        # Check for available cameras
        if num_cam==0:
            print("EasyPySpin: no camera is available", file=stderr)
            self._cam_list.Clear()
            self._system.ReleaseInstance()
            return None
        
        # Try to connect camera
        try:
            # Index case
            if type(index) is int:
                # Check for 'index' bound
                if index<0 or num_cam-1<index:
                    print(f"EasyPySpin: out device of bound (0-{num_cam-1}): {index}", file=stderr)
                self.cam = self._cam_list.GetByIndex(index)
            # Serial case
            elif type(index) is str:
                self.cam = self._cam_list.GetBySerial(index)
        except:
            print("EasyPySpin: camera failed to properly initialize!", file=stderr)
            self._cam_list.Clear()
            self._system.ReleaseInstance()
            return None

        self.cam.Init()
        self.nodemap = self.cam.GetNodeMap()
        
        s_node_map = self.cam.GetTLStreamNodeMap()
        handling_mode = PySpin.CEnumerationPtr(s_node_map.GetNode('StreamBufferHandlingMode'))
        handling_mode_entry = handling_mode.GetEntryByName('NewestOnly')
        handling_mode.SetIntValue(handling_mode_entry.GetValue())

        self.grabTimeout = PySpin.EVENT_TIMEOUT_INFINITE
        self.streamID = 0
        self.auto_software_trigger_execute = False
Example #21
0
def print_device_info(nodemap):
    """
    This function prints the device information of the camera from the transport
    layer; please see NodeMapInfo example for more in-depth comments on printing
    device information from the nodemap.

    :param nodemap: Transport layer device nodemap.
    :type nodemap: INodeMap
    :returns: True if successful, False otherwise.
    :rtype: bool
    """

    print('*** DEVICE INFORMATION ***\n')

    try:
        result = True
        node_device_information = PySpin.CCategoryPtr(
            nodemap.GetNode('DeviceInformation'))

        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(
                node_device_information):
            features = node_device_information.GetFeatures()
            for feature in features:
                node_feature = PySpin.CValuePtr(feature)
                feature_string = node_feature.ToString() if PySpin.IsReadable(
                    node_feature) else 'Node not readable'
                print('{}: {}'.format(node_feature.GetName(), feature_string))

        else:
            print('Device control information not available.')

        print('')

    except PySpin.SpinnakerException as ex:
        print('Error: {}'.format(ex))
        return False

    return result
    def print_device_info(self, nodemap):
        """
		This function prints the device information of the camera from the transport
		layer; please see NodeMapInfo example for more in-depth comments on printing
		device information from the nodemap.

		:param nodemap: Transport layer device nodemap.
		:type nodemap: INodeMap
		:returns: True if successful, False otherwise.
		:rtype: bool
		"""

        print "*** DEVICE INFORMATION ***\n"

        try:
            result = True
            node_device_information = PySpin.CCategoryPtr(
                nodemap.GetNode("DeviceInformation"))

            if PySpin.IsAvailable(
                    node_device_information) and PySpin.IsReadable(
                        node_device_information):
                features = node_device_information.GetFeatures()
                for feature in features:
                    node_feature = PySpin.CValuePtr(feature)
                    print "%s: %s" % (node_feature.GetName(),
                                      node_feature.ToString()
                                      if PySpin.IsReadable(node_feature) else
                                      "Node not readable")

            else:
                print "Device control information not available."

        except PySpin.SpinnakerException as ex:
            print "Error: %s" % ex
            return False

        return result
Example #23
0
 def acquire_images(self, n=1):
     # TODO: ideas to make this faster -> only set nodemap once use async
     if hasattr(self, "imsize"):
         image_data = np.zeros(self.imsize+(n, self.ncams), dtype="uint8")
     for cam in self.cams:  # start the cameras
         node_acquisition_mode = PySpin.CEnumerationPtr(
             cam.GetNodeMap().GetNode('AcquisitionMode'))
         if (not PySpin.IsAvailable(node_acquisition_mode) or
                 not PySpin.IsWritable(node_acquisition_mode)):
             raise ValueError(
                 'Unable to set acquisition to continuous, aborting...')
         node_acquisition_mode_continuous = \
             node_acquisition_mode.GetEntryByName('Continuous')
         if (not PySpin.IsAvailable(node_acquisition_mode_continuous) or
                 not PySpin.IsReadable(node_acquisition_mode_continuous)):
             raise ValueError(
                 'Unable to set acquisition to continuous, aborting...')
         acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue()
         node_acquisition_mode.SetIntValue(acquisition_mode_continuous)
         cam.BeginAcquisition()
     for i_image in range(n):
         for i_cam, cam in enumerate(self.cams):
             time.sleep(0.1)
             image_result = cam.GetNextImage()
             if image_result.IsIncomplete():
                 raise ValueError('Image incomplete: image status %d ...'
                                  % image_result.GetImageStatus())
             image = image_result.Convert(
                 PySpin.PixelFormat_Mono8, PySpin.HQ_LINEAR)
             image = image.GetNDArray()
             image.setflags(write=1)
             image_result.Release()
             if hasattr(self, "imsize"):
                 image_data[:, :, i_image, i_cam] = image
             else:
                 image_data = image
     [cam.EndAcquisition() for cam in self.cams]
     return image_data
Example #24
0
def print_device_info(nodemap):
    """
    # This function prints the device information of the camera from the transport
    # layer; please see NodeMapInfo example for more in-depth comments on printing
    # device information from the nodemap.

    :param nodemap: Device nodemap.
    :type nodemap: INodeMap
    :return: return True if successful, False otherwise
    :rtype: bool
    """
    result = True
    print "*** DEVICE INFORMATION ***\n"

    try:
        node_device_information = PySpin.CCategoryPtr(
            nodemap.GetNode("DeviceInformation"))

        if PySpin.IsAvailable(node_device_information) and PySpin.IsReadable(
                node_device_information):
            features = node_device_information.GetFeatures()
            for feature in features:
                node_feature = PySpin.CValuePtr(feature)
                if PySpin.IsReadable(node_feature):
                    feature_string = node_feature.ToString()
                else:
                    feature_string = "Node not readable"

                print "{}: {}".format(node_feature.GetName(), feature_string)

        else:
            print "Device control information not available."

    except PySpin.SpinnakerException as ex:
        print "Error: {}".format(ex)
        result = False

    return result
    def set_pixel_format(self):
        try:
            nodemap = self.cam.GetNodeMap()
            node_pixel_format = PySpin.CEnumerationPtr(
                nodemap.GetNode('PixelFormat'))
            if PySpin.IsAvailable(node_pixel_format) and PySpin.IsWritable(
                    node_pixel_format):
                if self._pixel_format is BayerPattern.GRAY:
                    node_pixel_format_type = PySpin.CEnumEntryPtr(
                        node_pixel_format.GetEntryByName('Mono8'))
                elif self._pixel_format is BayerPattern.RGB:
                    node_pixel_format_type = PySpin.CEnumEntryPtr(
                        node_pixel_format.GetEntryByName('RGB8'))
                elif self._pixel_format is BayerPattern.BGR:
                    node_pixel_format_type = PySpin.CEnumEntryPtr(
                        node_pixel_format.GetEntryByName('BGR8'))
                else:
                    node_pixel_format_type = PySpin.CEnumEntryPtr(
                        node_pixel_format.GetEntryByName('Mono8'))
                if PySpin.IsAvailable(
                        node_pixel_format_type) and PySpin.IsReadable(
                            node_pixel_format_type):
                    pixel_format_type = node_pixel_format_type.GetValue()
                    node_pixel_format.SetIntValue(pixel_format_type)
                    print('Pixel format set to: %s' %
                          node_pixel_format.GetCurrentEntry().GetSymbolic())
                else:
                    raise Exception("[ERROR] Can't set BayerPattern.",
                                    self.cam.PixelFormat.GetAccessMode())
            else:
                print(PySpin.IsAvailable(node_pixel_format))
                raise Exception("[ERROR] Can't set BayerPattern.",
                                self.cam.PixelFormat.GetAccessMode())

        except PySpin.SpinnakerException as ex:
            raise Exception('[ERROR] %s' % ex)

        return True
Example #26
0
    def initSingleCamera(self, cam, nodemap, nodemap_tldevice):

          # In order to access the node entries, they have to be casted to a pointer type (CEnumerationPtr here)
          node_acquisition_mode = PySpin.CEnumerationPtr(nodemap.GetNode('AcquisitionMode'))
          if not PySpin.IsAvailable(node_acquisition_mode) or not PySpin.IsWritable(node_acquisition_mode):
              applyai.log('Unable to set acquisition mode to continuous (enum retrieval). Aborting...', self.logname)
              return False

          # Retrieve entry node from enumeration node
          node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName('Continuous')
          if not PySpin.IsAvailable(node_acquisition_mode_continuous) or not PySpin.IsReadable(node_acquisition_mode_continuous):
              applyai.log('Unable to set acquisition mode to continuous (entry retrieval). Aborting...', self.logname)
              return False

          # Retrieve integer value from entry node
          acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue()

          # Set integer value from entry node as new value of enumeration node
          node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

          applyai.log('Acquisition mode set to continuous...', self.logname)

          #  Begin acquiring images
          #
          #  *** NOTES ***
          #  What happens when the camera begins acquiring images depends on the
          #  acquisition mode. Single frame captures only a single image, multi
          #  frame catures a set number of images, and continuous captures a
          #  continuous stream of images. Because the example calls for the
          #  retrieval of 10 images, continuous mode has been set.
          #
          #  *** LATER ***
          #  Image acquisition must be ended when no more images are needed.
          cam.BeginAcquisition()

          applyai.log('Acquiring images...', self.logname)

          #  Retrieve device serial number for filename
          #
          #  *** NOTES ***
          #  The device serial number is retrieved in order to keep cameras from
          #  overwriting one another. Grabbing image IDs could also accomplish
          #  this.
          device_serial_number = ''
          node_device_serial_number = PySpin.CStringPtr(nodemap_tldevice.GetNode('DeviceSerialNumber'))
          if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(node_device_serial_number):
              device_serial_number = node_device_serial_number.GetValue()
              applyai.log('Device serial number retrieved as %s...' % device_serial_number, self.logname)
Example #27
0
    def reset_trigger(self, nodemap):

        try:
            result = True
            node_trigger_mode = PySpin.CEnumerationPtr(
                nodemap.GetNode('TriggerMode'))
            if not PySpin.IsAvailable(
                    node_trigger_mode) or not PySpin.IsReadable(
                        node_trigger_mode):
                return False

            node_trigger_mode_off = node_trigger_mode.GetEntryByName('Off')
            if not PySpin.IsAvailable(
                    node_trigger_mode_off) or not PySpin.IsReadable(
                        node_trigger_mode_off):
                return False

            node_trigger_mode.SetIntValue(node_trigger_mode_off.GetValue())

        except PySpin.SpinnakerException as ex:
            result = False

        return result
Example #28
0
 def get_node_entries(self, node_name: str) -> List[Any]:
     node: PySpin.INode = self._get_node(node_name)
     if node is None:
         raise ValueError(f"{node_name} node is not available")
     elif "GetPrincipalInterfaceType" not in dir(node):
         raise ValueError(
             f"Could not determine the type of node: {node_name}")
     elif node.GetPrincipalInterfaceType() == PySpin.intfIEnumeration:
         return self._get_available_enum_entries(
             PySpin.CEnumerationPtr(node))
     else:
         raise ValueError(
             f"Range not available for {node_name} node of type: {node.GetPrincipalInterfaceType()}"
         )
		def setContinuousAcquisition(nodemap):
			### set acquisition mode to continuous. mode is left as continuous for both continous feed and snapping images, so we do it here. code from PySpin example "Acquisition.py"
			node_acquisition_mode = PySpin.CEnumerationPtr(nodemap.GetNode('AcquisitionMode'))
			if not PySpin.IsAvailable(node_acquisition_mode) or not PySpin.IsWritable(node_acquisition_mode):
				print('Unable to set acquisition mode to continuous (enum retrieval). Aborting...')
				return False
			# Retrieve entry node from enumeration node
			node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName('Continuous')
			if not PySpin.IsAvailable(node_acquisition_mode_continuous) or not PySpin.IsReadable(node_acquisition_mode_continuous):
				print('Unable to set acquisition mode to continuous (entry retrieval). Aborting...')
				return False
			# Retrieve integer value from entry node
			acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue()
			# Set integer value from entry node as new value of enumeration node
			node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

			### set buffer handling mode to provide most recent images first, prevents the camera buffer from falling behind
			# options are NewestFirst, NewestOnly, OldestFirst, OldestFirstOverwrite
			# handling_mode = PySpin.CEnumerationPtr(nodemap.GetNode('StreamBufferHandlingMode'))
			# handling_mode_entry = handling_mode.GetEntryByName('NewestOnly')
			# handling_mode.SetIntValue(handling_mode_entry.GetValue())

			return True
Example #30
0
    def _get_flir_cam(self, cam_obj):
        # Takes data from Camera object to get a PySpin.Camera object
        # Retrieve singleton reference to system object
        system = PySpin.System.GetInstance()

        # Retrieve list of cameras from the system
        cam_list = system.GetCameras()

        for i, flir_cam in enumerate(cam_list):

            nodemap_tldevice = flir_cam.GetTLDeviceNodeMap()
            node_device_information = PySpin.CCategoryPtr(
                nodemap_tldevice.GetNode('DeviceInformation'))
            features = node_device_information.GetFeatures()

            for feature in features:

                node_feature = PySpin.CValuePtr(feature)
                if node_feature.GetName() == "DeviceID":

                    match_str = "FLIR cam {}".format(node_feature.ToString())
                    if match_str == cam_obj.link:
                        return flir_cam, cam_list, system