In [2]:
%matplotlib inline
import cv2
import numpy as np
import matplotlib.pyplot as plt

In [3]:
img = cv2.imread('page22.tif')
#img = cv2.cvtColor(img, cv2.cv.CV_BGR2RGB)

In [4]:
board = img[1045:2245, 1858:3058]

In [5]:
plt.imshow(board)


Out[5]:
<matplotlib.image.AxesImage at 0x11099cc10>

In [6]:
def get_cell(x, y):
    x_cell_size = 149
    y_cell_size = 150
    x *= x_cell_size
    y *= y_cell_size
    field = board[y:y+y_cell_size, x:x+x_cell_size]
    plt.imshow(field)
    return field

In [7]:
f = get_cell(0,0)



In [8]:
f = get_cell(7,7)



In [9]:
dark = get_cell(3,4)



In [13]:
black_pawn_on_dark = board[150:300, 0:150]
plt.imshow(black_pawn_on_dark)


Out[13]:
<matplotlib.image.AxesImage at 0x117b221d0>

In [27]:
# Let's try to find all black pawns on dark squares...

_, w, h = black_pawn_on_dark.shape[::-1]
board_copy = board.copy()

res = cv2.matchTemplate(board, black_pawn_on_dark, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    cv2.rectangle(board_copy, pt, (pt[0] + w, pt[1] + h), (0,200,0), 5)

plt.imshow(board_copy)


Out[27]:
<matplotlib.image.AxesImage at 0x1225719d0>

In [26]:
zip(*loc[::-1])


Out[26]:
[(301, 147),
 (600, 147),
 (601, 147),
 (898, 147),
 (899, 147),
 (900, 147),
 (1, 148),
 (2, 148),
 (299, 148),
 (300, 148),
 (301, 148),
 (599, 148),
 (600, 148),
 (601, 148),
 (897, 148),
 (898, 148),
 (899, 148),
 (0, 149),
 (1, 149),
 (2, 149),
 (298, 149),
 (299, 149),
 (300, 149),
 (598, 149),
 (599, 149),
 (600, 149),
 (897, 149),
 (898, 149),
 (0, 150),
 (1, 150),
 (298, 150),
 (299, 150),
 (300, 150),
 (598, 150),
 (599, 150),
 (0, 151),
 (297, 151),
 (298, 151)]

In [ ]: