2017-09-26 222 views
0

我有兩個面,一個大surface imagePython的OpenCV的:使用matchTemplate

和一個較小的一個enter image description here

我試圖將它們視爲灰度圖像,以適應template matching tutorial這些表面。

我需要更新教程以在x和y中獨立縮放,我已經完成了這個工作,但添加了一個額外的循環。我的代碼是:

import pandas as pd 
import numpy as np 
import cv2 
import matplotlib.pyplot as plt 
import matplotlib.patches as patches 

# If True shows each iteration of the template matching 
Visualise = True 

# Load in image and template 
image = pd.read_excel('TemplateMatching_exampleData.xlsx',sheetname="radial_template").as_matrix().astype(np.float32) 
template = pd.read_excel('TemplateMatching_exampleData.xlsx',sheetname="radial_image").as_matrix().T.astype(np.float32) 

# Save a raw copy of the template 
template_raw = template 

# Rescale the template to approximate the same range in values as the image 
template = template - np.mean(template) 
template = (template/np.max(template)) * np.max(image) 

# Get the height and width of the template 
(tH, tW) = template.shape[:2] 

# initialize the bookkeeping variable to keep track of the matched region 
found = None 

# If visualise = True then initialise the figure to show the iteration 
if Visualise: 
    fig1 = plt.figure() 
    ax1 = fig1.add_subplot(111) 

# loop over the scales of the image 
for scale_width in np.linspace(0.1, 2, 20): 
    for scale_height in np.linspace(0.1, 3, 20)[::-1]: 
     # resize the image according to the scale, and keep track 
     # of the ratio of the resizing 
     resized = cv2.resize(image, (int(image.shape[0] * scale_height), int(image.shape[1] * scale_width))) 
     r_h = image.shape[0]/float(resized.shape[0]) 
     r_w = image.shape[1]/float(resized.shape[1]) 

     # if the resized image is smaller than the template, then break 
     # from the loop 
     if resized.shape[0] < tH or resized.shape[1] < tW: 
      break 

     # apply template matching to find the template in the image 
     result = cv2.matchTemplate(resized, template, cv2.TM_CCOEFF) 
     (_, maxVal, _, maxLoc) = cv2.minMaxLoc(result) 

     # check to see if the iteration should be visualized 
     if Visualise: 
      ax1.clear() 
      ax1.imshow(resized) 
      ax1.add_patch(patches.Rectangle((maxLoc[0], maxLoc[1]), tW, tH, fill=False, edgecolor = 'red')) 
      plt.show() 
      plt.draw() 
      plt.pause(0.05) # fig1.waitforbuttonpress() 

     # if we have found a new maximum correlation value, then update 
     # the bookkeeping variable 
     if found is None or maxVal > found[0]: 
      found = (maxVal, maxLoc, r_w, r_h, scale_width, scale_height) 

# unpack the bookkeeping varaible and compute the (x, y) coordinates 
# of the bounding box based on the resized ratio 
(_, maxLoc, r_w, r_h, scale_width, scale_height) = found 
(startX, startY) = (int(maxLoc[0] * r_w), int(maxLoc[1] * r_h)) 
(endX, endY) = (int((maxLoc[0] + tW) * r_w), int((maxLoc[1] + tH) * r_h)) 

# draw a bounding box around the detected result and display the image 
figure = plt.figure() 
ax1 = figure.add_subplot(111) 
ax1.imshow(image) 
ax1.add_patch(patches.Rectangle((startX,startY), endX-startX, endY-startY, fill=False, edgecolor = 'red')) 
plt.show() 
plt.draw() 

# show the matching image segment and template together 
plt.figure() 
plt.subplot(121) 
plt.imshow(image[startX:endX, startY:endY]) 
plt.title('Image') 
plt.subplot(122) 
plt.imshow(template) 
plt.title('Template') 

但是什麼我發現的是,「最佳組合」是在最大scale_width值總是發現,不管是什麼我將該值設置爲是,但我想不通爲什麼。我猜這是衡量體質如何的結果,但我對cv2.matchTemplate瞭解不多,因此我一直在苦苦思索這幾天。

請你能幫我解決我的代碼嗎?

我已將我的數據從我的Excel文件複製到this GoogleDocs document

+0

1.它可能會更好用標準差(簡單地'numpy.std(陣列)')不僅僅是由最大規模來劃分;通過std dev移動均值和潛水給你一個0均值和單位標準dev的分佈。 2.您應該縮放模板和圖像以獲得相似的分佈。 3.您可以共享Excel數據在公共谷歌片或類似的,或縮放的灰階值恰好浮子0 UINT8 0和1之間或之間和255,並將它們保存爲OpenCV的'imwrite()'和公佈這些灰度圖像爲我們加載。 –

+0

謝謝,我在主帖中添加了數據鏈接 – jlt199

+0

查看電子表格中的值,您是否實際縮放了'image'或僅僅是'template'?因爲由'max'被劃分後,你的模板將有'1',而你的'image'有像一個最大值'10000',所以你不會得到任何接近的比賽的最大值。請嘗試按比例兩者,無論是與標準方差就像我提到的,甚至只是天真地轉移/他們兩個大規模進入0和1,看看你是否得到比賽的方式。因爲否則,只要關閉該教程並擴展您的模板應該會相對較好。 –

回答

2

一個問題開始,你可以解決

所以第一關有一些簿記需要做---似乎imagetemplate以Excel文檔切換,進而似乎template是實際上旋轉了90度。爲了得到工作的東西,我會手動將模板縮放到合適的大小,並確保可以找到模板。請注意,我將每張表導出爲.csv文件並更正了名稱。

此外,我設置圖像的平均值爲零,標準偏差爲1,只需將平均值減去標準偏差即可。這應該使圖像保持大致相同的分佈,以便在原始陣列中沿着高度不同的值進行良好匹配。

import cv2 
import numpy as np 

img = np.genfromtxt('radial_img.csv', delimiter=',').astype(np.float32) 
tmp = np.genfromtxt('radial_tmp.csv', delimiter=',').astype(np.float32) 
tmp = np.rot90(tmp) 
tmp = cv2.resize(tmp, None, fx=0.5, fy=0.33) 

img = (img - np.mean(img))/np.std(img) 
tmp = (tmp - np.mean(tmp))/np.std(tmp) 

ccorr = cv2.matchTemplate(img, tmp, cv2.TM_CCORR) 
tl = cv2.minMaxLoc(ccorr)[3] 
h, w = tmp.shape[:2] 
br = (tl[0]+w, tl[1]+h) 

matched = cv2.normalize(img, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) 
matched = cv2.merge([matched, matched, matched]) 
cv2.rectangle(matched, tl, br, (0, 255, 0)) 
cv2.imshow('matched0.png', matched) 
cv2.waitKey() 

Matched with manual resize

太好了!有用!請注意,這裏的模板實際上非常小,比它應該小一點,但我們仍然有粗略的位置,所以我們知道我們正處在正確的軌道上。

通過多種尺寸

現在,我們只需要創建你做這些循環和多次調整模板,直到我們得到最佳匹配循環。但是請注意,模板匹配的方法都具有與模板大小相關的比例,所以較小的模板將具有較小的誤差。因此,我們需要使用_NORMED方法來確保結果大部分是規模不變的。我認爲使用列表理解來構建所有調整大小的圖像,然後遍歷所有這些圖像更清晰,而不是創建多個for循環。我們可以隨時保存最佳結果,然後在完成後顯示最佳結果。請注意,這裏的所有標準化都嚴格用於可視化;使用OpenCV功能沒有必要:

import cv2 
import numpy as np 

img = np.genfromtxt('radial_img.csv', delimiter=',').astype(np.float32) 
tmp = np.genfromtxt('radial_tmp.csv', delimiter=',').astype(np.float32) 
tmp = np.rot90(tmp) 

img = (img - np.mean(img))/np.std(img) 
tmp = (tmp - np.mean(tmp))/np.std(tmp) 

sz_ranges = np.linspace(0.1, 2.0, 19) 
resized_tmps = [cv2.resize(tmp, None, fx=i, fy=j) 
       for i in sz_ranges for j in sz_ranges] 
n_tmps = len(resized_tmps) 

for rs_tmp, k in zip(resized_tmps, range(n_tmps)): 
    ccorr = cv2.matchTemplate(img, rs_tmp, cv2.TM_CCORR_NORMED) 
    match_val, match_loc = cv2.minMaxLoc(ccorr)[1::2] 
    if k == 0: 
     best_match_val = match_val 
    if match_val > best_match_val: 
     best_match_val = match_val 
     best_match_loc = match_loc 
     best_match = k 

best_match_tmp = resized_tmps[best_match] 
best_match_tmp = cv2.normalize(best_match_tmp, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) 
best_match_tmp = cv2.merge([best_match_tmp, best_match_tmp, best_match_tmp]) 

h, w = best_match_tmp.shape[:2] 
best_match_loc_end = (best_match_loc[0]+w, best_match_loc[1]+h) 
matched = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) 
matched = cv2.merge([matched, matched, matched]) 
cv2.rectangle(matched, best_match_loc, best_match_loc_end, (0, 255, 0)) 

cv2.imshow('matched1.png', matched) 
cv2.waitKey() 

cv2.imshow('besttmp.png', best_match_tmp) 
cv2.waitKey() 

而且,它的工作原理!

Matched after auto-resizing

下面是相匹配的最佳模板:

Best matched template

其中通過目測看起來是正確的。最佳匹配模板的高度和寬度爲(85, 99)這基本上只是有點橫向拉伸的原始模板。

+0

非常感謝,這是我可以要求的最詳細,最有用的答案:D – jlt199