Skip to content

Instantly share code, notes, and snippets.

@quocdat32461997
Created February 8, 2020 07:02
Show Gist options
  • Select an option

  • Save quocdat32461997/fae180384076fdea9bf0b2553ea4e10c to your computer and use it in GitHub Desktop.

Select an option

Save quocdat32461997/fae180384076fdea9bf0b2553ea4e10c to your computer and use it in GitHub Desktop.

Revisions

  1. quocdat32461997 created this gist Feb 8, 2020.
    37 changes: 37 additions & 0 deletions nn.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    """
    nn - function nearest neigbor to map pixels of scaled images to the original images for image interpolation. By default, assume that scale around (0, 0)
    Parameters:
    orgi_img I/P original 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 color-filled image
    """
    def nn(origi_img, scaled_img, h_ratio, w_ratio):
    """
    nearest neighbor - a linear interpolation to fill pixels of scaled images by picking the neartest pixels
    """

    #get height and width of scaled_img and origi_img
    height = scaled_img.shape[0]
    h = origi_img.shape[0]
    width = scaled_img.shape[1]
    w = origi_img.shape[1]

    #visit each pixel and map back to original image
    for row in range(height):
    x = round(row / h_ratio)
    if not x in range(h): #if out-of-bound, fill w/ zeros
    continue

    for col in range(width):
    y = round(col / w_ratio)

    #map to the nearest pixels
    if not y in range(w): #if out-of-bound, fill with zero
    continue
    else:
    scaled_img[row, col] = origi_img[x, y]
    return scaled_img
    """ end of nn """