Created
January 3, 2017 07:44
-
-
Save lotabout/c3240290fd18ee232a8b1ff33ec93cd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
# -*- coding: utf-8 -*- | |
from PIL import Image | |
def chunks(l, n): | |
"""Yield successive n-sized chunks from l.""" | |
for i in range(0, len(l), n): | |
yield l[i:i + n] | |
def run_length_encode(array): | |
"""[0, 0, 1, 1, 1, 0, 0] => [2, 3, 2]""" | |
ret = [1] | |
for (pre, cur) in zip(array, array[1:]): | |
if pre == cur: | |
ret[-1] += 1 | |
else: | |
ret.append(1) | |
return ret | |
def marker_num(encodings): | |
"""calculate how many black/white pairs are there | |
Allow 20 percent mistake""" | |
max_num = 0 | |
num = 0 | |
for (pre, cur) in zip(encodings, encodings[1:]): | |
if abs(cur - pre) / (1.0 * pre) - 0.2 <= 0: | |
num += 1 | |
else: | |
max_num = max(max_num, num) | |
num = 0 | |
return max_num | |
class QRCode(object): | |
"""docstring for QRCode""" | |
def __init__(self, filename): | |
super(QRCode, self).__init__() | |
self.img = Image.open(filename).convert('L') | |
data = [0 if pixel < 127 else 255 for pixel in self.img.getdata()] | |
self.data = list(chunks(data, self.img.size[0])) | |
def is_qrcode(self): | |
marker_nums_row = [marker_num(run_length_encode(row)) for row in self.data] | |
# QRCode requires at least 14 chunks | |
return any([num >= 14 for num in marker_nums_row]) | |
import sys | |
import shutil | |
if __name__ == '__main__': | |
for filename in sys.argv[1:]: | |
is_qrcode = QRCode(filename).is_qrcode() | |
if is_qrcode: | |
shutil.move(filename, './qrcodes') | |
print '{} : {}'.format(filename, "QRCode") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment