I find your numpy code to be quite rational as far as my skills go, but your script have several things to improve on besides that.
Improvable in current scope :
- Removing duplicate code thanks to a helper function
- Painting the whole background to simplify
- Removing (yet) unecessary line
w, h, k = data.shape - Naming error, or logic error ? Background and edge color seem swapped. Changing
<= levelto> level - Some non-compliant and unexplicit variable names
Code showing this
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
def get_dist_array(data, shifted_data, level):
distance_axisdistance_map = np.absolute(np.sum(data - shifted_data, axis=2))
return np.asarray(distance_axisdistance_map > level, dtype="int32")
def stroke(image_path, output, level=80, edge_color=[255,255,255], blackground_color=[0,0,0]):
img = Image.open(image_path)
data = np.asarray(img, dtype="int32")
level = min(max(1,level), 255)
edges_right = get_dist_array(data, np.concatenate((data[:, 1:], data[:,-1:]), axis=1), level)
edges_down = get_dist_array(data, np.concatenate((data[1:,:], data[-1:,:]), axis=0), level)
data[:] = blackground_color
edges = (edges_right+edges_down) > 1
data[edges] = edge_color
img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype="uint8"), "RGB")
img.save(output)
if __name__ == "__main__":
stroke("images/bob.png", "new_test.jpg")
Other things to consider worth improving :
- Get rid of hardcoded file names. You could use
argparsehere - RGBA support ?