Python scipy.interpolate.NearestNDInterpolator() Examples

The following are 10 code examples of scipy.interpolate.NearestNDInterpolator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.interpolate , or try the search function .
Example #1
Source File: models.py    From rainymotion with MIT License 7 votes vote down vote up
def _interpolator(points, coord_source, coord_target, method="idw"):

    coord_source_i, coord_source_j = coord_source
    coord_target_i, coord_target_j = coord_target

    # reshape
    trg = np.vstack((coord_source_i.ravel(), coord_source_j.ravel())).T
    src = np.vstack((coord_target_i.ravel(), coord_target_j.ravel())).T

    if method == "nearest":
        interpolator = NearestNDInterpolator(src, points.ravel(),
                                             tree_options={"balanced_tree": False})
        points_interpolated = interpolator(trg)
    elif method == "linear":
        interpolator = LinearNDInterpolator(src, points.ravel(), fill_value=0)
        points_interpolated = interpolator(trg)
    elif method == "idw":
        interpolator = ipol.Idw(src, trg)
        points_interpolated = interpolator(points.ravel())

    # reshape output
    points_interpolated = points_interpolated.reshape(points.shape)

    return points_interpolated.astype(points.dtype) 
Example #2
Source File: imgproc.py    From graph_distillation with Apache License 2.0 6 votes vote down vote up
def inpaint(img, threshold=1):
  h, w = img.shape[:2]

  if len(img.shape) == 3:  # RGB
    mask = np.all(img == 0, axis=2).astype(np.uint8)
    img = cv2.inpaint(img, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)

  else:  # depth
    mask = np.where(img > threshold)
    xx, yy = np.meshgrid(np.arange(w), np.arange(h))
    xym = np.vstack((np.ravel(xx[mask]), np.ravel(yy[mask]))).T
    img = np.ravel(img[mask])
    interp = interpolate.NearestNDInterpolator(xym, img)
    img = interp(np.ravel(xx), np.ravel(yy)).reshape(xx.shape)

  return img 
Example #3
Source File: level.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def _build_vertex_values(self, items, area_func, value_func):
        """
        Interpolate vertice with known altitudes to get altitudes for the remaining ones.
        """
        vertex_values = np.empty(self.vertices.shape[:1], dtype=np.int32)
        if not vertex_values.size:
            return vertex_values
        vertex_value_mask = np.full(self.vertices.shape[:1], fill_value=False, dtype=np.bool)

        for item in items:
            faces = area_func(item).faces
            if not faces:
                continue
            i_vertices = np.unique(self.faces[np.array(tuple(chain(*faces)))].flatten())
            vertex_values[i_vertices] = value_func(item, i_vertices)
            vertex_value_mask[i_vertices] = True

        if np.any(vertex_value_mask) and not np.all(vertex_value_mask):
            interpolate = NearestNDInterpolator(self.vertices[vertex_value_mask],
                                                vertex_values[vertex_value_mask])
            vertex_values[np.logical_not(vertex_value_mask)] = interpolate(
                *np.transpose(self.vertices[np.logical_not(vertex_value_mask)])
            )

        return vertex_values 
Example #4
Source File: stars.py    From pyLIMA with GNU General Public License v3.0 6 votes vote down vote up
def define_claret_filter_tables(self):
        """
            Define the filter_claret table. For more details, see " Gravity and limb-darkening coefficients for
            the Kepler, CoRoT,
            Spitzer, uvby,   UBVRIJHK,
            and Sloan photometric systems"
            Claret, A. and Bloemen, S. 2011A&A...529A..75C.
        """
        all_filters = np.unique(self.claret_table[:,-1])
        self.filter_claret_table = {}

        for filter in all_filters:

            good_filter  = np.where(self.claret_table[:,-1] == filter)[0]

            subclaret = self.claret_table[good_filter,:-1].astype(float)

            grid_interpolation = si.NearestNDInterpolator(subclaret[:,:-1],subclaret[:,-1])

            self.filter_claret_table[filter] = grid_interpolation 
