drawing-machine/linedraw.py

412 lines
10 KiB
Python
Raw Normal View History

2018-03-21 12:00:46 -04:00
#!/usr/bin/env python3
"""
Takes a raster image file and vectorizes it to create line art usable by
a pen plotter.
"""
2018-03-21 11:06:44 -04:00
import os
import math
2018-03-21 12:00:46 -04:00
from random import *
2018-03-21 11:06:44 -04:00
from PIL import Image, ImageDraw, ImageOps
no_cv = True
draw_contours = True
draw_hatch = False
try:
import numpy as np
import cv2
except:
print("Cannot import numpy/openCV. Switching to NO_CV mode.")
no_cv = True
F_Blur = {
(-2,-2):2,(-1,-2):4,(0,-2):5,(1,-2):4,(2,-2):2,
(-2,-1):4,(-1,-1):9,(0,-1):12,(1,-1):9,(2,-1):4,
(-2,0):5,(-1,0):12,(0,0):15,(1,0):12,(2,0):5,
(-2,1):4,(-1,1):9,(0,1):12,(1,1):9,(2,1):4,
(-2,2):2,(-1,2):4,(0,2):5,(1,2):4,(2,2):2,
}
2018-03-21 12:00:46 -04:00
2018-03-21 11:33:32 -04:00
F_SobelX = {
(-1,-1): 1,
(0,-1): 0,
2018-03-21 12:00:46 -04:00
(1,-1): -1,
2018-03-21 11:33:32 -04:00
(-1,0): 2,
(0,0): 0,
2018-03-21 12:00:46 -04:00
(1,0): -2,
2018-03-21 11:33:32 -04:00
(-1,1): 1,
(0,1): 0,
(1,1): -1}
2018-03-21 12:00:46 -04:00
2018-03-21 11:33:32 -04:00
F_SobelY = {
(-1,-1): 1,
(0,-1): 2,
(1,-1): 1,
(-1,0): 0,
(0,0): 0,
(1,0): 0,
2018-03-21 12:00:46 -04:00
(-1,1): -1,
(0,1): -2,
(1,1): -1}
2018-03-21 11:06:44 -04:00
2018-03-21 12:00:46 -04:00
def appmask(image, masks):
PX = image.load()
w, h = image.size
2018-03-21 11:06:44 -04:00
NPX = {}
2018-03-21 12:00:46 -04:00
for x in range(0, w):
for y in range(0, h):
2018-03-21 11:06:44 -04:00
a = [0]*len(masks)
for i in range(len(masks)):
for p in masks[i].keys():
2018-03-21 12:00:46 -04:00
if 0 < x + p[0] < w and 0 < y + p[1] < h:
a[i] += PX[x + p[0], y + p[1]] * masks[i][p]
if sum(masks[i].values()) != 0:
2018-03-21 11:06:44 -04:00
a[i] = a[i] / sum(masks[i].values())
2018-03-21 12:00:46 -04:00
NPX[x,y] = int(sum([v**2 for v in a])**0.5)
for x in range(0, w):
for y in range(0, h):
PX[x, y] = NPX[x, y]
2018-03-21 11:06:44 -04:00
def distsum(*args):
2018-03-21 11:33:32 -04:00
"""
Takes a list of pairs of points, finds the distance between each point
pair, and returns the sum of all distances.
"""
dists = []
2018-03-22 11:44:51 -04:00
for i in range(1, len(args)):
2018-03-21 12:00:46 -04:00
a = args[i][0] - args[i-1][0]
b = args[i][1] - args[i-1][1]
2018-03-21 11:33:32 -04:00
dist = (a**2 + b**2)**0.5
dists.append(dist)
return sum(dists)
2018-03-21 11:06:44 -04:00
def sortlines(lines):
print("optimizing stroke sequence...")
clines = lines[:]
slines = [clines.pop(0)]
while clines != []:
2018-03-21 12:00:46 -04:00
x, s, r = None, 1000000, False
2018-03-21 11:06:44 -04:00
for l in clines:
2018-03-21 12:00:46 -04:00
d = distsum(l[0], slines[-1][-1])
dr = distsum(l[-1], slines[-1][-1])
2018-03-21 11:06:44 -04:00
if d < s:
2018-03-21 12:00:46 -04:00
x, s, r = l[:], d, False
2018-03-21 11:06:44 -04:00
if dr < s:
2018-03-21 12:00:46 -04:00
x, s, r = l[:], s, True
2018-03-21 11:06:44 -04:00
clines.remove(x)
if r == True:
x = x[::-1]
slines.append(x)
return slines
2018-03-21 12:00:46 -04:00
def auto_canny(image, sigma=0.33):
2018-03-21 11:06:44 -04:00
"""
Automatically determines appropriate upper and lower boundries for the Canny function.
"""
2018-03-21 12:00:46 -04:00
med = np.median(image)
2018-03-21 11:06:44 -04:00
lower = int(max(0, (1.0 - sigma) * med))
upper = int(min(255, (1.0 + sigma) * med))
2018-03-21 12:00:46 -04:00
edges = cv2.Canny(image, lower, upper)
2018-03-21 11:06:44 -04:00
return edges
2018-03-21 12:00:46 -04:00
def find_edges(image):
2018-03-21 11:06:44 -04:00
print("finding edges...")
no_cv = True
if no_cv:
2018-03-21 12:00:46 -04:00
#appmask(image, [F_Blur])
appmask(image, [F_SobelX, F_SobelY])
2018-03-21 11:06:44 -04:00
else:
2018-03-21 12:00:46 -04:00
image = np.array(image)
image = cv2.GaussianBlur(image, (3, 3), 0)
#image = cv2.Canny(image,100,200)
image = auto_canny(image)
image = Image.fromarray(image)
return image.point(lambda p: p > 128 and 255)
2018-03-21 11:06:44 -04:00
2018-03-21 12:00:46 -04:00
def getdots(image):
2018-03-21 11:06:44 -04:00
print("getting contour points...")
2018-03-21 12:00:46 -04:00
PX = image.load()
2018-03-21 11:06:44 -04:00
dots = []
2018-03-21 12:00:46 -04:00
w, h = image.size
2018-03-21 11:06:44 -04:00
for y in range(h-1):
row = []
2018-03-21 12:00:46 -04:00
for x in range(1, w):
if PX[x, y] == 255:
2018-03-21 11:06:44 -04:00
if len(row) > 0:
2018-03-21 12:00:46 -04:00
if x-row[-1][0] == row[-1][-1] + 1:
row[-1] = (row[-1][0], row[-1][-1] + 1)
2018-03-21 11:06:44 -04:00
else:
2018-03-21 12:00:46 -04:00
row.append((x, 0))
2018-03-21 11:06:44 -04:00
else:
2018-03-21 12:00:46 -04:00
row.append((x, 0))
2018-03-21 11:06:44 -04:00
dots.append(row)
return dots
2018-03-21 11:33:32 -04:00
2018-03-21 11:06:44 -04:00
def connectdots(dots):
print("connecting contour points...")
contours = []
for y in range(len(dots)):
2018-03-21 12:00:46 -04:00
for x, v in dots[y]:
2018-03-21 11:06:44 -04:00
if v > -1:
if y == 0:
2018-03-21 12:00:46 -04:00
contours.append([(x, y)])
2018-03-21 11:06:44 -04:00
else:
closest = -1
cdist = 100
2018-03-21 12:00:46 -04:00
for x0, v0 in dots[y-1]:
if abs(x0 - x) < cdist:
cdist = abs(x0 - x)
2018-03-21 11:06:44 -04:00
closest = x0
if cdist > 3:
2018-03-21 12:00:46 -04:00
contours.append([(x, y)])
2018-03-21 11:06:44 -04:00
else:
found = 0
for i in range(len(contours)):
2018-03-21 12:00:46 -04:00
if contours[i][-1] == (closest, y-1):
contours[i].append((x, y,))
2018-03-21 11:06:44 -04:00
found = 1
break
if found == 0:
2018-03-21 12:00:46 -04:00
contours.append([(x, y)])
2018-03-21 11:06:44 -04:00
for c in contours:
2018-03-21 12:00:46 -04:00
if c[-1][1] < y-1 and len(c) < 4:
2018-03-21 11:06:44 -04:00
contours.remove(c)
return contours
2018-03-21 12:00:46 -04:00
def getcontours(image, sc=2):
2018-03-21 11:06:44 -04:00
print("generating contours...")
2018-03-21 12:00:46 -04:00
image = find_edges(image)
2018-03-22 11:44:51 -04:00
image1 = image.copy()
2018-03-21 12:00:46 -04:00
image2 = image.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
dots1 = getdots(image1)
2018-03-21 11:06:44 -04:00
contours1 = connectdots(dots1)
2018-03-21 12:00:46 -04:00
dots2 = getdots(image2)
2018-03-21 11:06:44 -04:00
contours2 = connectdots(dots2)
for i in range(len(contours2)):
2018-03-21 12:00:46 -04:00
contours2[i] = [(c[1], c[0]) for c in contours2[i]]
contours = contours1 + contours2
2018-03-21 11:06:44 -04:00
for i in range(len(contours)):
for j in range(len(contours)):
2018-03-21 12:00:46 -04:00
if len(contours[i]) > 0 and len(contours[j]) > 0:
if distsum(contours[j][0], contours[i][-1]) < 8:
contours[i] = contours[i] + contours[j]
2018-03-21 11:06:44 -04:00
contours[j] = []
for i in range(len(contours)):
2018-03-21 12:00:46 -04:00
contours[i] = [contours[i][j] for j in range(0, len(contours[i]), 8)]
2018-03-21 11:06:44 -04:00
contours = [c for c in contours if len(c) > 1]
2018-03-21 12:00:46 -04:00
for i in range(0, len(contours)):
contours[i] = [(v[0] * sc, v[1] * sc) for v in contours[i]]
2018-03-21 11:06:44 -04:00
2018-03-21 12:00:46 -04:00
for i in range(0, len(contours)):
for j in range(0, len(contours[i])):
contours[i][j] = int(contours[i][j][0] + 10), int(contours[i][j][1] + 10)
2018-03-21 11:06:44 -04:00
return contours
2018-03-21 12:00:46 -04:00
def hatch(image, sc=16):
2018-03-21 11:06:44 -04:00
print("hatching...")
2018-03-21 12:00:46 -04:00
PX = image.load()
w,h = image.size
2018-03-21 11:06:44 -04:00
lg1 = []
lg2 = []
for x0 in range(w):
for y0 in range(h):
2018-03-21 12:00:46 -04:00
x = x0 * sc
y = y0 * sc
if PX[x0, y0] > 144:
2018-03-21 11:06:44 -04:00
pass
2018-03-21 12:00:46 -04:00
elif PX[x0, y0] > 64:
lg1.append([(x, y+sc/4), (x+sc, y+sc/4)])
elif PX[x0, y0] > 16:
lg1.append([(x, y+sc/4), (x+sc, y+sc/4)])
lg2.append([(x+sc, y), (x, y+sc)])
2018-03-21 11:06:44 -04:00
else:
2018-03-21 12:00:46 -04:00
lg1.append([(x, y+sc/4), (x+sc, y+sc/4)])
lg1.append([(x, y+sc/2 + sc/4), (x+sc, y+sc/2 + sc/4)])
lg2.append([(x+sc, y), (x, y+sc)])
lines = [lg1, lg2]
for k in range(0, len(lines)):
for i in range(0, len(lines[k])):
for j in range(0, len(lines[k])):
2018-03-21 11:06:44 -04:00
if lines[k][i] != [] and lines[k][j] != []:
if lines[k][i][-1] == lines[k][j][0]:
2018-03-21 12:00:46 -04:00
lines[k][i] = lines[k][i] + lines[k][j][1:]
2018-03-21 11:06:44 -04:00
lines[k][j] = []
lines[k] = [l for l in lines[k] if len(l) > 0]
2018-03-21 12:00:46 -04:00
lines = lines[0] + lines[1]
2018-03-21 11:06:44 -04:00
2018-03-21 12:00:46 -04:00
for i in range(0, len(lines)):
for j in range(0, len(lines[i])):
lines[i][j] = int(lines[i][j][0] + sc), int(lines[i][j][1] + sc) - j
2018-03-21 11:06:44 -04:00
return lines
2018-03-21 11:33:32 -04:00
def sketch(path, export_path=None, resolution=1024, hatch_size=16, contour_simplify=2):
2018-03-21 11:06:44 -04:00
image = Image.open(path)
if image._getexif().get(274): # "Orientation"
if image._getexif().get(274) > 4: # modes 5-8 indicate the image was rotated
image = image.rotate(-90, expand=True)
2018-03-21 11:06:44 -04:00
image = image.convert("L")
image = ImageOps.autocontrast(image ,10)
lines = []
if draw_contours:
2018-03-21 11:33:32 -04:00
width = int(resolution/contour_simplify)
height = int(resolution/contour_simplify*image.height/image.width)
2018-03-21 11:33:32 -04:00
lines += getcontours(image.resize((width, height)), contour_simplify)
2018-03-21 12:00:46 -04:00
2018-03-21 11:06:44 -04:00
if draw_hatch:
2018-03-21 11:33:32 -04:00
width = int(resolution/hatch_size)
height = int(resolution/hatch_size*image.height/image.width)
2018-03-21 11:33:32 -04:00
lines += hatch(image.resize((width, height)), hatch_size)
2018-03-21 11:06:44 -04:00
lines = sortlines(lines)
export_path = path.replace("received", "converted")
export_path = os.path.splitext(export_path)[0]
os.makedirs(os.path.split(export_path)[0], exist_ok=True)
2018-03-21 11:06:44 -04:00
with open(export_path + ".svg", "w") as file:
file.write(makePathSvg(lines))
with open(export_path + ".ngc", "w") as file:
file.write(makeGcode(lines))
print(len(lines), "strokes.")
print("done.")
return lines
def makePolySvg(lines):
"""
Uses the provided set of contours to generate an SVG file and returns it as a string. Contours get
written as polyline as objects.
"""
print("generating svg file...")
out = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">\n'
for l in lines:
l = ",".join([str(p[0]*0.5)+","+str(p[1]*0.5) for p in l])
out += '<polyline points="'+l+'" stroke="black" stroke-width="2" fill="none" />\n'
out += '</svg>'
return out
def makePathSvg(lines):
"""
Uses the provided set of contours to generate an SVG file and returns it as a string. Contours get
written as path objects.
"""
print("generating svg file...")
out = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">\n'
for l in lines:
l = ",".join([str(p[0]*0.5)+","+str(p[1]*0.5) for p in l])
out += '<path d="M'+l+'" stroke="black" stroke-width="2" fill="none" />\n'
out += "</svg>"
return out
def makeGcode(lines, paper_size="letter"):
"""
Converts the provided contour lines into G-code commands and returns them as a string.
"""
paper_sizes = {
"letter": (67.46875, 87.3125),
"ledger": (87.3125, 139.2903226),
"max": (90, 140)}
tot = []
for line in lines:
tot += line
max_x = max([p[0] for p in tot])
max_y = max([p[1] for p in tot])
d_x = paper_sizes[paper_size][0] / max_x
d_y = paper_sizes[paper_size][1] / max_y
scale = min(d_x, d_y)
print("generating gcode file...")
out = "$X\n$32=1\nM03\nF800\nG17 G21 G90 G54\nG01\n\n"
2018-03-21 11:06:44 -04:00
for line in lines:
start = line.pop(0)
out += "S1000\n"
#out += f"X{start[0]*0.5} Y{start[1]*0.5}\n"
out += "X" + str(start[0]*scale) + " Y" + str(start[1]*scale) + "\n"
out += "S0\n"
for point in line:
#out += f"X{point[0]*0.5} Y{point[1]*0.5}\n"
out += "X" + str(point[0]*scale) + " Y" + str(point[1]*scale) + "\n"
out += "\n"
out += "S1000\nX0 Y0\nM2\n"
return out
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="Convert image to vectorized line drawing for plotters.")
parser.add_argument(
'-i',
'--input',
nargs='?',
help='Input path')
parser.add_argument(
'-o',
'--output',
nargs='?',
help='Output path.')
parser.add_argument(
'--no_contour',
action='store_true',
help="Don't draw contours.")
parser.add_argument(
'--hatch',
action='store_true',
help='Enable hatching.')
parser.add_argument(
'--no_cv',
action='store_true',
help="Don't use OpenCV.")
parser.add_argument(
"--resolution",
default=1024,
type=int,
help="Resolution. eg. 512, 1024, 2048")
parser.add_argument(
'--contour_simplify',
default=2,
type=int,
help='Level of contour simplification. eg. 1, 2, 3')
parser.add_argument(
'--hatch_size',
default=16,
type=int,
help='Patch size of hatches. eg. 8, 16, 32')
args = parser.parse_args()
export_path = args.output
draw_hatch = args.hatch
draw_contours = not args.no_contour
no_cv = args.no_cv
2018-03-21 11:33:32 -04:00
sketch(args.input, args.output, args.resolution, args.contour_simplify, args.hatch_size)
2018-03-21 11:06:44 -04:00