2017年9月22日 BY
本篇文章介紹使用Python和OpenCV對圖像進行模板匹配和識別。模板匹配是在圖像中尋找和識別模板的一種簡單的方法。以下是具體的步驟及代碼。
首先導入所需庫文件,numpy和cv2。
#導入所需庫文件
import cv2 import numpy as np
然后加載原始圖像和要搜索的圖像模板。OpenCV對原始圖像進行處理,創建一個灰度版本,在灰度圖像里進行處理和查找匹配。然后使用相同的坐標在原始圖像中進行還原並輸出。
#加載原始RGB圖像
img_rgb = cv2.imread("photo.jpg") #創建一個原始圖像的灰度版本,所有操作在灰度版本中處理,然后在RGB圖像中使用相同坐標還原 img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) #加載將要搜索的圖像模板 template = cv2.imread('face.jpg',0) #記錄圖像模板的尺寸 w, h = template.shape[::-1]
這里我們分別輸出並查看原始圖像,原始圖像的灰度版本,以及圖像模板。
#查看三組圖像(圖像標簽名稱,文件名稱)
cv2.imshow('rgb',img_rgb) cv2.imshow('gray',img_gray) cv2.imshow('template',template) cv2.waitKey(0) cv2.destroyAllWindows()
使用matchTemplate在原始圖像中查找並匹配圖像模板中的內容,並設置閾值。
#使用matchTemplate對原始灰度圖像和圖像模板進行匹配
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) #設定閾值 threshold = 0.7 #res大於70% loc = np.where( res >= threshold)
匹配完成后在原始圖像中使用灰度圖像的坐標對原始圖像進行標記。
#使用灰度圖像中的坐標對原始RGB圖像進行標記
for pt in zip(*loc[::-1]): cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2) #顯示圖像 cv2.imshow('Detected',img_rgb) cv2.waitKey(0) cv2.destroyAllWindows()
以下為完整代碼:
def mathc_img(image,Target,value): import cv2 import numpy as np img_rgb = cv2.imread(image) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(Target,0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) threshold = value loc = np.where( res >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7,249,151), 2) cv2.imshow('Detected',img_rgb) cv2.waitKey(0) cv2.destroyAllWindows()
image=("photo.jpg") Target=('face.jpg') value=0.9 mathc_img(image,Target,value)








