Python cv2 模块,remap() 实例源码

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

项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def linearToPolar(img, center=None,
                  final_radius=None,
                  initial_radius=None,
                  phase_width=None,
                  interpolation=cv2.INTER_AREA, maps=None,
                  borderValue=0, borderMode=cv2.BORDER_REFLECT, **opts):
    '''
    map a 2d (x,y) Cartesian array to a polar (r, phi) array
    using opencv.remap
    '''
    if maps is None:
        mapY, mapX = linearToPolarMaps(img.shape[:2], center, final_radius,
                                       initial_radius, phase_width)
    else:
        mapY, mapX = maps

    o = {'interpolation': interpolation,
         'borderValue': borderValue,
         'borderMode': borderMode}
    o.update(opts)

    return cv2.remap(img, mapY, mapX, **o)
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def polarToLinear(img, shape=None, center=None, maps=None,
                  interpolation=cv2.INTER_AREA,
                  borderValue=0, borderMode=cv2.BORDER_REFLECT, **opts):
    '''
    map a 2d polar (r, phi) polar array to a  Cartesian (x,y) array
    using opencv.remap
    '''

    if maps is None:
        mapY, mapX = polarToLinearMaps(img.shape[:2], shape, center)
    else:
        mapY, mapX = maps

    o = {'interpolation': interpolation,
         'borderValue': borderValue,
         'borderMode': borderMode}
    o.update(opts)

    return cv2.remap(img, mapY, mapX, **o)
项目:tensorflow-litterbox    作者:rwightman    | 项目源码 | 文件源码
def distort_elastic_cv2(image, alpha=80, sigma=20, random_state=None):
    """Elastic deformation of images as per [Simard2003].
    """
    if random_state is None:
        random_state = np.random.RandomState(None)

    shape_size = image.shape[:2]

    # Downscaling the random grid and then upsizing post filter
    # improves performance. Approx 3x for scale of 4, diminishing returns after.
    grid_scale = 4
    alpha //= grid_scale  # Does scaling these make sense? seems to provide
    sigma //= grid_scale  # more similar end result when scaling grid used.
    grid_shape = (shape_size[0]//grid_scale, shape_size[1]//grid_scale)

    blur_size = int(4 * sigma) | 1
    rand_x = cv2.GaussianBlur(
        (random_state.rand(*grid_shape) * 2 - 1).astype(np.float32),
        ksize=(blur_size, blur_size), sigmaX=sigma) * alpha
    rand_y = cv2.GaussianBlur(
        (random_state.rand(*grid_shape) * 2 - 1).astype(np.float32),
        ksize=(blur_size, blur_size), sigmaX=sigma) * alpha
    if grid_scale > 1:
        rand_x = cv2.resize(rand_x, shape_size[::-1])
        rand_y = cv2.resize(rand_y, shape_size[::-1])

    grid_x, grid_y = np.meshgrid(np.arange(shape_size[1]), np.arange(shape_size[0]))
    grid_x = (grid_x + rand_x).astype(np.float32)
    grid_y = (grid_y + rand_y).astype(np.float32)

    distorted_img = cv2.remap(image, grid_x, grid_y,
        borderMode=cv2.BORDER_REFLECT_101, interpolation=cv2.INTER_LINEAR)

    return distorted_img
项目:kaggle_amazon_from_space    作者:N01Z3    | 项目源码 | 文件源码
def randomDistort1(img, distort_limit=0.35, shift_limit=0.25, u=0.5):
    if random.random() < u:
        height, width, channel = img.shape

        # debug
        # img = img.copy()
        # for x in range(0,width,10):
        #     cv2.line(img,(x,0),(x,height),(1,1,1),1)
        # for y in range(0,height,10):
        #     cv2.line(img,(0,y),(width,y),(1,1,1),1)

        k = random.uniform(-distort_limit, distort_limit) * 0.00001
        dx = random.uniform(-shift_limit, shift_limit) * width
        dy = random.uniform(-shift_limit, shift_limit) * height

        # map_x, map_y = cv2.initUndistortRectifyMap(intrinsics, dist_coeffs, None, None, (width,height),cv2.CV_32FC1)
        # https://stackoverflow.com/questions/6199636/formulas-for-barrel-pincushion-distortion
        # https://stackoverflow.com/questions/10364201/image-transformation-in-opencv
        x, y = np.mgrid[0:width:1, 0:height:1]
        x = x.astype(np.float32) - width / 2 - dx
        y = y.astype(np.float32) - height / 2 - dy
        theta = np.arctan2(y, x)
        d = (x * x + y * y) ** 0.5
        r = d * (1 + k * d * d)
        map_x = r * np.cos(theta) + width / 2 + dx
        map_y = r * np.sin(theta) + height / 2 + dy

        img = cv2.remap(img, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
    return img


# http://pythology.blogspot.sg/2014/03/interpolation-on-regular-distorted-grid.html
## grid distortion
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def warp_flow(img, flow):
    h, w = flow.shape[:2]
    flow = -flow
    flow[:,:,0] += np.arange(w)
    flow[:,:,1] += np.arange(h)[:,np.newaxis]
    res = cv2.remap(img, flow, None, cv2.INTER_LINEAR)
    return res
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def rectify(self, l, r): 
        """
        Rectify frames passed as (left, right) 
        Remapping is done with nearest neighbor for speed.
        """
        return [cv2.remap(l, self.undistortion_map[cidx], self.rectification_map[cidx], cv2.INTER_NEAREST)
                for cidx in range(len(self.cams))]
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def remap(self, src):
        """
        :param src: source image
        :type src: :class:`cvMat`

        Apply the post-calibration undistortion to the source image
        """
        return cv2.remap(src, self.mapx, self.mapy, cv2.INTER_LINEAR)
项目:watchGo    作者:daniel-bandstra    | 项目源码 | 文件源码
def readImage():
    # read image from cap, remapping it if we have mapx, mapy
    # assumes camera is already open
    retval, img = cap.read()
    if mapx is not None and mapy is not None:
        return cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)
    else:
        return img

# finding and watching a go board

# open the cascade classifiers:
项目:cvcalib    作者:Algomorph    | 项目源码 | 文件源码
def undistort_stereo(stereo_rig, test_im_left, test_im_right, size_factor):
    im_size = test_im_left.shape
    map1x, map1y, map2x, map2y = compute_stereo_rectification_maps(stereo_rig, im_size, size_factor)
    rect_left = cv2.remap(test_im_left, map1x, map1y, cv2.INTER_LINEAR)
    rect_right = cv2.remap(test_im_right, map2x, map2y, cv2.INTER_LINEAR)
    return rect_left, rect_right
项目:cvcalib    作者:Algomorph    | 项目源码 | 文件源码
def rectify_image(self, image):
        return remap(image, self.map_x, self.map_y, INTER_LINEAR)
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
    '''
    remap an image using velocity field
    '''
    ny,nx = u.shape
    sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
    sx += u*t
    sy += v*t
    return cv2.remap(img.astype(np.float32), 
                    (sx).astype(np.float32),
                    (sy).astype(np.float32), interpolation)
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def correct(self, image, keepSize=False, borderValue=0):
        '''
        remove lens distortion from given image
        '''
        image = imread(image)
        (h, w) = image.shape[:2]
        mapx, mapy = self.getUndistortRectifyMap(w, h)
        self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                             borderMode=cv2.BORDER_CONSTANT,
                             borderValue=borderValue
                             )
        if not keepSize:
            xx, yy, ww, hh = self.roi
            self.img = self.img[yy: yy + hh, xx: xx + ww]
        return self.img
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def distortImage(self, image):
        '''
        opposite of 'correct'
        '''
        image = imread(image)
        (imgHeight, imgWidth) = image.shape[:2]
        mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight)
        return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                         borderValue=(0, 0, 0))
