Skip to content

Instantly share code, notes, and snippets.

@GregTJ
Created October 8, 2019 08:03
Show Gist options
  • Save GregTJ/097d7829048c6bf27bc5008a8d153825 to your computer and use it in GitHub Desktop.
Save GregTJ/097d7829048c6bf27bc5008a8d153825 to your computer and use it in GitHub Desktop.
Pixel sorting with Numpy
import numpy as np
from PIL import Image
def sort_pixels(image, condition, rotation=0):
pixels = np.rot90(np.array(image), rotation)
luminosity = np.sum(pixels, axis=2) / (255 * 3)
mask = np.zeros_like(luminosity)
mask[condition(luminosity)] = 1
edges = np.apply_along_axis(lambda row: np.convolve(row, [-1, 1], 'same'), 0, mask)
intervals = [np.flatnonzero(row) for row in edges]
for row, key in enumerate(luminosity):
order = np.split(key, intervals[row])
for index, segment in enumerate(order[1:]):
order[index + 1] = np.argsort(segment) + intervals[row][index]
order = np.concatenate(order)
for channel in range(3):
pixels[row, :, channel] = pixels[row, order.astype('uint32'), channel]
return Image.fromarray(np.rot90(pixels, -rotation))
sort_pixels(Image.open('in.jpg'), lambda lum: (lum > 2 / 6) & (lum < 4 / 6), 1).save('out.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment