Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple, efficient bilinear interpolation of images in numpy and python

How do I implement bilinear interpolation for image data represented as a numpy array in python?

like image 283
Alex Flint Avatar asked Oct 04 '12 14:10

Alex Flint


People also ask

Which interpolation method is best for image?

BICUBIC INTERPOLATION Bicubic produces noticeably sharper images than the previous two methods, and is perhaps the ideal combination of processing time and output quality.

What is bilinear interpolation in image processing?

In computer vision and image processing, bilinear interpolation is used to resample images and textures. An algorithm is used to map a screen pixel location to a corresponding point on the texture map. A weighted average of the attributes (color, transparency, etc.)

What is interpolation of image in Python?

Given a random-sampled selection of pixels from an image, scipy. interpolate. griddata could be used to interpolate back to a representation of the original image. The code below does this, when fed the name of an image file on the command line.


1 Answers

I found many questions on this topic and many answers, though none were efficient for the common case that the data consists of samples on a grid (i.e. a rectangular image) and represented as a numpy array. This function can take lists as both x and y coordinates and will perform the lookups and summations without need for loops.

def bilinear_interpolate(im, x, y):
    x = np.asarray(x)
    y = np.asarray(y)

    x0 = np.floor(x).astype(int)
    x1 = x0 + 1
    y0 = np.floor(y).astype(int)
    y1 = y0 + 1

    x0 = np.clip(x0, 0, im.shape[1]-1);
    x1 = np.clip(x1, 0, im.shape[1]-1);
    y0 = np.clip(y0, 0, im.shape[0]-1);
    y1 = np.clip(y1, 0, im.shape[0]-1);

    Ia = im[ y0, x0 ]
    Ib = im[ y1, x0 ]
    Ic = im[ y0, x1 ]
    Id = im[ y1, x1 ]

    wa = (x1-x) * (y1-y)
    wb = (x1-x) * (y-y0)
    wc = (x-x0) * (y1-y)
    wd = (x-x0) * (y-y0)

    return wa*Ia + wb*Ib + wc*Ic + wd*Id
like image 141
Alex Flint Avatar answered Oct 23 '22 17:10

Alex Flint