模板匹配
膜版匹配不能匹配尺度变换和视角变换的图像
 图片中查找和模板相似度最高的图像
 计算相似程度最高的位置
 res = cv.matchTemplate(img , template, method)
 该方法返回一个类似灰度图的东西,如果用的相关匹配,那么亮的地方就是可能匹配上的地方
 img图像template模板
 method
- 平方差匹配CV_TM_SQDIFF 模板与图像的平方差进行匹配,最好的匹配是0,匹配越差值越大
 - 相关匹配CV_TM_CCORR 模板与图像乘法进行匹配,数值越大表示匹配程度越高
 - 相关系数匹配CV_TM_CCOEFF 模板与图像相关系数匹配,1表示完美匹配,-1表示最差匹配
 
cv.minMaxLoc()查找最大值/最小值位置即可
 该方法返回最小值,最大值,最小值位置(数列),最大值位置(数列)
img = cv.imread....
template = cv.read...
res = cv.matchTemplate(img, template, CV_TM_CCORR)
minval,maxval,minloc,maxloc = cv.minMaxLoc(res)
top_left = maxloc  # 匹配位置方框的左上角就是maxloc返回的位置,因为使用的是相关匹配
h,w = template.shape[:2]
bottom_right = (top_left[0]+w,top_left[1]+h)
cv.rectangle(img,top_left,bottom_right,(0,255,0),2) #绘制方框 绿色线框宽度为2 
 
霍夫变换
用于提取直线和圆的形状
霍夫直线检测

 
 cv.HoughLines(edges,rho,theta)
 edges一般为灰度且进行过canny边缘化的灰度图像
- rho:以像素为单位的距离精度。
 - double类型的theta:以弧度为单位的角度精度
 
返回的是一个array型数组,每一个元素都是一组rho,theta
import matplotlib.pyplot as plt
import cv2 as cv
import numpy as np
img = cv.imread("/Users/liruiyan/Downloads/IMG_9534.jpg")
plt.subplot(2, 2, 1)
plt.title("origin")
plt.axis("off")
plt.imshow(img[:, :, ::-1])
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
plt.subplot(2, 2, 2)
plt.title("convert_gray")
plt.axis("off")
plt.imshow(gray, cmap=plt.cm.gray)
edges = cv.Canny(gray, 50, 150)
plt.subplot(2, 2, 3)
plt.axis("off")
plt.title("canny_edges")
plt.imshow(gray, cmap=plt.cm.gray)
lines = cv.HoughLines(edges, 0.6, np.pi/180, 250)
# 返回的lines是一个关于rho,theta的一个array,每一个[rho,theta]都是霍夫空间内一个关于直线的描述
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    
    # 计算延伸的直线起点和终点
    x1 = int(x0 + 10000*(-b))
    x2 = int(x0 - 10000*(-b))
    y1 = int(y0 + 10000 * a)
    y2 = int(y0 - 10000 * a)
    cv.line(img, (x1, y1), (x2, y2), (0, 255, 0), 10)
plt.subplot(2, 2, 4)
plt.title("result")
plt.imshow(img[:, :, ::-1])
plt.axis("off")
plt.show()
plt.imshow(img[:, :, ::-1])
plt.figure(figsize=(10, 8), dpi=200)
plt.show()
 
霍夫圆检测
霍夫圆对噪声比较敏感,要进行中值滤波
 cv.HoughCircles(img, method ,dp, minDist, param1, param2, minRadius, maxRadius)
 img:输入图像,灰度图像
 method :霍夫圆检测算法:CV_HOUGH_GRADIENT
 dp:霍夫空间分辨率,1表示和原图一致,2表示为原图一半
 minDist:圆心之间最小距离 ,两圆心如果小于该值,视为同一个圆
 param1
 param2
 minRadius,maxRadius:要检测的圆半径的最小值和最大值


















