當前位置: 首頁>>代碼示例>>Python>>正文


Python cv2.transform方法代碼示例

本文整理匯總了Python中cv2.transform方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.transform方法的具體用法?Python cv2.transform怎麽用?Python cv2.transform使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cv2的用法示例。


在下文中一共展示了cv2.transform方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _adjust_affine_matrix

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def _adjust_affine_matrix(self, mask_size, affine_matrix):
        """ Adjust the affine matrix for the mask's storage size

        Parameters
        ----------
        mask_size: int
            The original size of the mask.
        affine_matrix: numpy.ndarray
            The affine matrix to transform the mask at original size to the parent frame.

        Returns
        -------
        affine_matrix: numpy,ndarray
            The affine matrix adjusted for the mask at its stored dimensions.
        """
        zoom = self.stored_size / mask_size
        zoom_mat = np.array([[zoom, 0, 0.], [0, zoom, 0.]])
        adjust_mat = np.dot(zoom_mat, np.concatenate((affine_matrix, np.array([[0., 0., 1.]]))))
        logger.trace("storage_size: %s, mask_size: %s, zoom: %s, original matrix: %s, "
                     "adjusted_matrix: %s", self.stored_size, mask_size, zoom, affine_matrix.shape,
                     adjust_mat.shape)
        return adjust_mat 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:24,代碼來源:faces_detect.py

示例2: keypoint_rotate

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def keypoint_rotate(keypoint, angle, rows, cols, **params):
    """Rotate a keypoint by angle.

    Args:
        keypoint (tuple): A keypoint `(x, y, angle, scale)`.
        angle (float): Rotation angle.
        rows (int): Image height.
        cols (int): Image width.

    Returns:
        tuple: A keypoint `(x, y, angle, scale)`.

    """
    matrix = cv2.getRotationMatrix2D(((cols - 1) * 0.5, (rows - 1) * 0.5), angle, 1.0)
    x, y, a, s = keypoint[:4]
    x, y = cv2.transform(np.array([[[x, y]]]), matrix).squeeze()
    return x, y, a + math.radians(angle), s 
開發者ID:albumentations-team,項目名稱:albumentations,代碼行數:19,代碼來源:functional.py

示例3: persTransform

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def persTransform(pts, H):
    """Transforms a list of points, `pts`,
    using the perspective transform `H`."""
    src = np.zeros((len(pts), 1, 2))
    src[:, 0] = pts
    dst = cv2.perspectiveTransform(src, H)
    return np.array(dst[:, 0, :], dtype='float32') 
開發者ID:mathandy,項目名稱:python-opencv-rectangle-tracker,代碼行數:9,代碼來源:rectangle_tracker.py

示例4: affTransform

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def affTransform(pts, A):
    """Transforms a list of points, `pts`,
    using the affine transform `A`."""
    src = np.zeros((len(pts), 1, 2))
    src[:, 0] = pts
    dst = cv2.transform(src, A)
    return np.array(dst[:, 0, :], dtype='float32') 
開發者ID:mathandy,項目名稱:python-opencv-rectangle-tracker,代碼行數:9,代碼來源:rectangle_tracker.py

示例5: sepia

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def sepia(img):
    kernel = np.float32([
        [0.272, 0.534, 0.131],
        [0.349, 0.686, 0.168],
        [0.393, 0.769, 0.189]])
    return cv2.transform(img, kernel) 
開發者ID:andreaschiavinato,項目名稱:python_grabber,代碼行數:8,代碼來源:image_process.py

示例6: extreme_corners

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def extreme_corners(frame, transforms):
    """Calculate max drift of each frame corner caused by stabilizing transforms

    :param frame: frame from video being stabilized
    :param transforms: VidStab transforms attribute
    :return: dictionary of most extreme x and y values caused by transformations
    """
    h, w = frame.shape[:2]
    frame_corners = np.array([[0, 0],  # top left
                              [0, h - 1],  # bottom left
                              [w - 1, 0],  # top right
                              [w - 1, h - 1]],  # bottom right
                             dtype='float32')
    frame_corners = np.array([frame_corners])

    min_x = min_y = max_x = max_y = 0
    for i in range(transforms.shape[0]):
        transform = transforms[i, :]
        transform_mat = vidstab_utils.build_transformation_matrix(transform)
        transformed_frame_corners = cv2.transform(frame_corners, transform_mat)

        delta_corners = transformed_frame_corners - frame_corners

        delta_y_corners = delta_corners[0][:, 1].tolist()
        delta_x_corners = delta_corners[0][:, 0].tolist()
        min_x = min([min_x] + delta_x_corners)
        min_y = min([min_y] + delta_y_corners)
        max_x = max([max_x] + delta_x_corners)
        max_y = max([max_y] + delta_y_corners)

    return {'min_x': min_x, 'min_y': min_y, 'max_x': max_x, 'max_y': max_y} 
