September 22, 2017 byBlue whale LEAVE A COMMENT
This article describes template matching and recognition of images using Python and OpenCV. Template matching is an easy way to find and identify templates in an image. The following are the specific steps and code.
First import the required library files, NumPy and Cv2.
#导入所需库文件Import Cv2 asNP
Then load the original image and the image template to search for. OpenCV processes the original image, creates a grayscale version, processes and finds matches in the grayscale image. The same coordinates are then used to restore and output in the original image.
#加载原始RGB图像img_rgb = Cv2. imread("photo.jpg")#创建一个原始图像的灰度版本, all operations are processed in grayscale versions and then restored Img_gray = Cv2 in the RGB image using the same coordinates. Cvtcolor(Img_rgb, Cv2. Color_bgr2gray) #加载将要搜索的图像模板template = Cv2. Imread(' face.jpg ',0)#记录图像模板的尺寸w, h = template. Shape[::-1]
Here we separately output and view the original image, the grayscale version of the original image, and the image template.
#查看三组图像 (image tag name, file name) Cv2. imshow(' RGB ', Img_rgb) cv2. Imshow(' Gray ', Img_gray) cv2. Imshow(' template ', template) cv2. Waitkey(0) cv2. Destroyallwindows()
Use Matchtemplate to find and match the contents of the image template in the original image and set the threshold value.
#使用matchTemplate对原始灰度图像和图像模板进行匹配res = Cv2. matchtemplate(img_gray,template,cv2. Tm_ccoeff_normed)0.7#res大于70%loc = np. where>= threshold)
The original image is marked with the coordinates of the grayscale image in the original image after the match is complete.
#使用灰度图像中的坐标对原始RGB图像进行标记For PTInchZip(*loc[::-1]): Cv2. Rectangle(Img_rgb, PT, (PT[0] + W, pt[1] + H), (7,249,151< c18>), 2)#显示图像 cv2. Imshow(' detected ', Img_rgb) cv2. Waitkey(0) cv2. Destroyallwindows()
The following is the full code:
def mathc_img(Image,target,value):Import Cv2Import NumPyAs 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 PTInchZip (*loc[::-< span class= "nu0" >1) rectangle (Img_rgb, PT, (Pt[ 0] + W, pt[1 + H (7,249,151 2 Cv2. Imshow ' detected ', Img_rgb Waitkey (0 Destroyallwindows ()
Image=("photo.jpg") target=(' face.jpg ') value=0.9mathc_img(image,target,value )
Read MORE:HTTP://BLUEWHALE.CC/2017-09-22/USE-PYTHON-OPENCV-FOR-IMAGE-TEMPLATE-MATCHING-MATCH-TEMPLATE.HTML#IXZZ5HWAZAIKB
Use PYTHON+OPENCV for image template matching (match template)