Skip to content

Instantly share code, notes, and snippets.

@quocdat32461997
Created February 8, 2020 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quocdat32461997/8e7ed648b32020e42a22542ff4d37dcb to your computer and use it in GitHub Desktop.
Save quocdat32461997/8e7ed648b32020e42a22542ff4d37dcb to your computer and use it in GitHub Desktop.
"""
linear_interpolate - function to bilinear interpolatation trasformation
Parameters:
origi_img I/P image input
scaled_img I/P scaled image input - 2d array of mapped pixels
h_ratio I/P scaling ratio for height
w_ratio I/P scaling ratio for width
O/P transformed image
"""
def linear_interpolate(origi_img, scaled_img, h_ratio, w_ratio):
#get height and width of scaled_img and origi_img
height = scaled_img.shape[0]
width = scaled_img.shape[1]
h = origi_img.shape[0]
w = origi_img.shape[1]
#visit each pixel and map back to original image
#extra variables are pre-computed in order to prevent re-computing within for loops
for row in range(height):
#get x, floor and ceil of x, compute weight b
x = row / h_ratio
fx = np.int(np.floor(x))
cx = np.int(np.ceil(x))
#if out-of-bound, fill w/ zero
if not fx in range(h) or not cx in range(h):
continue
#compute weight
b = x - fx
nb = 1 - b
for col in range(width):
#get y, floor and ceil of y, and compute weight a
y = col / w_ratio
fy = np.int(np.floor(y))
cy = np.int(np.ceil(y))
#compute transformed pixels
if fy in range(w) and cy in range(w): #if out-of-bound, fill with zeros
#compute weight
a = y - fy
na = 1 - a
scaled_img[row, col] = na * nb * origi_img[fx, fy] + na * b * origi_img[fx, cy] + a * nb * origi_img[cx, fy] + a * b * origi_img[cx, cy]
else:
pass
return scaled_img
""" linear_interpolate """
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment