Esempio n. 1
0
    def _call_cfunc(cls, func_name, argtypes, restype, *args):
        """
        Extract function from vital library and call it with a VitalErrorHandle.

        This assumes that the C function takes an additional parameter than what
        is given to this function that is the error handle.

        :param func_name: C function name to pull from library
        :type func_name: str

        :param argtypes: Ctypes argument type array
        :type argtypes: list | tuple

        :param restype: Ctypes return type

        :param args: iterable of positional arguments to the C function
        :param args: tuple

        :return: Result of the c function call

        """
        # local import to prevent circular import
        from vital.util import VitalErrorHandle
        f = cls.VITAL_LIB[func_name]
        if argtypes:
            f.argtypes = list(argtypes) + [VitalErrorHandle.c_ptr_type()]
        f.restype = restype
        with VitalErrorHandle() as eh:
            return f(*(args + (eh,)))
Esempio n. 2
0
 def intrinsics(self):
     """
     :return: a reference to this camera's intrinsics object
     :rtype: CameraIntrinsics
     """
     cam_int = self.VITAL_LIB['vital_camera_intrinsics']
     cam_int.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
     cam_int.restype = CameraIntrinsics.c_ptr_type()
     with VitalErrorHandle() as eh:
         c_ptr = cam_int(self, eh)
     return CameraIntrinsics(from_cptr=c_ptr)
Esempio n. 3
0
 def rotation(self):
     """
     :return: a copy of this camera's rotation
     :rtype: Rotation
     """
     cam_rot = self.VITAL_LIB['vital_camera_rotation']
     cam_rot.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
     cam_rot.restype = Rotation.c_ptr_type()
     with VitalErrorHandle() as eh:
         c_ptr = cam_rot(self, eh)
     return Rotation(from_cptr=c_ptr)
Esempio n. 4
0
 def covariance(self):
     """
     :return: a copy of this camera's center covariance
     :rtype: Covariance
     """
     cam_covar = self.VITAL_LIB['vital_camera_center_covar']
     cam_covar.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
     cam_covar.restype = Covariance.c_ptr_type(3)
     with VitalErrorHandle() as eh:
         c_ptr = cam_covar(self, eh)
     return Covariance(3, from_cptr=c_ptr)
Esempio n. 5
0
 def translation(self):
     """
     :return: a copy of this camera's translation vector
     :rtype: EigenArray
     """
     cam_trans = self.VITAL_LIB['vital_camera_translation']
     cam_trans.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
     cam_trans.restype = EigenArray.c_ptr_type(3)
     with VitalErrorHandle() as eh:
         c_ptr = cam_trans(self, eh)
     return EigenArray(3, from_cptr=c_ptr)
Esempio n. 6
0
 def center(self):
     """
     :return: a copy of this camera's center coordinate.
     :rtype: EigenArray
     """
     cam_center = self.VITAL_LIB['vital_camera_center']
     cam_center.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
     cam_center.restype = EigenArray.c_ptr_type(3)
     with VitalErrorHandle() as eh:
         c_ptr = cam_center(self, eh)
     return EigenArray(3, from_cptr=c_ptr)
