OpenCV Pawn Chess棋子没有检测到?

时间:2018-09-28 18:20:16

标签: python python-3.x opencv object-detection chess

我在检测棋子白色棋子时遇到麻烦。这有点奇怪,因为它每隔两秒就检测一次白色典当。如果我播放未检测到的棋子,就会被检测到。

这就是我之所以在Stackoverflow中进行询问的原因,因为我找不到任何帮助或无法向自己解释。

常规信息: 我在Lichess玩所有默认设置和样式。我的白色典当图片也是透明的白色png文件(50像素x 50像素)。 阈值是0.6,因为我得到了最好的结果。如果减少数量,则检测到的白色典当数量会减少;如果增加数量,则会检测到的黑卒子数量。

# Standard settings
img_rgb = cv2.cvtColor(original_img,cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)

# White Pawn Template
pawn_white_template = cv2.imread("chess_pieces_template/pawn_white.png",0)

w_pawn_white, h_pawn_white = pawn_white_template.shape[::-1]

res_pawn_white = cv2.matchTemplate(img_gray,pawn_white_template,cv2.TM_CCOEFF_NORMED)

threshhold = 0.6
loc = np.where(res_pawn_white >= threshhold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb,pt,(pt[0]+w_pawn_white, pt[1]+h_pawn_white),(0,255,255),1)

cv2.imshow('detected',img_rgb)

Picture of the result detected Window

Template of White Pawn

我希望你们能帮助我。如果您需要任何其他信息,请问我。

最好的问候

Tobias

1 个答案:

答案 0 :(得分:0)

我已经下载了您的图片并对其进行了编辑以删除黄色方块,并用油漆完成了自己的模板(请不要判断我)。然后,我尝试了您的代码,效果很好。很难说出为什么它在您的情况下不起作用,但是如果我想我不得不说它与您的模板有关。当您说自己有透明的png图片时,是否表示它完全透明(甚至在黑色边框内)还是只是周围?如果第一种情况是正确的,请尝试制作一个模板,该模板的中间与原始图像一样填充白色像素。

您的代码:

import cv2
import numpy as np

img = cv2.imread('pawn.png')

# Standard settings
img_rgb = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)

# White Pawn Template
pawn_white_template = cv2.imread("pawn_white2.png",0)

w_pawn_white, h_pawn_white = pawn_white_template.shape[::-1]

res_pawn_white = cv2.matchTemplate(img_gray,pawn_white_template,cv2.TM_CCOEFF_NORMED)

threshhold = 0.6
loc = np.where(res_pawn_white >= threshhold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb,pt,(pt[0]+w_pawn_white, pt[1]+h_pawn_white),(0,255,255),1)

cv2.imshow('detected',img_rgb)

结果:

enter image description here

我的原始img:

enter image description here

我的模板:

enter image description here