资源简介
python-OpenCV实现边缘模板匹配算法。介绍一种新的模板匹配算法,主要是基于图像边缘梯度,它对图像光照与像素迁移都有很强的抗干扰能力
代码片段和文件信息
# -*- coding: utf-8 -*-
“““
OpenCV实现边缘模板匹配算法
This is a temporary script file.
“““
import numpy as np
import cv2
import time
import matplotlib.pyplot as plt
class GeoMatch:
def __init__(self):
self.noOfCordinates=0 # 坐标数组中元素的个数
self.cordinates = [] # 坐标数组存储模型点
self.modelHeight=0 # 模型高
self.modelWidth=0 # 模型宽
self.edgeMagnitude = [] # 梯度大小
self.edgeDerivativeX = [] # 在X方向的梯度
self.edgeDerivativeY = [] # 在Y方向的梯度
self.centerOfGravity = [] # 模板重心
self.modelDefined=0
def CreateGeoMatchModel(self templateArr maxContrast minContrast):
Ssize = []
src = templateArr.copy()
# 设置宽和高
Ssize.append(src.shape[1]) # 宽
Ssize.append(src.shape[0]) # 高
self.modelHeight = src.shape[0] # 存储模板的高
self.modelWidth = src.shape[1] # 存储模板的宽
self.noOfCordinates = 0 # 初始化
self.cordinates = [] #self.modelWidth * self.modelHeight # 为模板图像中选定点的联合分配内存
self.edgeMagnitude = [] # 为选定点的边缘幅度分配内存
self.edgeDerivativeX = [] # 为选定点的边缘X导数分配内存
self.edgeDerivativeY = [] # 为选定点的边缘Y导数分配内存
## 计算模板的梯度
gx = cv2.Sobel(src cv2.CV_32F 1 0 3)
gy = cv2.Sobel(src cv2.CV_32F 0 1 3)
MaxGradient = -99999.99
orients = []
nmsEdges = np.zeros((Ssize[1] Ssize[0]))
magMat = np.zeros((Ssize[1] Ssize[0]))
for i in range(1 Ssize[1]-1):
for j in range(1 Ssize[0]-1):
fdx = gx[i][j] # 读x y的导数值
fdy = gy[i][j]
MagG = (float(fdx*fdx) + float(fdy * fdy))**(1/2.0) # Magnitude = Sqrt(gx^2 +gy^2)
direction = cv2.fastAtan2(float(fdy) float(fdx)) # Direction = invtan (Gy / Gx)
magMat[i][j] = MagG
if MagG > MaxGradient:
MaxGradient = MagG # 获得最大梯度值进行归一化。
# 从04590135得到最近的角
if (direction > 0 and direction < 22.5) or (direction > 157.5 and direction < 202.5) or (direction > 337.5 and direction < 360):
direction = 0
elif (direction > 22.5 and direction < 67.5) or (direction >202.5 and direction <247.5):
direction = 45
elif (direction >67.5 and direction < 112.5) or (direction>247.5 and direction<292.5):
direction = 90
elif (direction >112.5 and direction < 157.5) or (direction>292.5 and direction<337.5):
direction = 135
else:
direction = 0
orients.append(int(direction))
count = 0 # 初始化count
# 非最大抑制
for i in range(1 Ssize[1]-1):
for j in range(1 Ssize[0] - 1):
if orients[count] == 0:
leftPixel = magMat[i][j- 1]
rightPixel = magM
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 42793 2010-07-06 12:20 Template Matching\Search1.jpg
文件 83167 2010-07-06 12:21 Template Matching\Search2.jpg
文件 13068 2020-05-27 22:15 Template Matching\Template Matching.py
文件 8465 2010-07-06 12:21 Template Matching\Template.jpg
目录 0 2020-05-27 22:24 Template Matching
----------- --------- ---------- ----- ----
147493 5
- 上一篇:预训练数据VGG_imagenet.npy
- 下一篇:商品管理系统python
评论
共有 条评论