项目:page_dewarp    作者:mzucker    | 项目源码 | 文件源码
def remap_image(name, img, small, page_dims, params):

    height = 0.5 * page_dims[1] * OUTPUT_ZOOM * img.shape[0]
    height = round_nearest_multiple(height, REMAP_DECIMATE)

    width = round_nearest_multiple(height * page_dims[0] / page_dims[1],
                                   REMAP_DECIMATE)

    print '  output will be {}x{}'.format(width, height)

    height_small = height / REMAP_DECIMATE
    width_small = width / REMAP_DECIMATE

    page_x_range = np.linspace(0, page_dims[0], width_small)
    page_y_range = np.linspace(0, page_dims[1], height_small)

    page_x_coords, page_y_coords = np.meshgrid(page_x_range, page_y_range)

    page_xy_coords = np.hstack((page_x_coords.flatten().reshape((-1, 1)),
                                page_y_coords.flatten().reshape((-1, 1))))

    page_xy_coords = page_xy_coords.astype(np.float32)

    image_points = project_xy(page_xy_coords, params)
    image_points = norm2pix(img.shape, image_points, False)

    image_x_coords = image_points[:, 0, 0].reshape(page_x_coords.shape)
    image_y_coords = image_points[:, 0, 1].reshape(page_y_coords.shape)

    image_x_coords = cv2.resize(image_x_coords, (width, height),
                                interpolation=cv2.INTER_CUBIC)

    image_y_coords = cv2.resize(image_y_coords, (width, height),
                                interpolation=cv2.INTER_CUBIC)

    img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    remapped = cv2.remap(img_gray, image_x_coords, image_y_coords,
                         cv2.INTER_CUBIC,
                         None, cv2.BORDER_REPLICATE)

    thresh = cv2.adaptiveThreshold(remapped, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                   cv2.THRESH_BINARY, ADAPTIVE_WINSZ, 25)

    pil_image = Image.fromarray(thresh)
    pil_image = pil_image.convert('1')

    threshfile = name + '_thresh.png'
    pil_image.save(threshfile, dpi=(OUTPUT_DPI, OUTPUT_DPI))

    if DEBUG_LEVEL >= 1:
        height = small.shape[0]
        width = int(round(height * float(thresh.shape[1])/thresh.shape[0]))
        display = cv2.resize(thresh, (width, height),
                             interpolation=cv2.INTER_AREA)
        debug_show(name, 6, 'output', display)

    return threshfile
