-
Notifications
You must be signed in to change notification settings - Fork 1
/
board_splitter.py
executable file
·95 lines (76 loc) · 2.42 KB
/
board_splitter.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
#!/usr/bin/env python
# encoding: utf-8
#
# Python 2/3 compatibility
from __future__ import print_function
import os, sys, cv2
import numpy as np
import json
import datetime
now = datetime.datetime.now()
suffix = now.strftime( '%Y-%m-%d_%H%M' )
def save_square( base, num, square ) :
'''
create a file name from base name and save the square
'''
folder = 'squares_%s' % suffix
if not os.path.isdir(folder) :
os.mkdir( folder )
name = os.path.join( folder, '%s_board_%d.png' % (base, num))
print( 'saving square', name )
cv2.imwrite( name, square )
def is_empty( square ) :
average = np.mean( square[2:-2, 2:-2] )
if average > 240 :
return True # white square
# now checking black square to be uniform
center = np.mean( square[ 10:-10, 10:-10 ] )
#print( 'average: %.2f center: %.2f' % (average, center) )
return abs( average - center ) < 3
if __name__ == '__main__':
if len(sys.argv) < 2 :
sys.exit('Need an argument: ./board_splitter.py FOLDER')
for pages in sys.argv[1:] :
if not os.path.isdir(pages) :
sys.exit('Not a folder or does not exist: ' + folder)
r, d, files = os.walk(pages).next()
for f in files :
#f = 'dee3ed3205b763ac0ad29cf218b93810-120.png'
#f = '4e53bead1775de509de92091ab72a583-57.png'
print( f )
name = os.path.join( r, f )
base = f.split('/')[-1].split('.')[0]
img = cv2.imread( name )
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
offset = 5
size_x = img.shape[0] - offset*2
size_y = img.shape[1] - offset*2
for i in range(9) :
start_point = (0, offset + i*size_x / 8)
end_point = (img.shape[1], offset + i*size_x / 8)
cv2.line( img, start_point, end_point, (0, 255, 0), 1 )
start_point = (offset + i*size_y / 8, 0)
end_point = (offset + i*size_y / 8, img.shape[0])
cv2.line( img, start_point, end_point, (0, 0, 255), 1 )
empty_count = 0
for i in range(8) :
for j in range(8) :
left = offset + i*size_y/8
right = offset + (i+1)*size_y/8
top = offset + j*size_x/8
bottom = offset + (j+1)*size_x/8
square = gray[top:bottom, left:right]
empty = is_empty( square )
if empty :
empty_count += 1
empty_count &= 31
if empty_count == 0 or not empty :
save_square( base, i*8+j, square )
#print( np.mean( square ), is_empty(square), end = '')
print()
#cv2.imshow('squares', cv2.pyrUp(img))
#ch = cv2.waitKey() & 0xFF
#if ch == 27:
# break
#break
cv2.destroyAllWindows()