開發者ID:AdamSpannbauer,項目名稱:python_video_stab,代碼行數:33,代碼來源:auto_border_utils.py

示例7: generateImage

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def generateImage(self):
        width = self._shape[0]
        height = self._shape[1]
        eyePoint = [(0.34 * width, height / 2.2), (0.66 * width, height / 2.2)]
        boundPoint = [(0, 0), (width / 2.0, 0), (width - 1, 0), (width - 1, height / 2.0), (width - 1, height - 1),
                      (width / 2.0, height - 1), (0, height - 1), (0, height / 2.0)]
        pointsAvg = np.array([(0, 0)] * (len(self._pointsArray[0]) + len(boundPoint)), np.float32)
        numImages = len(self._imageList)
        pointsNorm = []
        imagesNorm = []
        for point, image in zip(self._pointsArray, self._imageList):
            eyePointSrc = [point[self._keyPoint[0]], point[self._keyPoint[1]]]
            transform = AverageFace.similarityTransform(eyePointSrc, eyePoint)
            img = cv2.warpAffine(image, transform, (width, height))
            points = np.reshape(point, [len(self._pointsArray[0]), 1, 2])
            points = np.reshape(cv2.transform(points, transform), [len(self._pointsArray[0]), 2])
            points = np.append(points, boundPoint, 0)
            pointsAvg = pointsAvg + points / numImages
            pointsNorm.append(points)
            imagesNorm.append(img)
        rect = (0, 0, width, height)
        triangleList = AverageFace.calculateDelaunayTriangles(rect, pointsAvg)
        output = np.zeros((width, height, 3), dtype=np.float32)
        for i in range(len(imagesNorm)):
            img = np.zeros([width, height, 3], dtype=np.float32)
            for j in range(len(triangleList)):
                tin = []
                tout = []
                for k in range(3):
                    pIn = pointsNorm[i][triangleList[j][k]]
                    pIn = AverageFace.constrainPoint(pIn, width, height)
                    pOut = pointsAvg[triangleList[j][k]]
                    pOut = AverageFace.constrainPoint(pOut, width, height)
                    tin.append(pIn)
                    tout.append(pOut)
                AverageFace.warpTriangle(imagesNorm[i], img, tin, tout)
            output = output + img
        self._output = output / len(imagesNorm) 
開發者ID:yhswjtuILMARE,項目名稱:Machine-Learning-Study-Notes,代碼行數:40,代碼來源:AverageFace.py

示例8: add_mask

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def add_mask(self, name, mask, affine_matrix, interpolator, storage_size=128):
        """ Add a :class:`Mask` to this detected face

        The mask should be the original output from  :mod:`plugins.extract.mask`
        If a mask with this name already exists it will be overwritten by the given
        mask.

        Parameters
        ----------
        name: str
            The name of the mask as defined by the :attr:`plugins.extract.mask._base.name`
            parameter.
        mask: numpy.ndarray
            The mask that is to be added as output from :mod:`plugins.extract.mask`
            It should be in the range 0.0 - 1.0 ideally with a ``dtype`` of ``float32``
        affine_matrix: numpy.ndarray
            The transformation matrix required to transform the mask to the original frame.
        interpolator, int:
            The CV2 interpolator required to transform this mask to it's original frame.
        storage_size, int (optional):
            The size the mask is to be stored at. Default: 128
        """
        logger.trace("name: '%s', mask shape: %s, affine_matrix: %s, interpolator: %s)",
                     name, mask.shape, affine_matrix, interpolator)
        fsmask = Mask(storage_size=storage_size)
        fsmask.add(mask, affine_matrix, interpolator)
        self.mask[name] = fsmask 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:29,代碼來源:faces_detect.py

示例9: load_reference_face

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def load_reference_face(self, image, size=64, coverage_ratio=0.625, dtype=None):
        """ Align a face in the correct dimensions for reference against the output from a model.

        Parameters
        ----------
        image: numpy.ndarray
            The image that contains the face to be aligned
        size: int
            The size of the face in pixels to be fed into the model
        coverage_ratio: float, optional
            the ratio of the extracted image that was used for training. Default: `0.625`
        dtype: str, optional
            Optionally set a ``dtype`` for the final face to be formatted in. Default: ``None``

        Notes
        -----
        This method must be executed to get access to the following `properties`:
            - :func:`reference_face`
            - :func:`reference_landmarks`
            - :func:`reference_matrix`
            - :func:`reference_interpolators`
        """
        logger.trace("Loading reference face: (size: %s, coverage_ratio: %s, dtype: %s)",
                     size, coverage_ratio, dtype)

        self.reference["size"] = size
        self.reference["padding"] = self._padding_from_coverage(size, coverage_ratio)
        self.reference["matrix"] = get_align_mat(self)

        face = AlignerExtract().transform(image,
                                          self.reference["matrix"],
                                          size,
                                          self.reference["padding"])
        self.reference["face"] = face if dtype is None else face.astype(dtype)

        logger.trace("Loaded reference face. (face_shape: %s, matrix: %s)",
                     self.reference_face.shape, self.reference_matrix) 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:39,代碼來源:faces_detect.py

