<p>您可以采取的一种方法是从所有瓷砖都为空的快照中获取此帧的差异。这将以最少的计算得到所需的掩码。在</p>
<p>由于您在问题中没有提到您可以访问所有空的tile快照,所以我还将介绍另一种称为<code>color segmentation</code>的技术。由于背景颜色是一致的,但是编号的色块会发生变化,因此我们将首先分割出背景,然后反转遮罩以找到轮廓,如下所示:</p>
<pre><code>import cv2
import numpy as np
def threshold_tiles(board_img):
board_bgd_color_low = np.array([155, 170, 140])
board_bgd_color_high = np.array([200, 185, 195])
board_empty_low = np.array([175, 180, 200])
board_empty_high = np.array([185, 195, 210])
mask_bgd = cv2.inRange(board_img, board_bgd_color_low, board_bgd_color_high)
mask_tile = cv2.inRange(board_img, board_empty_low, board_empty_high)
mask = cv2.max(mask_bgd, mask_tile)
kernel = np.ones((7, 7), np.uint8)
mask = cv2.dilate(mask, kernel)
return ~mask
def get_box_contours(mask):
_, cnt, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnt = filter(lambda x:cv2.contourArea(x) > 100, cnt)
return cnt
def main():
game_snapshot = cv2.imread("/path/to/img.jpg")
# Crop the white borders
game_snapshot = game_snapshot[5:-5, 5:-5]
mask = threshold_tiles(game_snapshot)
contours = get_box_contours(mask)
for i in xrange(len(contours)):
cv2.drawContours(game_snapshot, contours, i, (0, 255, 0), 3)
cv2.imwrite("output.png", game_snapshot)
if __name__ == "__main__":
main()
</code></pre>
<h2>中间遮罩:</h2>
<p><a href="https://i.stack.imgur.com/z25xL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z25xL.png" alt="enter image description here"/></a>+<a href="https://i.stack.imgur.com/18gMv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/18gMv.png" alt="enter image description here"/></a>=<a href="https://i.stack.imgur.com/GTcmU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GTcmU.png" alt="enter image description here"/></a></p>
<h2>轮廓的最终遮罩:</h2>
<p><a href="https://i.stack.imgur.com/94ihm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/94ihm.png" alt="enter image description here"/></a></p>
<p>输出:</p>
<p><a href="https://i.stack.imgur.com/TM4zo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TM4zo.png" alt="enter image description here"/></a></p>