OPenCV 养成计划——边缘检测、图像金字塔轮廓检测 03

4.双阈值

梯度值>maxVal 处理为边界

minVal<梯度值<maxVal:连有边界保留,否则舍弃

梯度值<minVal 舍弃

v1=cv2.Canny(img,80,150)#80为minVal,150为maxVal,两个值越小会显示越多的边界细节

2.图像金字塔(图像特征提取,每一层特征不一样)

2.1高斯金字塔

向下采样法(缩小),向上走(1)与高斯内核卷积(2) 将所有偶数行和列去除

向上采样法(放大),向下走(1)将图像向每个方向 扩大两倍,以0为填充(2)相同内积和进行卷积

up=cv2.pyrUp(img)
down=cv2.pyrDown(img)

2.2拉普拉斯金字塔

3.图像轮廓检测(轮廓比边缘更加连续)

cv.findContours(img,mode,methd)

mode:
轮廓检索方式

method:轮廓逼近方法 

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
binary,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
draw_img=img.copy()
res=cv2.drawContours(draw_img,contours,-1,(0,0,255),2)#2为线条宽度,(0,0,255)BGR用红色来画,在img上画出contours,-1表示所有轮廓,可以取1,2等层轮廓

##轮廓近似
grat=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh=cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
binary,contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
draw_img=img.copy()
cat=contours[0]
epsilon=0.15*cv2.arcLength(cat,True)
approx=cv2.approxPolyDP(cat,epsilon,True)
res=cv2.drawContours(draw_img,[approx],-1,(0,0,255),2)

4.模板匹配

template=cv2.imread("模板路径",0)
w,h=template.shape[:2]
res=cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
threshold=0.8
loc=np.where(res>=threshold)
for pt in zip(*loc[::-1]):
    bottom_right=(pt[0]+w,pt[1]+h)
    cv2.rectangle(img,pt,bottom_right,(0,0,225),2)
发布了35 篇原创文章 · 获赞 4 · 访问量 2338

猜你喜欢

转载自blog.csdn.net/devilangel2/article/details/104177459