有多种裁剪图像的方法,也有多种使用opencv匹配模板的方法。
但是有什么办法可以同时使用它来获得最大相似度的图像?这样,两个图像就会以最小的差异重叠。
模板制作代码:
from PIL import Image
import numpy as np
import cv2
path = './Image_1.png'
org = cv2.imread(path)
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
# print (len(approx))
if len(approx)==5:
# print "pentagon"
cv2.drawContours(img,[cnt],0,255,-1)
elif len(approx)==3:
# print "triangle"
cv2.drawContours(img,[cnt],0,(0,255,0),-1)
elif len(approx)==4:
# print "square"
cv2.drawContours(img,[cnt],0,(0,0,255),-1)
elif len(approx) == 9:
# print "half-circle"
cv2.drawContours(img,[cnt],0,(255,255,0),-1)
elif len(approx) > 15:
# print "circle"
cv2.drawContours(img,[cnt],0,(0,255,255),-1)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
roi_1 = org[y:y+h, x:x+w] # crop image
# dst = cv2.create(roi.size(), CV_8UC3)
print (roi_1.shape)
cv2.imwrite('./test/Image_crop.jpg', roi_1) # color org. image
# cv2.imshow('img',roi)
# cv2.imshow('img_1',img)
# cv2.waitKey(0)
cv2.imshow('img_2',roi_1)
cv2.waitKey(0)
制作两个模板后:
模板匹配代码:
import numpy as np
import cv2
image = cv2.imread('./Image_1.png')
template = cv2.imread('./Image_2.jpg')
# resize images
image = cv2.resize(image, (0,0), fx=0.5, fy=0.5)
template = cv2.resize(template, (0,0), fx=0.5, fy=0.5)
# Convert to grayscale
imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
templateGray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# Find template
result = cv2.matchTemplate(imageGray,templateGray, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
h,w = templateGray.shape
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image,top_left, bottom_right,(0,0,255),1)
# Show result
cv2.imshow("Template", template)
cv2.waitKey(0)
cv2.imshow("Result", image)
cv2.waitKey(0)
这是制作模板然后与之匹配的代码,但是如果我们要制作两个相同的模板,且它们具有使用相机捕获的同一对象的99%匹配,该怎么办。
任何为最大相似度的相同对象的两个图像制作模板的解决方案吗?
在其他作品中,我想制作彼此相同的模板,它们也是相同的?
图片1: Image 1
图片2: Image 2
接受的输出: Accepted output
差异后的输出:
谢谢。