I want to calculate the k nearest pixels to any pixel, but my current method is very time consuming.

Im want to do image inpainting. So want to predict any black pixel using the nearest k non-black pixels.

Heres my implementation:

def find_200_nearest(image, pixel_idx1, pixel_idx2, k=200): """ Returns k nearest pixels from (pixel_idx1, pixel_idx2) Args: image: Entire image pixel_idx1: x co-ordinate of source pixel pixel_idx2: y co-ordinate of source pixel k: Number of nearest pixels needed Returns: k nearest pixels """ a = np.empty((0, 5)) for i in range(1, image.shape[1]): if pixel_idx1 - i >= 0: a = get_pixels(image, x=max(pixel_idx1 - i, 0), y=list(range(max(pixel_idx2 - i, 0), min(pixel_idx2 + i, image.shape[1] - 1) + 1)), a=a, pos='row') if pixel_idx1 + i < image.shape[1]: a = get_pixels(image, x=min(pixel_idx1 + i, image.shape[1] - 1), y=list(range(max(pixel_idx2 - i, 0), min(pixel_idx2 + i, image.shape[1] - 1) + 1)), a=a, pos='row') if pixel_idx2 - i >= 0: a = get_pixels(image, x=list(range(max(pixel_idx1 - i + 1, 0), min(pixel_idx1 + i - 1, image.shape[1] - 1) + 1)), y=max(pixel_idx2 - i, 0), a=a, pos='col') if pixel_idx2 + i < image.shape[1]: a = get_pixels(image, x=list(range(max(pixel_idx1 - i + 1, 0), min(pixel_idx1 + i - 1, image.shape[1] - 1) + 1)), y=min(pixel_idx2 + i, image.shape[1] - 1), a=a, pos='col') if a.shape[0] >= 200: break try: return a[:k] except IndexError: print('{} nearest non-black pixels not available'.format(k))

def get_pixels(image, x, y, a, pos='row'): """ Returns non-black pixels at (x, y) Args: image: Entire image x: Row number or range for pixels at distance i, lower bounded by 0 and upper bounded by image_size -1 y: Column number or range for pixels at distance i, lower bounded by 0 and upper bounded by image_size -1 a: Data array pos: Row or Column Returns: a """ black_pixels = np.argwhere(np.sum(image[:, x, y], axis=0) > 0) if pos == 'row': for n, idx in enumerate(black_pixels): a = np.append(a, np.array([image[:, x, y[0] + idx].flatten().tolist() + [x, int(y[0] + idx)]]), axis=0) # appending (R, G, B, i, j) for an image at i, j else: for n, idx in enumerate(black_pixels): a = np.append(a, np.array([image[:, x[0] + idx, y].flatten().tolist() + [int(x[0] + idx), y]]), axis=0) return a

More Anupam Anurag Tripathi's questions See All
Similar questions and discussions