Esempio n. 7
0
    def __new__(cls, size=128, ctype=ctypes.c_double, from_cptr=None):
        """
        Create a descriptor instance

        :param size: Size of the descriptor (number of elements). Default of 128
            (arbitrary).
        :param ctype: Data type that this data is represented as under the hood.
        :param from_cptr: Existing Descriptor instance to wrap.
        """
        # noinspection PyProtectedMember
        type_char = ctype._type_

        if from_cptr is None:
            d_new = cls.VITAL_LIB['vital_descriptor_new_{}'.format(type_char)]
            d_new.argtypes = [ctypes.c_size_t, VitalErrorHandle.c_ptr_type()]
            d_new.restype = cls.c_ptr_type()
            with VitalErrorHandle() as eh:
                inst_ptr = d_new(size, eh)
        else:
            if not isinstance(from_cptr, cls.c_ptr_type()):
                raise ValueError("Invalid ``from_cptr`` value (given %s"
                                 % type(from_cptr))
            inst_ptr = from_cptr

        # Get the raw-data pointer from inst to wrap array around
        d_raw_data = cls.VITAL_LIB['vital_descriptor_get_{}_raw_data'
                                   .format(type_char)]
        d_raw_data.argtypes = [cls.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
        d_raw_data.restype = ctypes.POINTER(ctype)
        # TODO: We could recover from an exception here by parsing the type
        #       expected in the error message and changing the construction type
        with VitalErrorHandle() as eh:
            eh.set_exception_map({1: VitalDynamicCastException})
            data_ptr = d_raw_data(inst_ptr, eh)
        b = numpy.ctypeslib.as_array(data_ptr, (size,))

        dtype = numpy.dtype(ctype)
        obj = numpy.ndarray.__new__(cls, size, dtype, b)
        obj._inst_ptr = inst_ptr
        obj._owns_data = True  # This is the owning instance
        return obj
Esempio n. 8
0
    def as_matrix(self):
        """
        Convert camera into a new 3x4 homogeneous projection matrix.

        :return: new 3x4 homogeneous projection matrix
        :rtype: EigenArray
        """
        cam_asmat = self.VITAL_LIB['vital_camera_as_matrix']
        cam_asmat.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
        cam_asmat.restype = EigenArray.c_ptr_type(3, 4)
        with VitalErrorHandle() as eh:
            cptr = cam_asmat(self, eh)
        return EigenArray(3, 4, from_cptr=cptr)
Esempio n. 9
0
 def from_string(cls, s):
     """
     :param s: String camera representation. This must be in the same form
         that would be generated by this class' ``as_string`` method.
     :type s: str
     :return: New camera instance from a string sequence.
     :rtype: Camera
     """
     cam_from_str = cls.VITAL_LIB['vital_camera_new_from_string']
     cam_from_str.argtypes = [ctypes.c_char_p, VitalErrorHandle.c_ptr_type()]
     cam_from_str.restype = cls.c_ptr_type()
     with VitalErrorHandle() as eh:
         cptr = cam_from_str(s, eh)
     return Camera(from_cptr=cptr)
Esempio n. 10
0
    def tobytearray(self):
        """
        :return: a copy of the descriptor vector as a numpy.ndarray. Copied data
            will be of bytes regardless of stored data type.
        :rtype: vital.util.array_wrapping.CArrayWrapper
        """
        d_as_bytes = self.VITAL_LIB['vital_descriptor_as_bytes']
        d_as_bytes.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
        d_as_bytes.restype = ctypes.POINTER(ctypes.c_uint8)

        with VitalErrorHandle() as eh:
            cptr = d_as_bytes(self, eh)

        return CArrayWrapper(cptr, self.nbytes, ctypes.c_uint8, free_void_ptr)
Esempio n. 11
0
 def impl_name(self):
     """
     :return: String name for the current implementation, or None if this
         algorithm is not initialized to an implementation
     :rtype: str
     """
     if self._inst_ptr:
         algo_impl_name = self.VITAL_LIB.vital_algorithm_impl_name
         algo_impl_name.argtypes = [self.C_TYPE_PTR,
                                    VitalErrorHandle.C_TYPE_PTR]
         algo_impl_name.restype = self.MST_TYPE_PTR
         with VitalErrorHandle() as eh:
             s_ptr = algo_impl_name(self, eh)
             s = s_ptr.contents.str
             self.MST_FREE(s_ptr)
             return s
     else:
         return None
Esempio n. 12
0
 def __getitem__(self, p):
     """
     Get an element of the covariance matrix
     :param p: row, column index pair
     :return: Value at the specified index in if bounds
     :raises IndexError: Index out of bounds
     """
     r, c = p
     if not (0 <= r < self._N and 0 <= c < self._N):
         raise IndexError(p)
     c_get = self._func_map['get']
     c_get.argtypes = [
         self.C_TYPE_PTR, ctypes.c_uint, ctypes.c_uint,
         VitalErrorHandle.C_TYPE_PTR
     ]
     c_get.restype = self._ctype
     with VitalErrorHandle() as eh:
         return c_get(self, r, c, eh)
Esempio n. 13
0
    def convert(self, image_container):
        """
        :param image_container: The image container with image data to convert
        :type image_container: ImageContainer

        :return: A new ImageContainer with the converted underlying data
        :rtype: ImageContainer

        """
        ci_convert = self.VITAL_LIB.vital_algorithm_convert_image_convert
        ci_convert.argtypes = [
            self.C_TYPE_PTR, ImageContainer.C_TYPE_PTR,
            VitalErrorHandle.C_TYPE_PTR
        ]
        ci_convert.restype = ImageContainer.C_TYPE_PTR
        with VitalErrorHandle() as eh:
            return ImageContainer.from_c_pointer(
                ci_convert(self, image_container, eh))
Esempio n. 14
0
    def save(self, image_container, filepath):
        """
        Save an image to the specified path

        :param image_container: ImageContainer containing the image to save
        :type image_container: ImageContainer

        :param filepath: The path to save the image to
        :type filepath: str

        """
        iio_save = self.VITAL_LIB.vital_algorithm_image_io_save
        iio_save.argtypes = [
            self.C_TYPE_PTR, ctypes.c_char_p, ImageContainer.C_TYPE_PTR,
            VitalErrorHandle.C_TYPE_PTR
        ]
        with VitalErrorHandle() as eh:
            iio_save(self, filepath, image_container, eh)
Esempio n. 15
0
    def from_file(cls, filepath):
        """
        Create a new track set as read from the given filepath.
        :param filepath: Path to a file to a track set from
        :type filepath: str

        :return: New track set as read from the given file.
        :rtype: TrackSet

        """
        ts_new_from_file = cls.VITAL_LIB['vital_trackset_new_from_file']
        ts_new_from_file.argtypes = [
            ctypes.c_char_p, VitalErrorHandle.C_TYPE_PTR
        ]
        ts_new_from_file.restype = cls.C_TYPE_PTR

        with VitalErrorHandle() as eh:
            return TrackSet(from_cptr=ts_new_from_file(filepath, eh))
Esempio n. 16
0
    def __eq__(self, other):
        if isinstance(other, Rotation):
            if self._ctype != other._ctype:
                # raise ValueError("Cannot test equality of two rotations of "
                #                  "different data types (%s != %s)"
                #                  % (self._ctype, other._ctype))
                self._log.debug("Converting `other` from %s into %s.",
                                other._ctype, self._ctype)
                other = Rotation.from_quaternion(other.quaternion(),
                                                 self._ctype)

            r_eq = self._get_c_function(self._spec, "are_equal")
            r_eq.argtypes = [self.C_TYPE_PTR, other.C_TYPE_PTR,
                             VitalErrorHandle.C_TYPE_PTR]
            r_eq.restype = ctypes.c_bool
            with VitalErrorHandle() as eh:
                return r_eq(self, other, eh)
        return False
Esempio n. 17
0
    def project(self, point):
        """
        Project a 3D point into a new 2D image point (eigen array) via this
        camera model.

        :param point: 3D point to transform into the 2D image plane.
        :return: New 2D eigen array that is the transformed point.
        """
        point = EigenArray.from_iterable(point, target_shape=(3, 1))

        cam_project = self.VITAL_LIB['vital_camera_project']
        cam_project.argtypes = [self.c_ptr_type(),
                                EigenArray.c_ptr_type(3),
                                VitalErrorHandle.c_ptr_type()]
        cam_project.restype = EigenArray.c_ptr_type(2)
        with VitalErrorHandle() as eh:
            cptr = cam_project(self, point, eh)
        return EigenArray(2, from_cptr=cptr)
Esempio n. 18
0
    def load(self, filepath):
        """
        Load an image into a ImageContainer

        :param filepath: Path to the image to load
        :type filepath: str

        :return: New ImageContainer containing the loaded image
        :rtype: ImageContainer

        """
        iio_load = self.VITAL_LIB.vital_algorithm_image_io_load
        iio_load.argtypes = [
            self.C_TYPE_PTR, ctypes.c_char_p, VitalErrorHandle.C_TYPE_PTR
        ]
        iio_load.restype = ImageContainer.C_TYPE_PTR
        with VitalErrorHandle() as eh:
            ic_ptr = iio_load(self, filepath, eh)
        return ImageContainer.from_c_pointer(ic_ptr)
Esempio n. 19
0
    def as_string(self):
        """
        Convert the camera to a string representation

        :return: String representation of this camera
        :rtype: str
        """
        cam_tostr = self.VITAL_LIB['vital_camera_to_string']
        cam_tostr.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]

        cam_tostr.restype = ctypes.c_void_p
        with VitalErrorHandle() as eh:
            v_ptr = cam_tostr(self, eh)
        s = ctypes.c_char_p(v_ptr).value

        ptr_free = self.VITAL_LIB['vital_free_pointer']
        ptr_free.argtypes = [ctypes.c_void_p]
        ptr_free(v_ptr)

        return s
