-
Notifications
You must be signed in to change notification settings - Fork 2
/
qrcodes.py
70 lines (51 loc) · 1.68 KB
/
qrcodes.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
import multiprocessing
import qrcode
import random
import string
import numpy as np
IMAGE_SIZE = 21
STRING_LENGTH = 10
CHARACTER_SET = string.ascii_lowercase + string.ascii_uppercase + \
string.digits
def randomString():
"""
Return a random string where characters are drawn from a fixed
set of characters.
"""
return "".join(random.choice(CHARACTER_SET) for _ in range(STRING_LENGTH))
def qrCodeMatrix(data):
"""
Encode the given data in a QR code and return it as a numpy array of `0`
and `1`s.
"""
qr = qrcode.QRCode(
version=None, # automatically determine size
error_correction=qrcode.constants.ERROR_CORRECT_L, # 7% error tolerance
box_size=1, # single pixels for one box
border=0, # no border
)
qr.add_data(data)
qr.make(fit=True) # fit=True automatically determines the size
# Reverse black <-> white and convert to numpy array
return 1 - np.asarray(qr.get_matrix(), dtype=np.float)
def dataToVector(data):
"""
Returns the first letter of the given string, encoded as a numpy vector
of length `len(CHARACTER_SET)`.
"""
letter = data[0]
nums = map(lambda l: l == letter, CHARACTER_SET)
return np.asarray(list(nums), dtype=np.float)
def getRandomBatch(size):
"""
Return a number of QR code matrices and the corresponding labels.
"""
numProcesses = max(1, multiprocessing.cpu_count() - 2)
pool = multiprocessing.Pool(numProcesses)
strings = [randomString() for _ in range(size)]
X = pool.map(qrCodeMatrix, strings)
y = pool.map(dataToVector, strings)
X = np.asarray(X)
X = X[..., np.newaxis]
pool.close()
return X, y