import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
1.模板匹配
wulin = cv.imread('img/wulin.jpeg')
template = cv.imread('img/bai.jpeg')
res = cv.matchTemplate(wulin,template,cv.TM_CCORR)
plt.imshow(res,cmap=plt.cm.gray)
<matplotlib.image.AxesImage at 0x24d7c137af0>
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(res)
top_left = max_loc
h,w = template.shape[:2]
bottom_right = (top_left[0]+w,top_left[1]+h)
res = cv.rectangle(wulin,top_left,bottom_right,(0,255,0),2)
plt.imshow(res[:,:,::-1])
<matplotlib.image.AxesImage at 0x24d7cc2ccd0>
2.霍夫变换
2.1霍夫线检测
rili = cv.imread('img/rili.jpg')
edges = cv.Canny(rili,50,150)
plt.imshow(edges,cmap=plt.cm.gray)
<matplotlib.image.AxesImage at 0x24d7c177640>
lines = cv.HoughLines(edges,0.8,np.pi/180,150)
for line in lines:
rho,theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = rho * a
y0 = rho * b
x1 = int(x0+1000*(-b))
y1 = int(y0+1000*a)
x2 = int(x0-1000*(-b))
y2 = int(y0-1000*a)
cv.line(rili,(x1,y1),(x2,y2),(0,255,0))
plt.imshow(rili[:,:,::-1])
<matplotlib.image.AxesImage at 0x24d7f021c70>
2.2霍夫圆检测
star = cv.imread('img/star.jpeg')
gray_star = cv.cvtColor(star,cv.COLOR_BGR2GRAY)
img = cv.medianBlur(gray_star,7)
plt.imshow(img,cmap=plt.cm.gray)
<matplotlib.image.AxesImage at 0x24d7efc20d0>
circles = cv.HoughCircles(img,cv.HOUGH_GRADIENT,1,200,param1=100,param2=50,minRadius=0,maxRadius=200)
circles
array([[[494.5, 820.5, 71.7],
[494.5, 596.5, 71.3],
[221.5, 370.5, 72. ],
[221.5, 596.5, 71.2],
[773.5, 820.5, 71.6],
[494.5, 371.5, 71.6],
[773.5, 369.5, 70.7],
[220.5, 820.5, 71.5],
[774.5, 594.5, 70.6],
[362.5, 145.5, 64.5],
[632.5, 138.5, 63.3]]], dtype=float32)
for c in circles[0,:]:
cv.circle(star,(int(c[0]),int(c[1])),int(c[2]),(0,255,0),2)
cv.circle(star,(int(c[0]),int(c[1])),2,(255,0,0),-1)
plt.figure(dpi=400)
plt.imshow(star[:,:,::-1])
<matplotlib.image.AxesImage at 0x24d7f0361f0>
总结
|