Esempio n. 20
0
    def check_config(self, cb):
        """
        Check the given configuration block for valid algorithm configuration

        :param cb: Configuration to check.
        :type cb: ConfigBlock

        :return: True if the given configuration block contains a valid
            configuration for this algorithm type and implementation.
        :rtype: bool

        """
        algo_ctc = self.VITAL_LIB['vital_algorithm_%s_check_type_config'
                                  % self.type_name()]
        algo_ctc.argtypes = [ctypes.c_char_p,
                             ConfigBlock.C_TYPE_PTR,
                             VitalErrorHandle.C_TYPE_PTR]
        algo_ctc.restype = ctypes.c_bool
        with VitalErrorHandle() as eh:
            return algo_ctc(self.name, cb, eh)
Esempio n. 21
0
    def write(self, filepath):
        """
        Output this configuration to the specified file path

        :raises VitalBaseException: Error occurred in writing configuration to
            the given file path.

        :param filepath: Output file path.

        """
        cb_write = self.VITAL_LIB.vital_config_block_file_write
        cb_write.argtypes = [self.C_TYPE_PTR, ctypes.c_char_p,
                             VitalErrorHandle.C_TYPE_PTR]
        with VitalErrorHandle() as eh:
            eh.set_exception_map({
                -1: VitalConfigBlockIoException,
                1: VitalConfigBlockIoFileWriteException
            })

            cb_write(self, filepath, eh)
Esempio n. 22
0
    def undistort_2d(self, dist_pt):
        """
        Unmap distorted normalized coordinates into normalized coordinates

        :param dist_pt: Distorted 2D coordinate to un-distort.

        :return: Normalized 2D image coordinate.

        """
        assert len(dist_pt) == 2, "Input sequence was not of length 2"
        f = self.VITAL_LIB['vital_camera_intrinsics_undistort_2d']
        f.argtypes = [self.C_TYPE_PTR,
                      EigenArray.c_ptr_type(2, 1, ctypes.c_double),
                      VitalErrorHandle.C_TYPE_PTR]
        f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double)
        p = EigenArray(2)
        p.T[:] = dist_pt
        with VitalErrorHandle() as eh:
            m_ptr = f(self, p, eh)
            return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True)
Esempio n. 23
0
    def _call_cfunc(cls, func_name, argtypes=(), args=(), restype=None,
                    exception_map=None):
        """
        Extract function from vital library and call it with a VitalErrorHandle.

        This assumes that the C function takes an additional parameter than what
        is given to this function that is the error handle instance.

        This function may raise an exception when the C function call's error
        handle picked something up. If an exception map is provided, it should
        be a dictionary mapping integer error codes to the python exception
        type that should be thrown.

        :param func_name: C function name to pull from library
        :type func_name: str

        :param argtypes: Ctypes argument type array
        :type argtypes: list | tuple

        :param args: sequence of positional arguments to the C function
        :type args: list | tuple

        :param restype: optional Ctypes return type

        :param exception_map: Return code to exception mapping to give to the
            error handler.
        :type exception_map: dict[int, BaseException | types.FunctionType]

        :return: Result of the c function call

        """
        # local to prevent circular import
        from vital.util import VitalErrorHandle
        f = cls.VITAL_LIB[func_name]
        if argtypes:
            f.argtypes = list(argtypes) + [VitalErrorHandle.c_ptr_type()]
        f.restype = restype
        with VitalErrorHandle() as eh:
            if exception_map:
                eh.set_exception_map(exception_map)
            return f(*(list(args) + [eh]))
Esempio n. 24
0
    def _new(self, init_scalar_or_matrix):
        """
        Construct a new instance, returning new instance opaque C pointer and
        initializing any other necessary object properties

        :returns: New C opaque structure pointer.

        """
        N = self._N
        c_type = self._ctype

        # Choose relevant constructor
        if init_scalar_or_matrix is None:
            self._log.debug("Initializing identity")
            c_new = self._func_map['new_identity']
            c_new.argtypes = [VitalErrorHandle.C_TYPE_PTR]
            c_new.restype = self.C_TYPE_PTR
            args = ()
        elif isinstance(init_scalar_or_matrix,
                        (collections.Iterable, numpy.ndarray)):
            self._log.debug("Initializing with matrix")
            # Should be a NxN square matrix
            mat = EigenArray.from_iterable(init_scalar_or_matrix, c_type,
                                           (N, N))
            c_new = self._func_map['new_matrix']
            c_new.argtypes = [mat.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
            args = (mat, )
        else:
            self._log.debug("Initializing with scalar")
            c_new = self._func_map['new_scalar']
            c_new.argtypes = [self._ctype, VitalErrorHandle.C_TYPE_PTR]
            args = (init_scalar_or_matrix, )

        c_new.restype = self.C_TYPE_PTR
        with VitalErrorHandle() as eh:
            c_args = args + (eh, )
            # self._log.debug("Construction args: %s", c_args)
            c_ptr = c_new(*c_args)
        if not bool(c_ptr):
            raise RuntimeError("C++ Construction failed (null pointer)")
        return c_ptr
Esempio n. 25
0
    def compose(self, other_rot):
        """
        Compose this rotation with another (multiply).

        This rotation is considered the left-hand operand and the given 
        rotation is considered the right-hand operand.

        Result rotation will have the same data type as this rotation.

        :param other_rot: Right-hand side Rotation instance
        :type other_rot: vital.types.Rotation

        :return: new rotation that is the composition of this rotation and the
            other
        :rtype: vital.types.Rotation

        :raises ValueError: Other is not a rotation.

        """
        if not isinstance(other_rot, Rotation):
            raise ValueError("Other operand must be another rotation instance"
                             "(given: %s)" % type(other_rot))
        if self._ctype != other_rot._ctype:
            # raise ValueError("Cannot compose (multiply) two rotations of "
            #                  "different data types (%s != %s)"
            #                  % (self._ctype, other_rot._ctype))
            # Create new rotation from the given, but with our data type
            self._log.debug(
                "Converting input rotation of type %s into "
                "compatible type %s", other_rot._ctype, self._ctype)
            other_rot = Rotation.from_quaternion(other_rot.quaternion(),
                                                 self._ctype)

        r_compose = self._get_c_function(self._spec, "compose")
        r_compose.argtypes = [
            self.C_TYPE_PTR, other_rot.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR
        ]
        r_compose.restype = self.C_TYPE_PTR
        with VitalErrorHandle() as eh:
            r_ptr = r_compose(self, other_rot, eh)
        return Rotation(self._ctype, r_ptr)
Esempio n. 26
0
    def at_eigen_base_index(self, row, col=0):
        """
        Get the value at the specified index in the base Eigen matrix.

        **Note:** *The base Eigen matrix may not be the same shape as the
        current instance as this might be a sliced view of the base matrix.*

        :param row: Row of the value
        :param col: Column of the value

        :return: Value at the specified index.

        """
        assert 0 <= row < self.shape[0], "Row out of range"
        assert 0 <= col < self.shape[1], "Col out of range"
        f = self.VITAL_LIB[self._func_map['get']]
        f.argtypes = [self.C_TYPE_PTR, c_ptrdiff_t, c_ptrdiff_t,
                      VitalErrorHandle.C_TYPE_PTR]
        f.restype = self._c_type
        with VitalErrorHandle() as eh:
            return f(self, row, col, eh)
Esempio n. 27
0
    def depth(self, point):
        """
        Compute the distance of the 3d point to the image plane.

        Points with negative depth are behind the camera.

        :param point: 3D point to find the depth of.

        :return: Depth value
        :rtype: float

        """
        point = EigenArray.from_iterable(point)

        cam_depth = self.VITAL_LIB['vital_camera_depth']
        cam_depth.argtypes = [self.c_ptr_type(),
                              EigenArray.c_ptr_type(3),
                              VitalErrorHandle.c_ptr_type()]
        cam_depth.restype = ctypes.c_double
        with VitalErrorHandle() as eh:
            return cam_depth(self, point, eh)
Esempio n. 28
0
 def yaw_pitch_roll(self):
     """
     :return: Convert to yaw, pitch, and roll (radians).
     :rtype: tuple of three floats
     """
     r2ypr = self._get_c_function(self._spec, "ypr")
     r2ypr.argtypes = [
         self.C_TYPE_PTR,
         ctypes.POINTER(self._ctype),  # yaw
         ctypes.POINTER(self._ctype),  # pitch
         ctypes.POINTER(self._ctype),  # roll
         VitalErrorHandle.C_TYPE_PTR
     ]
     # void return
     yaw = self._ctype()
     pitch = self._ctype()
     roll = self._ctype()
     with VitalErrorHandle() as eh:
         r2ypr(self, ctypes.byref(yaw), ctypes.byref(pitch),
               ctypes.byref(roll), eh)
     return yaw.value, pitch.value, roll.value
Esempio n. 29
0
    def track(self, prev_tracks, frame_num, image, mask=None):
        """
        Extend a previous set of tracks using the given image.

        An optional mask image may be provided, where positive valued regions
        indicate regions of the input image to consider for feature tracking.
        The mask image must be of the same dimensions as the input image, other
        wise an exception is raised.

        :param prev_tracks:
        :param frame_num:
        :param image:
        :param mask:
        :return:

        """
        tf_track_argtypes = [self.C_TYPE_PTR, TrackSet.C_TYPE_PTR,
                             ctypes.c_uint, ImageContainer.C_TYPE_PTR]
        tf_track_args = [self, prev_tracks, frame_num, image]
        tf_track_restype = TrackSet.C_TYPE_PTR

        if mask:
            tf_track = self.VITAL_LIB['vital_algorithm_track_features_'
                                      'track_with_mask']
            tf_track_argtypes.append(ImageContainer.C_TYPE_PTR)
            tf_track_args.append(mask)
        else:
            tf_track = self.VITAL_LIB['vital_algorithm_track_features_track']
        tf_track_argtypes.append(VitalErrorHandle.C_TYPE_PTR)

        tf_track.argtypes = tf_track_argtypes
        tf_track.restype = tf_track_restype

        with VitalErrorHandle() as eh:
            tf_track_args.append(eh)
            return TrackSet.from_c_pointer(
                tf_track(*tf_track_args)
            )
Esempio n. 30
0
    def _new(self, center, rotation, intrinsics):
        cam_new = self.VITAL_LIB['vital_camera_new']
        cam_new.argtypes = [EigenArray.c_ptr_type(3, 1, ctypes.c_double),
                            Rotation.c_ptr_type(ctypes.c_double),
                            CameraIntrinsics.c_ptr_type(),
                            VitalErrorHandle.c_ptr_type()]
        cam_new.restype = self.c_ptr_type()

        # Fill in parameter gaps
        if center is None:
            center = EigenArray(3)
            center[:] = 0
        else:
            center = EigenArray.from_iterable(center)

        if rotation is None:
            rotation = Rotation()

        if intrinsics is None:
            intrinsics = CameraIntrinsics()

        with VitalErrorHandle() as eh:
            return cam_new(center, rotation, intrinsics, eh)
Esempio n. 31
0
    def unmap_2d(self, pt):
        """
        Unmap actual image coordinates back into normalized image coordinates

        This function applies both application of the inverse calibration matrix
        and undistortion of the normalized coordinates

        :param pt: Actual image 2D point to un-map.

        :return: Un-mapped normalized image coordinate.

        """
        assert len(pt) == 2, "Input sequence was not of length 2"
        f = self.VITAL_LIB['vital_camera_intrinsics_unmap_2d']
        f.argtypes = [self.C_TYPE_PTR,
                      EigenArray.c_ptr_type(2, 1, ctypes.c_double),
                      VitalErrorHandle.C_TYPE_PTR]
        f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double)
        p = EigenArray(2)
        p.T[:] = pt
        with VitalErrorHandle() as eh:
            m_ptr = f(self, p, eh)
            return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True)
Esempio n. 32
0
    def map_3d(self, norm_hpt):
        """
        Map a 3D point in camera coordinates into actual image coordinates

        :param norm_hpt: Normalized coordinate to map to an image coordinate
            (3-element sequence)
        :type norm_hpt: collections.Sequence[float]

        :return: Mapped 2D image coordinate
        :rtype: EigenArray[float]

        """
        assert len(norm_hpt) == 3, "Input sequence was not of length 3"
        f = self.VITAL_LIB['vital_camera_intrinsics_map_3d']
        f.argtypes = [self.C_TYPE_PTR,
                      EigenArray.c_ptr_type(3, 1, ctypes.c_double),
                      VitalErrorHandle.C_TYPE_PTR]
        f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double)
        p = EigenArray(3)
        p.T[:] = norm_hpt
        with VitalErrorHandle() as eh:
            m_ptr = f(self, p, eh)
            return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True)
Esempio n. 33
0
 def _destroy(self):
     dos_del = self.VITAL_LIB.vital_detected_object_set_destroy
     dos_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         dos_del(self, eh)
Esempio n. 34
0
 def _destroy(self):
     bb_del = self.VITAL_LIB.vital_bounding_box_destroy
     bb_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         bb_del(self, eh)
Esempio n. 35
0
 def _destroy(self):
     ci_dtor = self.VITAL_LIB['vital_camera_intrinsics_destroy']
     ci_dtor.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         ci_dtor(self, eh)
