Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do bilinear interpolation for PIL Image in python?

I have read an image in python using Image module and converted it into a numpy array as follows...

       im=Image.open(infile)

       imdata = scipy.misc.fromimage(im)

After processing, what I get are not the integer coordinates but the real values. It is important to note that it is an rgb image. I want to get the color value as a bilinearly interpolated value. There is a method in image

     im.getPixel(x,y)

I am not sure that if we can give the real values as coordinates.

If we do it in numpy array, we can do bilinear interpolation but it will be separate for every channel if I am correct???

Thanks

like image 627
Shan Avatar asked Oct 20 '25 11:10

Shan


1 Answers

You are correct that getPixel will only accept integer coordinates.

You can do your own linear interpolation if you don't mind it being slow:

def lerp(a, b, coord):
    if isinstance(a, tuple):
        return tuple([lerp(c, d, coord) for c,d in zip(a,b)])
    ratio = coord - math.floor(coord)
    return int(round(a * (1.0-ratio) + b * ratio))

def bilinear(im, x, y):
    x1, y1 = int(floor(x)), int(floor(y))
    x2, y2 = x1+1, y1+1
    left = lerp(im.getpixel((x1, y1)), im.getpixel((x1, y2)), y)
    right = lerp(im.getpixel((x2, y1)), im.getpixel((x2, y2)), y)
    return lerp(left, right, x)

A robust implementation of bilinear would also include bounds checking for when the coordinates go off the image.

like image 166
Mark Ransom Avatar answered Oct 22 '25 23:10

Mark Ransom