python - cv2.matchTemplate 在图像中找到错误的模板
问题描述
我正在尝试创建一个程序,该程序知道具有以下功能的图像上的数字:
def img_in_img(big_picture, small_picture, tamper):
big_picture = str(big_picture)
small_picture = str(small_picture)
if os.path.isfile(big_picture) == False or os.path.isfile(small_picture) == False:
return "Image does not exist"
img = cv2.imread(big_picture,0)
templace_loc = small_picture
template = cv2.imread(templace_loc,0)
w, h = template.shape[::-1]
method = cv2.TM_CCOEFF
tamper = int(tamper)
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
height, width, channels = cv2.imread(templace_loc).shape
if int(top_left[0]) < int(height + tamper) and int(top_left[0]) > int(height - tamper) and int(top_left[1]) < int(width + tamper) and int(top_left[1]) > int(width - tamper):
return True
else:
return False
但是当我检查是否7.png
在img.png
代码中时
nur = "7"
if img_in_img("2020-01-14-17-36-08.537043/verification_image2.png", "verifynr/" + "old_orange" + "/" + nur + ".png", 25):
print(Style.BRIGHT + Fore.GREEN + "Color: " + "old_orange" + ", Num: " + nur + Fore.RESET)
else:
print(Style.BRIGHT + Fore.RED + "Color: " + "old_orange" + ", Num: " + nur + Fore.RESET)
它给了我红色:Color: old_orange, Num: 7
但是,如果我通过更改from来检查是否6.png
在其中,它会给我 Green: ,但这是错误的图像。img.png
nur
7
6
Color: old_orange, Num: 6
我还尝试了以下代码:
img_rgb = cv2.imread("2020-01-14-17-36-08.537043/verification_image2.png")
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('verifynr/old_orange/7.png',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_SQDIFF)
threshold = 0.8
loc = np.where( res >= threshold)
pt = list(zip(*loc[::-1]))
if len(pt) >= 1:
print("True")
打印True
,但它为我保存的每个数字 png 执行此操作。
如何让我的程序7.png
在img.png
不识别每个数字 png 的情况下识别 in?
图片.png:
6.png:
7.png:
解决方案
模板匹配不用于物体检测或模式识别,它的功能是找到最相似的补丁位置。对于检测使用检测器(haar,基于 dnn 的检测器,...),对于识别使用分类器(基于描述符或基于 nn)。'
推荐阅读
- xcode - SwifUI:如何根据另一个元素的位置对齐元素的填充值
- python - 我找不到在 python 中比较电子邮件正文的方法,因为某些电子邮件最后包含额外的许可证消息
- ruby-on-rails - 基于jquery sortable更新排名
- ruby-on-rails - 在 Rails 中显示软删除的记录
- mysql - MySQL 匹配基于日期的第一个实例值
- c++ - 当我尝试将范围值存储为 8 位的固定宽度整数时,它会显示一些其他值 [ASCII]
- android - Can a Flutter app be proposed on the Huawei AppGallery?
- python - 无法读取使用 soffice 命令转换 pdf 后得到的 .docx 文件
- python - Sqlalchemy:无法执行同步规则(在多对多关系中)
- arrays - 在 WindowsForm 中使用带有 DisplayArray 方法的泛型