Esempio n. 36
0
 def skew(self):
     f = self.VITAL_LIB['vital_camera_intrinsics_get_skew']
     f.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     f.restype = ctypes.c_double
     with VitalErrorHandle() as eh:
         return f(self, eh)
Esempio n. 37
0
 def _destroy(self):
     imgc_del = self.VITAL_LIB.vital_image_container_destroy
     imgc_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         imgc_del(self, eh)
Esempio n. 38
0
 def _destroy(self):
     if hasattr(self, '_owns_data') and self._owns_data:
         d_del = self.VITAL_LIB['vital_descriptor_destroy']
         d_del.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
         with VitalErrorHandle() as eh:
             d_del(self, eh)
Esempio n. 39
0
 def __len__(self):
     ts_size = self.VITAL_LIB['vital_trackset_size']
     ts_size.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     ts_size.restype = ctypes.c_size_t
     with VitalErrorHandle() as eh:
         return ts_size(self, eh)
Esempio n. 40
0
 def _destroy(self):
     ts_del = self.VITAL_LIB['vital_trackset_destroy']
     ts_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         ts_del(self, eh)
Esempio n. 41
0
 def _destroy(self):
     c_del = self._func_map['destroy']
     c_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         c_del(self, eh)
     self._inst_ptr = self.C_TYPE_PTR()
