forked from theveloped/ThreadTone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadTone.py
188 lines (140 loc) · 5.33 KB
/
threadTone.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import sys
import cv2
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('image', type=argparse.FileType("r"))
parser.add_argument('--nLines', type=int, default=3000)
parser.add_argument('--nPins', type=int, default=250)
parser.add_argument('--lineWidth', type=int, default=3)
parser.add_argument('--lineWeight', type=int, default=2)
args = parser.parse_args()
# Parameters
imgPath = sys.argv[1]
imgRadius = 500 # Number of pixels that the image radius is resized to
initPin = 0 # Initial pin to start threading from
nPins = args.nPins # Number of pins on the circular loom
nLines = args.nLines # Maximal number of lines
minLoop = 3 # Disallow loops of less than minLoop lines
lineWidth = args.lineWidth # The number of pixels that represents the width of a thread
lineWeight = args.lineWeight # The weight a single thread has in terms of "darkness"
banner = """
__ __ ________
/ /_/ /_ ________ ____ _____/ /_ __/___ ____ ___
/ __/ __ \/ ___/ _ \/ __ `/ __ / / / / __ \/ __ \/ _ \\
/ /_/ / / / / / __/ /_/ / /_/ / / / / /_/ / / / / __/
\__/_/ /_/_/ \___/\__,_/\__,_/ /_/ \____/_/ /_/\___/
Build a thread based halftone representation of an image
"""
# Invert grayscale image
def invertImage(image):
return (255-image)
# Apply circular mask to image
def maskImage(image, radius):
y, x = np.ogrid[-radius:radius + 1, -radius:radius + 1]
mask = x**2 + y**2 > radius**2
image[mask] = 0
return image
# Compute coordinates of loom pins
def pinCoords(radius, nPins=200, offset=0, x0=None, y0=None):
alpha = np.linspace(0 + offset, 2*np.pi + offset, nPins + 1)
if (x0 == None) or (y0 == None):
x0 = radius + 1
y0 = radius + 1
coords = []
for angle in alpha[0:-1]:
x = int(x0 + radius*np.cos(angle))
y = int(y0 + radius*np.sin(angle))
coords.append((x, y))
return coords
# Compute a line mask
def linePixels(pin0, pin1):
length = int(np.hypot(pin1[0] - pin0[0], pin1[1] - pin0[1]))
x = np.linspace(pin0[0], pin1[0], length)
y = np.linspace(pin0[1], pin1[1], length)
return (x.astype(np.int)-1, y.astype(np.int)-1)
if __name__=="__main__":
print(banner)
# Load image
image = cv2.imread(imgPath)
print(("[+] loaded " + imgPath + " for threading.."))
# Crop image
height, width = image.shape[0:2]
minEdge= min(height, width)
topEdge = int((height - minEdge)/2)
leftEdge = int((width - minEdge)/2)
imgCropped = image[topEdge:topEdge+minEdge, leftEdge:leftEdge+minEdge]
cv2.imwrite('./cropped.png', imgCropped)
# Convert to grayscale
imgGray = cv2.cvtColor(imgCropped, cv2.COLOR_BGR2GRAY)
cv2.imwrite('./gray.png', imgGray)
# Resize image
imgSized = cv2.resize(imgGray, (2*imgRadius + 1, 2*imgRadius + 1))
# Invert image
imgInverted = invertImage(imgSized)
cv2.imwrite('./inverted.png', imgInverted)
# Mask image
imgMasked = maskImage(imgInverted, imgRadius)
cv2.imwrite('./masked.png', imgMasked)
print("[+] image preprocessed for threading..")
# Define pin coordinates
coords = pinCoords(imgRadius, nPins)
height, width = imgMasked.shape[0:2]
# image result is rendered to
imgResult = 255 * np.ones((height, width))
# Initialize variables
i = 0
lines = []
previousPins = []
oldPin = initPin
lineMask = np.zeros((height, width))
imgResult = 255 * np.ones((height, width))
# Loop over lines until stopping criteria is reached
for line in range(nLines):
i += 1
bestLine = 0
oldCoord = coords[oldPin]
# Loop over possible lines
for index in range(1, nPins):
pin = (oldPin + index) % nPins
coord = coords[pin]
xLine, yLine = linePixels(oldCoord, coord)
# Fitness function
lineSum = np.sum(imgMasked[yLine, xLine])
if (lineSum > bestLine) and not(pin in previousPins):
bestLine = lineSum
bestPin = pin
# Update previous pins
if len(previousPins) >= minLoop:
previousPins.pop(0)
previousPins.append(bestPin)
# Subtract new line from image
lineMask = lineMask * 0
cv2.line(lineMask, oldCoord, coords[bestPin], lineWeight, lineWidth)
imgMasked = np.subtract(imgMasked, lineMask)
# Save line to results
lines.append((oldPin, bestPin))
# plot results
xLine, yLine = linePixels(coords[bestPin], coord)
imgResult[yLine, xLine] = 0
# cv2.imshow('image', imgResult)
# cv2.waitKey(1)
# Break if no lines possible
if bestPin == oldPin:
break
# Prepare for next loop
oldPin = bestPin
# Print progress
sys.stdout.write("\b\b")
sys.stdout.write("\r")
sys.stdout.write("[+] Computing line " + str(line + 1) + " of " + str(nLines) + " total")
sys.stdout.flush()
print("\n[+] Image threaded")
# Wait for user and save before exit
# cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('./threaded.png', imgResult)
print("[+] Circos Conf Written")
with open('circos/data/links.txt', 'w') as handle:
for (a, b) in lines:
handle.write('hs1 {0} {0} hs1 {1} {1}\n'.format(a * 10, b * 10))