我一直在关注有关计算机视觉的教程,并做了一个小项目来阅读游戏中的时间。游戏时间的格式为h:m。到目前为止,我已经使用findContours弄清了h和m,但是由于字符形状不是连续的,我很难隔离冒号。因此,当我尝试matchTemplate时,代码会出现异常,并开始使用点匹配所有其他数字。
有没有办法用X对轮廓进行分组?
这里是获取参考数字的简化代码,从屏幕获取数字的代码基本相同。
refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
refCnts = imutils.grab_contours(refCnts)
refCnts = contours.sort_contours(refCnts, method="left-to-right")[0]
digits = {}
# loop over the OCR-A reference contours
for (i, c) in enumerate(refCnts):
# compute the bounding box for the digit, extract it, and resize
# it to a fixed size
(x, y, w, h) = cv2.boundingRect(c)
roi = ref[y:y + h, x:x + w]
roi = cv2.resize(roi, (10, 13))
digits[i] = roi
是python和opencv的新手。如果这是一个愚蠢的问题,请提前道歉。
这是我正在使用的参考图像:
这是我要阅读的输入图像:
您拥有使用findCountours
吗?因为有更好的方法可以解决此类问题。例如,您可以使用template matching,如下所示:
这些是input
,template
(从参考图像切出)和output
图像:
import cv2
import numpy as np
# Read the input image & convert to grayscale
input_rgb = cv2.imread('input.png')
input_gray = cv2.cvtColor(input_rgb, cv2.COLOR_BGR2GRAY)
# Read the template (Using 0 to read image in grayscale mode)
template = cv2.imread('template.png', 0)
# Perform template matching - more on this here: https://docs.opencv.org/4.0.1/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d
res = cv2.matchTemplate(input_gray,template,cv2.TM_CCOEFF_NORMED)
# Store the coordinates of matched area
# found the threshold value of .56 using trial & error using the input image - might be different in your game
lc = np.where( res >= 0.56)
# Draw a rectangle around the matched region
# I used the width and height of the template image but in practice you need to use a better method to accomplish this
w, h = template.shape[::-1]
for pt in zip(*lc[::-1]):
cv2.rectangle(input_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 1)
# display output
cv2.imshow('Detected',input_rgb)
# cv2.imwrite('output.png', input_rgb)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
您也可以研究使用openCV进行文本检测和识别。