├── requrements.txt
├── .gitignore
├── assets
├── poetinThreaded.png
└── angelineThreaded.png
├── LICENSE.md
├── README.md
└── threadTone.py
/requrements.txt:
--------------------------------------------------------------------------------
1 | opencv-python
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | *.png
3 | *.jpg
4 | *.svg
5 | *.csv
6 |
--------------------------------------------------------------------------------
/assets/poetinThreaded.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/theveloped/ThreadTone/HEAD/assets/poetinThreaded.png
--------------------------------------------------------------------------------
/assets/angelineThreaded.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/theveloped/ThreadTone/HEAD/assets/angelineThreaded.png
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Tobias Scheepers
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ThreadTone | a halftone representation of an image made of thread
2 |
3 | The process of generating an image with thread is an idea of [Petros Vrellis](http://artof01.com/vrellis/index.html). As I've documented [here](http://www.thevelop.nl/blog/2016-12-25/ThreadTone/) the process is comprised of three steps:
4 |
5 | * Image pre-processing (cropping, resizing, etc.)
6 | * Algorithm to place threads
7 | * In my case parsing the result to G-Code for automated fabrication
8 |
9 | ## To use this tool, run:
10 | python threadTone.py -p [image-path] -l [number-of-lines-to-draw] -n [number-of-pins-to-draw-with]
11 |
12 | ex: python threadTone.py -p kitten.jpg -l 2000 -n 250
13 | ex: python threadTone.py -p puppr.png
14 | ###### Note: imgPath is a required field, and to give a value to numPins
15 |
16 | ## A set of two example images can be found below. Please refer to my [blog](http://www.thevelop.nl/blog/2016-12-25/ThreadTone/) for more details.
17 |
18 | 
19 |
20 | 
21 |
22 | ## License
23 |
24 | This script is released under MIT License.
25 |
--------------------------------------------------------------------------------
/threadTone.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import sys
4 | import cv2
5 | import numpy as np
6 |
7 | # Parameters
8 | imgRadius = 500 # Number of pixels that the image radius is resized to
9 |
10 | initPin = 0 # Initial pin to start threading from
11 | numPins = 200 # Number of pins on the circular loom
12 | numLines = 1000 # Maximal number of lines
13 |
14 | minLoop = 3 # Disallow loops of less than minLoop lines
15 | lineWidth = 3 # The number of pixels that represents the width of a thread
16 | lineWeight = 15 # The weight a single thread has in terms of "darkness"
17 |
18 | helpMessage = """
19 | To use this tool, run:
20 | python threadTone.py -p image-path -l number-of-lines-to-draw -n number-of-pins-to-draw-with
21 |
22 | ex: python threadTone.py -p kitten.jpg -l 2000 -n 250
23 | ex: python threadTone.py -p puppr.png
24 |
25 | Note: imgPath is a required field.
26 | """
27 | args = sys.argv
28 |
29 | # \/argument interpreter
30 | for arg in args:
31 | if arg == "-h" or arg == "-?" or arg == "help":
32 | print(helpMessage)
33 | sys.exit()
34 |
35 | argNum = 1
36 | while argNum < len(args):
37 | if args[argNum][0] == "-":
38 | flag = args[argNum]
39 | if flag == "-p" or flag == "-P":
40 | argument = args[argNum + 1]
41 | imgPath = args[argNum + 1]
42 | argNum += 2
43 | elif flag == "-l" or flag == "-L":
44 | try:
45 | int(args[argNum + 1])
46 | except ValueError:
47 | print("'" + args[argNum + 1] + "' is not an integer, please input an integer for the number of lines to draw.")
48 | sys.exit(1)
49 | numLines = int(args[argNum + 1])
50 | argNum += 2
51 | elif flag == "-n" or flag == "-N":
52 | try:
53 | int(args[argNum + 1])
54 | except ValueError:
55 | print("'" + args[argNum + 1] + "' is not an integer, please input an integer for the number of pins.")
56 | sys.exit(1)
57 | numPins = int(args[argNum + 1])
58 | argNum += 2
59 | else:
60 | print("Invalid flag: " + args[argNum])
61 | sys.exit(1)
62 | else:
63 | print("Invalid flag: " + args[argNum])
64 | sys.exit(1)
65 |
66 | # \/main processes
67 | banner = """
68 | __ __ ________
69 | / /_/ /_ ________ ____ _____/ /_ __/___ ____ ___
70 | / __/ __ \/ ___/ _ \/ __ `/ __ / / / / __ \/ __ \/ _ \\
71 | / /_/ / / / / / __/ /_/ / /_/ / / / / /_/ / / / / __/
72 | \__/_/ /_/_/ \___/\__,_/\__,_/ /_/ \____/_/ /_/\___/
73 |
74 | Build a thread based halftone representation of an image
75 | (Press: ctrl+c in this terminal window to kill the drawing)
76 | """
77 |
78 | # Invert grayscale image
79 | def invertImage(image):
80 | return (255-image)
81 |
82 | # Apply circular mask to image
83 | def maskImage(image, radius):
84 | y, x = np.ogrid[-radius:radius + 1, -radius:radius + 1]
85 | mask = x**2 + y**2 > radius**2
86 | image[mask] = 0
87 |
88 | return image
89 |
90 | # Compute coordinates of loom pins
91 | def pinCoords(radius, numPins=200, offset=0, x0=None, y0=None):
92 | alpha = np.linspace(0 + offset, 2*np.pi + offset, numPins + 1)
93 |
94 | if (x0 == None) or (y0 == None):
95 | x0 = radius + 1
96 | y0 = radius + 1
97 |
98 | coords = []
99 | for angle in alpha[0:-1]:
100 | x = int(x0 + radius*np.cos(angle))
101 | y = int(y0 + radius*np.sin(angle))
102 |
103 | coords.append((x, y))
104 | return coords
105 |
106 | # Compute a line mask
107 | def linePixels(pin0, pin1):
108 | length = int(np.hypot(pin1[0] - pin0[0], pin1[1] - pin0[1]))
109 |
110 | x = np.linspace(pin0[0], pin1[0], length)
111 | y = np.linspace(pin0[1], pin1[1], length)
112 |
113 | return (x.astype(int)-1, y.astype(int)-1)
114 |
115 |
116 | if __name__=="__main__":
117 | print(banner)
118 |
119 | # Load image
120 | image = cv2.imread(imgPath)
121 |
122 | print("[+] loaded " + imgPath + " for threading..")
123 |
124 | # Crop image
125 | height, width = image.shape[0:2]
126 | minEdge= min(height, width)
127 | topEdge = int((height - minEdge)/2)
128 | leftEdge = int((width - minEdge)/2)
129 | imgCropped = image[topEdge:topEdge+minEdge, leftEdge:leftEdge+minEdge]
130 | cv2.imwrite('./cropped.png', imgCropped)
131 |
132 | # Convert to grayscale
133 | imgGray = cv2.cvtColor(imgCropped, cv2.COLOR_BGR2GRAY)
134 | cv2.imwrite('./gray.png', imgGray)
135 |
136 | # Resize image
137 | imgSized = cv2.resize(imgGray, (2*imgRadius + 1, 2*imgRadius + 1))
138 |
139 | # Invert image
140 | imgInverted = invertImage(imgSized)
141 | cv2.imwrite('./inverted.png', imgInverted)
142 |
143 | # Mask image
144 | imgMasked = maskImage(imgInverted, imgRadius)
145 | cv2.imwrite('./masked.png', imgMasked)
146 |
147 | print("[+] image preprocessed for threading..")
148 |
149 | # Define pin coordinates
150 | coords = pinCoords(imgRadius, numPins)
151 | height, width = imgMasked.shape[0:2]
152 |
153 | # image result is rendered to
154 | imgResult = 255 * np.ones((height, width))
155 |
156 | # Initialize variables
157 | i = 0
158 | lines = []
159 | previousPins = []
160 | oldPin = initPin
161 | lineMask = np.zeros((height, width))
162 |
163 | imgResult = 255 * np.ones((height, width))
164 |
165 | # Loop over lines until stopping criteria is reached
166 | for line in range(numLines):
167 | i += 1
168 | bestLine = 0
169 | oldCoord = coords[oldPin]
170 |
171 | # Loop over possible lines
172 | for index in range(1, numPins):
173 | pin = (oldPin + index) % numPins
174 |
175 | coord = coords[pin]
176 |
177 | xLine, yLine = linePixels(oldCoord, coord)
178 |
179 | # Fitness function
180 | lineSum = np.sum(imgMasked[yLine, xLine])
181 |
182 | if (lineSum > bestLine) and not(pin in previousPins):
183 | bestLine = lineSum
184 | bestPin = pin
185 |
186 | # Update previous pins
187 | if len(previousPins) >= minLoop:
188 | previousPins.pop(0)
189 | previousPins.append(bestPin)
190 |
191 | # Subtract new line from image
192 | lineMask = lineMask * 0
193 | cv2.line(lineMask, oldCoord, coords[bestPin], lineWeight, lineWidth)
194 | imgMasked = np.subtract(imgMasked, lineMask)
195 |
196 | # Save line to results
197 | lines.append((oldPin, bestPin))
198 |
199 | # plot results
200 | xLine, yLine = linePixels(coords[bestPin], coord)
201 | imgResult[yLine, xLine] = 0
202 | cv2.imshow('image', imgResult)
203 | cv2.waitKey(1)
204 |
205 | # Break if no lines possible
206 | if bestPin == oldPin:
207 | break
208 |
209 | # Prepare for next loop
210 | oldPin = bestPin
211 |
212 | # Print progress
213 | sys.stdout.write("\b\b")
214 | sys.stdout.write("\r")
215 | sys.stdout.write("[+] Computing line " + str(line + 1) + " of " + str(numLines) + " total")
216 | sys.stdout.flush()
217 |
218 | print("\n[+] Image threaded")
219 |
220 | # Wait for user and save before exit
221 | cv2.waitKey(0)
222 | cv2.destroyAllWindows()
223 | cv2.imwrite('./threaded.png', imgResult)
224 |
225 | svg_output = open('threaded.svg','wb')
226 | header="""
227 | "
230 | svg_output.write(header.encode('utf8'))
231 | pather = lambda d : '\n' % d
232 | pathstrings=[]
233 | pathstrings.append("M" + "%i %i" % coords[lines[0][0]] + " ")
234 | for l in lines:
235 | nn = coords[l[1]]
236 | pathstrings.append("L" + "%i %i" % nn + " ")
237 | pathstrings.append("Z")
238 | d = "".join(pathstrings)
239 | svg_output.write(pather(d).encode('utf8'))
240 | svg_output.write(footer.encode('utf8'))
241 | svg_output.close()
242 |
243 | csv_output = open('threaded.csv','wb')
244 | csv_output.write("x1,y1,x2,y2\n".encode('utf8'))
245 | csver = lambda c1,c2 : "%i,%i" % c1 + "," + "%i,%i" % c2 + "\n"
246 | for l in lines:
247 | csv_output.write(csver(coords[l[0]],coords[l[1]]).encode('utf8'))
248 | csv_output.close()
249 |
250 | sys.exit()
251 |
--------------------------------------------------------------------------------