示例10: original_roi

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def original_roi(self):
        """ :class: `numpy.ndarray`: The original region of interest of the mask in the
        source frame. """
        points = np.array([[0, 0],
                           [0, self.stored_size - 1],
                           [self.stored_size - 1, self.stored_size - 1],
                           [self.stored_size - 1, 0]], np.int32).reshape((-1, 1, 2))
        matrix = cv2.invertAffineTransform(self._affine_matrix)
        roi = cv2.transform(points, matrix).reshape((4, 2))
        logger.trace("Returning: %s", roi)
        return roi 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:13,代碼來源:faces_detect.py

示例11: extract

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def extract(self, image, face, size):
        """ Extract a face from an image """
        logger.trace("size: %s", size)
        padding = int(size * 0.1875)
        alignment = get_align_mat(face)
        extracted = self.transform(image, alignment, size, padding)
        logger.trace("Returning face and alignment matrix: (alignment_matrix: %s)", alignment)
        return extracted, alignment 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:10,代碼來源:aligner.py

示例12: transform

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def transform(self, image, mat, size, padding=0):
        """ Transform Image """
        logger.trace("matrix: %s, size: %s. padding: %s", mat, size, padding)
        matrix = self.transform_matrix(mat, size, padding)
        interpolators = get_matrix_scaling(matrix)
        retval = cv2.warpAffine(image, matrix, (size, size), flags=interpolators[0])
        return retval 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:9,代碼來源:aligner.py

示例13: transform_points

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def transform_points(self, points, mat, size, padding=0):
        """ Transform points along matrix """
        logger.trace("points: %s, matrix: %s, size: %s. padding: %s", points, mat, size, padding)
        matrix = self.transform_matrix(mat, size, padding)
        points = np.expand_dims(points, axis=1)
        points = cv2.transform(points, matrix, points.shape)
        retval = np.squeeze(points)
        logger.trace("Returning: %s", retval)
        return retval 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:11,代碼來源:aligner.py

示例14: get_original_roi

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def get_original_roi(self, mat, size, padding=0):
        """ Return the square aligned box location on the original image """
        logger.trace("matrix: %s, size: %s. padding: %s", mat, size, padding)
        matrix = self.transform_matrix(mat, size, padding)
        points = np.array([[0, 0], [0, size - 1], [size - 1, size - 1], [size - 1, 0]], np.int32)
        points = points.reshape((-1, 1, 2))
        matrix = cv2.invertAffineTransform(matrix)
        logger.trace("Returning: (points: %s, matrix: %s", points, matrix)
        return cv2.transform(points, matrix) 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:11,代碼來源:aligner.py

示例15: _rotate_face

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import transform [as 別名]
def _rotate_face(face, rotation_matrix):
        """ Rotates the detection bounding box around the given rotation matrix.

        Parameters
        ----------
        face: :class:`DetectedFace`
            A :class:`DetectedFace` containing the `x`, `w`, `y`, `h` detection bounding box
            points.
        rotation_matrix: numpy.ndarray
            The rotation matrix to rotate the given object by.

        Returns
        -------
        :class:`DetectedFace`
            The same class with the detection bounding box points rotated by the given matrix.
        """
        logger.trace("Rotating face: (face: %s, rotation_matrix: %s)", face, rotation_matrix)
        bounding_box = [[face.left, face.top],
                        [face.right, face.top],
                        [face.right, face.bottom],
                        [face.left, face.bottom]]
        rotation_matrix = cv2.invertAffineTransform(rotation_matrix)

        points = np.array(bounding_box, "int32")
        points = np.expand_dims(points, axis=0)
        transformed = cv2.transform(points, rotation_matrix).astype("int32")
        rotated = transformed.squeeze()

        # Bounding box should follow x, y planes, so get min/max for non-90 degree rotations
        pt_x = min([pnt[0] for pnt in rotated])
        pt_y = min([pnt[1] for pnt in rotated])
        pt_x1 = max([pnt[0] for pnt in rotated])
        pt_y1 = max([pnt[1] for pnt in rotated])
        width = pt_x1 - pt_x
        height = pt_y1 - pt_y

        face.x = int(pt_x)
        face.y = int(pt_y)
        face.w = int(width)
        face.h = int(height)
        return face 
開發者ID:deepfakes,項目名稱:faceswap,代碼行數:43,代碼來源:_base.py


注:本文中的cv2.transform方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。