在待識別圖像上找到模板圖像
待識別圖像:
模板圖像:
識別原理
1. 將待識別圖像 -> 灰度圖像 -> 二值圖像
2. 通過輪廓檢索函數 cv.findContours 找到待識別圖像所有輪廓
3. 模板圖像 -> 灰度圖像 -> 二值圖像
4. 通過輪廓檢索函數 cv.findContours 找到模板圖像中字母 A 的外輪廓
5. 將第2步得到的輪廓逐一和第4步得到的輪廓 通過 cv.matchShapes 函數進行形狀匹配。找到其中最小值,最小值對應的待識別圖像中的輪廓即為匹配到的模板圖像
6. 標出在待識別圖像中找到的模板圖像
實驗:圖像匹配
import cv2 as cv
import numpy as np
# 載入原圖
img = cv.imread('abc.jpg', 0)
# 在下面這張圖像上作畫
image1 = cv.cvtColor(img,cv.COLOR_GRAY2BGR)
# 二值化圖像
_, thresh = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# 搜索輪廓
contours, hierarchy = cv.findContours(thresh, 3, 2)
hierarchy = np.squeeze(hierarchy)
# 載入標准模板圖
img_a = cv.imread('template_a.jpg', 0)
_, th = cv.threshold(img_a, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
contours1, hierarchy1 = cv.findContours(th, 3, 2)
# 字母A的輪廓
template_a = contours1[0]
# 記錄最匹配的值的大小和位置
min_pos = -1
min_value = 2
for i in range(len(contours)):
# 參數3:匹配方法;參數4:opencv預留參數
value = cv.matchShapes(template_a,contours[i],1,0.0)
if value < min_value:
min_value = value
min_pos = i
# 參數3為0表示繪制本條輪廓contours[min_pos]
cv.drawContours(image1,[contours[min_pos]],0,[255,0,0],3)
cv.imshow('result',image1)
cv.waitKey(0)
cv.destroyAllWindows()