Example #5
Source File: nearest.py    From hcipy with MIT License 5 votes vote down vote up
def make_nearest_interpolator_unstructured(field, grid=None):
	'''Make a nearest interpolator for an unstructured grid.

	Parameters
	----------
	field : Field or array_like
		The field to interpolate.
	grid : Grid or None
		The grid of the field. If it is given, the grid of `field` is replaced by this grid.

	Returns
	-------
	Field generator
		The interpolator as a Field generator. The grid on which this field generator will be evaluated does
		not need to have any structure.
	'''
	if grid is None:
		grid = field.grid
	else:
		field = Field(field, grid)

	interp = NearestNDInterpolator(grid.points, field)

	def interpolator(evaluated_grid):
		res = interp(grid.points)
		return Field(res, evaluated_grid)

	return interpolator 
Example #6
Source File: test_ndgriddata.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_nearest_options():
    # smoke test that NearestNDInterpolator accept cKDTree options
    npts, nd = 4, 3
    x = np.arange(npts*nd).reshape((npts, nd))
    y = np.arange(npts)
    nndi = NearestNDInterpolator(x, y)

    opts = {'balanced_tree': False, 'compact_nodes': False}
    nndi_o = NearestNDInterpolator(x, y, tree_options=opts)
    assert_allclose(nndi(x), nndi_o(x), atol=1e-14) 
Example #7
Source File: processing_manager.py    From pydem with Apache License 2.0 5 votes vote down vote up
def build_interpolator(self, dem_proc):
        # Build an interpolator
        gc = dem_proc.elev.grid_coordinates
#       points = np.meshgrid(gc.x_axis, gc.y_axis)
#       points = np.column_stack([pts.ravel() for pts in points])
#       interp = spinterp.NearestNDInterpolator(points, dem_proc.data.ravel())
#       interp = spinterp.LinearNDInterpolator(points, np.ravel(dem_proc.data),
#                                               fill_value=np.nan)
        interp = spinterp.interpolate.RegularGridInterpolator(
            points=(gc.y_axis[::-1], gc.x_axis),
            values=dem_proc.data[::-1, :].astype(float),
            method='nearest', fill_value=np.nan, bounds_error=False)
        return interp 
Example #8
Source File: table_interpolator.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, filename, verbose=1):
        """
        Initialisation of class to load templates from a file and create the interpolation
        objects

        Parameters
        ----------
        filename: string
            Location of Template file
        verbose: int
            Verbosity level,
            0 = no logging
            1 = File + interpolation point information
            2 = Detailed description of interpolation points
        """
        self.verbose = verbose
        if self.verbose:
            print("Loading lookup tables from", filename)

        grid, bins, template = self.parse_fits_table(filename)
        x_bins, y_bins = bins

        self.interpolator = interpolate.LinearNDInterpolator(
            grid, template, fill_value=0
        )
        self.nearest_interpolator = interpolate.NearestNDInterpolator(grid, template)

        self.grid_interp = interpolate.RegularGridInterpolator(
            (x_bins, y_bins),
            np.zeros([x_bins.shape[0], y_bins.shape[0]]),
            method="linear",
            bounds_error=False,
            fill_value=0,
        ) 
Example #9
Source File: kitti_utils.py    From DeepV2D with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def lin_interp(shape, xyd):
    # taken from https://github.com/hunse/kitti
    m, n = shape
    ij, d = xyd[:, 1::-1], xyd[:, 2]
    f = LinearNDInterpolator(ij, d, fill_value=0)
    # f = NearestNDInterpolator(ij, d)
    J, I = np.meshgrid(np.arange(n), np.arange(m))
    IJ = np.vstack([I.flatten(), J.flatten()]).T
    disparity = f(IJ).reshape(shape)
    return disparity 
Example #10
Source File: annotation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def image_inpaint_pixels(img, valid_mask):
    assert img.shape == valid_mask.shape, \
        'image size %r and mask size %r should be equal' \
        % (img.shape, valid_mask.shape)
    coords = np.array(np.nonzero(valid_mask)).T
    values = img[valid_mask]
    it = interpolate.NearestNDInterpolator(coords, values)
    img_paint = it(list(np.ndindex(img.shape))).reshape(img.shape)
    return img_paint