Python cv2 模块,WARP_INVERSE_MAP 实例源码

我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用cv2.WARP_INVERSE_MAP

项目:kaggle-dstl    作者:lopuhin    | 项目源码 | 文件源码
def _aligned(im_ref, im, im_to_align=None, key=None):
    w, h = im.shape[:2]
    im_ref = cv2.resize(im_ref, (h, w), interpolation=cv2.INTER_CUBIC)
    im_ref = _preprocess_for_alignment(im_ref)
    if im_to_align is None:
        im_to_align = im
    im_to_align = _preprocess_for_alignment(im_to_align)
    assert im_ref.shape[:2] == im_to_align.shape[:2]
    try:
        cc, warp_matrix = _get_alignment(im_ref, im_to_align, key)
    except cv2.error as e:
        logger.info('Error getting alignment: {}'.format(e))
        return im, False
    else:
        im = cv2.warpAffine(im, warp_matrix, (h, w),
                            flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
        im[im == 0] = np.mean(im)
        return im, True
项目:convnet-for-geometric-matching    作者:hjweide    | 项目源码 | 文件源码
def plot_samples(Ia, Ib, M, mean, prefix=''):
    assert Ia.shape == Ib.shape, 'shapes must match'

    for i, _ in enumerate(Ia):
        crop = (Ia[i].transpose(1, 2, 0) + mean).astype(np.uint8)
        warp = (Ib[i].transpose(1, 2, 0) + mean).astype(np.uint8)

        theta = M[i].reshape((2, 3))
        trns = cv2.warpAffine(warp, theta, crop.shape[0:2],
                              flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP)
        out = np.hstack((crop, warp, trns))
        cv2.imwrite('%s_%d.png' % (prefix, i), out)


# This is slightly different from https://arxiv.org/abs/1703.05593,
# where the dataset is generated in advance and kept fixed.  Here,
# we generate a new transformation every time an image is sampled.
项目:FaceSwap    作者:Aravind-Suresh    | 项目源码 | 文件源码
def warp_image(img, tM, shape):
    out = np.zeros(shape, dtype=img.dtype)
    # cv2.warpAffine(img,
    #                tM[:2],
    #                (shape[1], shape[0]),
    #                dst=out,
    #                borderMode=cv2.BORDER_TRANSPARENT,
    #                flags=cv2.WARP_INVERSE_MAP)
    cv2.warpPerspective(img, tM, (shape[1], shape[0]), dst=out,
                        borderMode=cv2.BORDER_TRANSPARENT,
                        flags=cv2.WARP_INVERSE_MAP)
    return out

# TODO: Modify this method to get a better face contour mask
项目:FaceSwapper    作者:QuantumLiu    | 项目源码 | 文件源码
def warp_im(self,im, M, dshape):
        '''
        ????????
        '''
        output_im = np.zeros(dshape, dtype=im.dtype)
        cv2.warpAffine(im,
                       M[:2],
                       (dshape[1], dshape[0]),
                       dst=output_im,
                       borderMode=cv2.BORDER_TRANSPARENT,
                       flags=cv2.WARP_INVERSE_MAP)
        return output_im
项目:masks-and-hats    作者:leoneckert    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:masks-and-hats    作者:leoneckert    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.ones(dshape, dtype=im.dtype)*0
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:Kutils    作者:ishank26    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,M[:2],(dshape[1], dshape[0]),dst=output_im,borderMode=cv2.BORDER_TRANSPARENT,flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:Automatic_Group_Photography_Enhancement    作者:Yuliang-Zou    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = numpy.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:SynthText    作者:ankush-me    | 项目源码 | 文件源码
def warpHomography(self,src_mat,H,dst_size):
        dst_mat = cv2.warpPerspective(src_mat, H, dst_size,
                                      flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR)
        return dst_mat
项目:photo-a-day-aligner    作者:matthewearl    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = numpy.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def uncorrect(self, img):
        img = imread(img)
        s = img.shape[:2]
        return cv2.warpPerspective(img, self.homography, s[::-1],
                                   flags=cv2.INTER_CUBIC | cv2.WARP_INVERSE_MAP)
项目:mask-generator    作者:antiboredom    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:VerySharp    作者:wilecoyote2015    | 项目源码 | 文件源码
def processImage(self, index, data):
        # get the image
        raw_image = CommonFunctions.preprocessImage(data["image"], 
                                                   self.scale_factor,
                                                    interpolation=cv2.INTER_CUBIC)
        image_dimension = raw_image.shape

        # create output image as numpy array with upscaled image size
        processed_image = np.zeros(image_dimension, np.float32)

        # align all tiles
        for tile, transform_matrix in zip(self.tiles, data["transform_matrix"]):

            tile_slice_raw_image = np.s_[tile["y"][0]:tile["y"][1],
                                         tile["x"][0]:tile["x"][1]]
            raw_image_tile = raw_image[tile_slice_raw_image]
            tile_aligned = cv2.warpAffine(raw_image_tile,
                                          transform_matrix,
                                          (raw_image_tile.shape[1],raw_image_tile.shape[0]),
                                          flags=cv2.INTER_CUBIC + cv2.WARP_INVERSE_MAP);      

            # Insert the inner area of tile_aligned (so without margins) into
            # the appropriate area in the processed image
            min_x = tile["x"][0] + tile["margin_x"][0]
            min_y = tile["y"][0] + tile["margin_y"][0]
            max_x = tile["x"][1] - tile["margin_x"][1]
            max_y = tile["y"][1] - tile["margin_y"][1]
            tile_slice_processed_image = np.s_[min_y:max_y,
                                               min_x:max_x]

            max_y_aligned = tile_aligned.shape[0] - tile["margin_y"][1]
            max_x_aligned = tile_aligned.shape[1] - tile["margin_x"][1]
            tile_aligned_slice = np.s_[tile["margin_y"][0]:max_y_aligned,
                                       tile["margin_x"][0]:max_x_aligned]                                

            tile_aligned_without_margin = tile_aligned[tile_aligned_slice]

            processed_image[tile_slice_processed_image] = tile_aligned_without_margin

        return processed_image
项目:faceSwapPython    作者:arijitx    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = numpy.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:facemash-workshop    作者:leoneckert    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:facemash-workshop    作者:leoneckert    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = np.ones(dshape, dtype=im.dtype)*255
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:SwitchFace    作者:messcode    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    """
    Affine transformation with matrix M to dshape.
    """
    output_im = numpy.zeros(dshape, dtype=im.dtype)  # zero matrix
    cv2.warpAffine(im,
                   M[:2], # shape of M
                   (dshape[1], dshape[0]),
                   dst = output_im,
                   borderMode = cv2.BORDER_TRANSPARENT,
                   flags = cv2.WARP_INVERSE_MAP)
    return output_im
项目:deezer-album-face-swap    作者:xbenji    | 项目源码 | 文件源码
def warp_im(im, M, dshape):
    output_im = numpy.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im
项目:sea-lion-counter    作者:rdinse    | 项目源码 | 文件源码
def applyLinearTransformToImage(self, image, angle, shear_x, shear_y, scale, size_out):
    '''Apply the image transformation specified by three parameters.

    Time it takes warping a 256 x 256 RGB image with various affine warping functions:

    * 0.25ms cv2.warpImage, nearest interpolation
    * 0.26ms cv2.warpImage, linear interpolation
    * 5.11ms ndii.affine_transform, order=0
    * 5.93ms skimage.transform._warps_cy._warp_fast, linear interpolation

    Args:
      x: 2D numpy array, a single image.
      angle: Angle by which the image is rotated.
      shear_x: Shearing factor along the x-axis by which the image is sheared.
      shear_y: Shearing factor along the x-axis by which the image is sheared.
      scale: Scaling factor by which the image is scaled.
      channel_axis: Index of axis for channels in the input tensor.

    Returns:
      A tuple of transformed version of the input and the correction scale factor.

    '''
    # Positions of the image center before and after the transformation in
    # pixel coordinates.
    s_out = (size_out, size_out)
    c_in = .5 * np.asarray(image.shape[:2], dtype=np.float64).reshape((2, 1))
    c_out = .5 * np.asarray(s_out, dtype=np.float64).reshape((2, 1)) 

    angle = -angle
    M_rot_inv = np.asarray([[math.cos(angle), -math.sin(angle)], \
                            [math.sin(angle),  math.cos(angle)]])
    M_shear_inv = (1. / (shear_x * shear_y - 1.)) \
                * np.asarray([[-1., shear_x], [shear_y, -1.]])

    M_inv = np.dot(M_shear_inv, M_rot_inv)  # First undo rotation, then shear.

    M_inv /= scale

    offset = c_in - np.dot(M_inv, c_out)

    # cv2.warpAffine transform according to dst(p) = src(M_inv * p + offset).
    # No need to reverse the channels because the channels are interpolated
    # separately.
    warped = cv2.warpAffine(image, np.concatenate((M_inv, offset), axis=1), s_out, 
                            flags=cv2.INTER_LANCZOS4 | cv2.WARP_INVERSE_MAP)
                            # flags=cv2.INTER_CUBIC | cv2.WARP_INVERSE_MAP)

    return warped
项目:VerySharp    作者:wilecoyote2015    | 项目源码 | 文件源码
def calculateOpticalFlowsForDataset(self, image_reference, dataset):
        # optical flows will be stored here        
        list_optical_flows = []

        # add zero optical flow for the reference image which is at first position
        shape_image_reference = image_reference.shape
        shape_optical_flow = [shape_image_reference[0],
                              shape_image_reference[1],
                              2] 
        zero_optical_flow = np.zeros(shape_optical_flow, np.float32)
        list_optical_flows.append(zero_optical_flow)

        # iterate through the dataset and calculate the optical flow for each
        # except the first one
        num_images = dataset.getImageCount()
        for index in range(1, num_images):

            print ("calculating optical flow for image ", index)      

            # Get the image at the index
            data = dataset.getData(index)
            hdu_image = data["hdu_list"][self.extension].data
            image = CommonFunctions.preprocessHduImage(hdu_image, 
                                                       self.scale_factor)

            # @todo: here, do not use config but simply check if matrix is None
            # apply the transformation to the input image
            if self.config["Processing_Options"]["align_images"] == "True":
                # get the image dimension
                image_shape = image.shape

                # Transform the Image
                image = cv2.warpAffine(image,
                                       data["transform_matrix"],
                                       (image_shape[1],image_shape[0]),
                                       flags=cv2.INTER_CUBIC + cv2.WARP_INVERSE_MAP)       

            # calculate the optical flow (backwards for warping!)
            optical_flow = cv2.calcOpticalFlowFarneback(image_reference,
                                                        image,
                                                        None,
                                                        self.pyr_scale,
                                                        self.levels,
                                                        self.winsize,
                                                        self.iterations,
                                                        self.poly_n,
                                                        self.poly_sigma,
                                                        cv2.OPTFLOW_FARNEBACK_GAUSSIAN)

            # Write out optical flow images for user evaluation
            self.writeOpticalFlowImage(index, optical_flow)

            list_optical_flows.append(optical_flow)

        return list_optical_flows


    ## Average a list of optical flows
    #  @param list_optical_flows list object containing optical flows as numpy arrays
    #  @return averaged optical flow as numpy array
项目:GradLab    作者:Ajf4163    | 项目源码 | 文件源码
def translationalThermalReg(im1,im2):
    import cv2,numpy

    #get dimensions
    s1=im1.shape
    s2=im2.shape

    #check sizes agree as a sanity check for inputs

    if s1!=s2:
        raise TypeError('Array Inputs are of different sizes!')

    #Select translation model in CV
    warp_model = cv2.MOTION_AFFINE

    #Define 2x3 Warp Matrix
    warp_matrix = numpy.eye(2, 3, dtype=numpy.float32)

    #Number of iterations allowed to converge on solution
    num_it=10000

    #Terminal Threshold
    termTh = 1e-9

    #Define Stopping Criteria
    criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, num_it,  termTh)

    #Ensure images are of datatype float32 (for compatibility with transformation convergence)
    im1=im1.astype(numpy.float32)
    im2=im2.astype(numpy.float32)

    #Find Ideal Transform given input parameters
    (cc, warp_matrix) = cv2.findTransformECC(im1,im2,warp_matrix, warp_model, criteria)

    #Apply Transform
    aligned = cv2.warpAffine(im2, warp_matrix, (s1[1], s1[0]), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP);
    print('Calculated Affine Warp Matrix:')
    print(warp_matrix)

    return aligned, warp_matrix


#Test Harness for debugging and testing of functions