Esempio n. 42
0
 def _destroy(self):
     cm_del = self.VITAL_LIB.vital_camera_map_destroy
     cm_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         cm_del(self, eh)
Esempio n. 43
0
    def __new__(cls, size=128, ctype=ctypes.c_double, from_cptr=None):
        """
        Create a descriptor instance

        :param size: Size of the descriptor (number of elements). Default of 128
            (arbitrary).
        :param ctype: Data type that this data is represented as under the hood.
        :param from_cptr: Existing Descriptor instance to wrap.
        """
        if from_cptr is None:
            d_type = ctype
            # Record type format character for calling the appropriate C
            # function.
            # noinspection PyProtectedMember
            d_type_char = ctype._type_
            d_new = cls.VITAL_LIB['vital_descriptor_new_{}'.format(d_type_char)]
            d_new.argtypes = [ctypes.c_size_t, VitalErrorHandle.c_ptr_type()]
            d_new.restype = cls.c_ptr_type()
            with VitalErrorHandle() as eh:
                inst_ptr = d_new(size, eh)
        else:
            if not isinstance(from_cptr, cls.c_ptr_type()):
                raise ValueError("Invalid ``from_cptr`` value (given %s"
                                 % type(from_cptr))
            inst_ptr = from_cptr
            # Get type char from generic data type introspection function
            # ASSUMING typename from c++ is the same as ctypes _type_ values,
            #   which is at least currently true for float/double types, which
            #   is all that we care about / is implemented in C/C++.
            d_type = TYPE_NAME_MAP[cls._call_cfunc(
                'vital_descriptor_type_name',
                [cls.c_ptr_type()],
                [inst_ptr],
                ctypes.c_char_p
            )]
            # Record type format character for calling the appropriate C
            # function.
            # noinspection PyProtectedMember
            d_type_char = d_type._type_
            # Extract existing instance size information
            size = cls._call_cfunc(
                'vital_descriptor_size',
                [cls.c_ptr_type()],
                [inst_ptr],
                ctypes.c_size_t
            )

        # Get the raw-data pointer from inst to wrap array around
        d_raw_data = cls.VITAL_LIB['vital_descriptor_get_{}_raw_data'
                                   .format(d_type_char)]
        d_raw_data.argtypes = [cls.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
        d_raw_data.restype = ctypes.POINTER(d_type)
        # TODO: We could recover from an exception here by parsing the type
        #       expected in the error message and changing the construction type
        with VitalErrorHandle() as eh:
            eh.set_exception_map({1: VitalDynamicCastException})
            data_ptr = d_raw_data(inst_ptr, eh)
        b = numpy.ctypeslib.as_array(data_ptr, (size,))

        npy_type = numpy.dtype(d_type)
        obj = numpy.ndarray.__new__(cls, size, npy_type, b)
        obj._inst_ptr = inst_ptr
        obj._owns_data = True  # This is the owning instance
        return obj
Esempio n. 44
0
 def _destroy(self):
     """ destroy our C pointer """
     r_del = self._get_c_function(self._spec, 'destroy')
     r_del.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     with VitalErrorHandle() as eh:
         r_del(self, eh)
Esempio n. 45
0
 def angle(self):
     r2angle = self._get_c_function(self._spec, 'angle')
     r2angle.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR]
     r2angle.restype = self._ctype
     with VitalErrorHandle() as eh:
         return r2angle(self, eh)
Esempio n. 46
0
 def _destroy(self):
     if hasattr(self, '_owns_data') and self._owns_data:
         d_del = self.VITAL_LIB['vital_descriptor_destroy']
         d_del.argtypes = [self.c_ptr_type(), VitalErrorHandle.c_ptr_type()]
         with VitalErrorHandle() as eh:
             d_del(self, eh)