Created
October 8, 2019 08:03
-
-
Save GregTJ/097d7829048c6bf27bc5008a8d153825 to your computer and use it in GitHub Desktop.
Pixel sorting with Numpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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