项目:AutoFan    作者:hgmeyer    | 项目源码 | 文件源码
def run(self):
        # Clear events
        self._exit.clear()

        # While exit event is not set...
        while not self._exit.is_set() or not self._pause_event.is_set():
            # ...clear new frame event
            self.newframe_event.clear()

            # ... read a frame from the camera
            frame = self._cam.read()[1]

            # ...convert camera image to grayscale
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # ...remap image into shared memory
            self._currentframe[:] = cv2.remap(frame, self._mapx, self._mapy, cv2.INTER_LINEAR).copy()

            if self._visualize:
                cv2.imshow('Unwarped image', self._currentframe)
                cv2.waitKey(1)

            if self._debug:
                print str(1 / (time.time() - self._oldtime)) + " frames/sec"
                self._oldtime = time.time()

            # Set new frame event
            self.newframe_event.set()

        # If exit event set...
        if self._exit_event.is_set():
            # ...release camera
            self._cam.release()
            # ...close windows
            cv2.destroyAllWindows()
项目:Smart-Car    作者:jimchenhub    | 项目源码 | 文件源码
def getDisparity(stereo, img1, img2, mapx1, mapy1, mapx2, mapy2):
    dst1 = cv2.remap(img1, mapx1, mapy1, cv2.INTER_LINEAR)
    dst2 = cv2.remap(img2, mapx2, mapy2, cv2.INTER_LINEAR)
    gray1 = cv2.cvtColor(dst1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(dst2, cv2.COLOR_BGR2GRAY)
    disparity = stereo.compute(gray1, gray2)/16
    # disparity = cv2.medianBlur(disparity, 5)
    return disparity
项目:Beagle360Camera    作者:AlekMabry    | 项目源码 | 文件源码
def unwarp(img,xmap,ymap):
    output = cv2.remap(img,xmap,ymap,cv2.INTER_LINEAR)
    return output
项目:pc-drone    作者:perrytsao    | 项目源码 | 文件源码
def undistort_crop(orig_img):
    #cv2.remap(src, map1, map2, interpolation[, dst[, borderMode[, borderValue]]]) -> dst   
    dst = cv2.remap(orig_img, map1, map2, cv2.INTER_LINEAR)
    x,y,w,h = roi
    crop_frame = dst[y:y+h, x:x+w]    
    return crop_frame
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def interp_lin(I, xn, yn, compute_derivs=True):
    """ Perform linear interpolation of I.

    I is evaluated at xn, yn.

    Returns
    -------
    I_warped : array_like
        Warped image
    dI_warped_dx : array_like
        Derivative of warped image in x direction
    dI_warped_dy : array_like
        Derivative of warped image in y direction
    """

    I_warped = cv2.remap(I.astype('float32'),
                         xn.astype('float32'),
                         yn.astype('float32'),
                         borderMode=cv2.BORDER_REPLICATE,
                         interpolation=cv2.INTER_CUBIC)

    if compute_derivs:
        if True:
            dI_dy, dI_dx = np.gradient(I)[:2]
            dI_warped_dy = cv2.remap(dI_dy.astype('float32'),
                                xn.astype('float32'),
                                yn.astype('float32'),
                                borderMode=cv2.BORDER_REPLICATE,
                                interpolation=cv2.INTER_CUBIC)

            dI_warped_dx = cv2.remap(dI_dx.astype('float32'),
                                xn.astype('float32'),
                                yn.astype('float32'),
                                borderMode=cv2.BORDER_REPLICATE,
                                interpolation=cv2.INTER_CUBIC)
        else:
            dI_warped_dy, dI_warped_dx = np.gradient(I_warped)[:2]

        return I_warped, dI_warped_dx, dI_warped_dy

    # If we don't want to compute the derivatives
    return I_warped
项目:kaggle_amazon_from_space    作者:N01Z3    | 项目源码 | 文件源码
def randomDistort2(img, num_steps=10, distort_limit=0.2, u=0.5):
    if random.random() < u:
        height, width, channel = img.shape

        x_step = width // num_steps
        xx = np.zeros(width, np.float32)
        prev = 0
        for x in range(0, width, x_step):
            start = x
            end = x + x_step
            if end > width:
                end = width
                cur = width
            else:
                cur = prev + x_step * (1 + random.uniform(-distort_limit, distort_limit))

            xx[start:end] = np.linspace(prev, cur, end - start)
            prev = cur

        y_step = height // num_steps
        yy = np.zeros(height, np.float32)
        prev = 0
        for y in range(0, height, y_step):
            start = y
            end = y + y_step
            if end > width:
                end = height
                cur = height
            else:
                cur = prev + y_step * (1 + random.uniform(-distort_limit, distort_limit))

            yy[start:end] = np.linspace(prev, cur, end - start)
            prev = cur

        map_x, map_y = np.meshgrid(xx, yy)
        map_x = map_x.astype(np.float32)
        map_y = map_y.astype(np.float32)
        img = cv2.remap(img, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
    return img


## blur sharpen, etc