import cv2 as cv
import numpy as np
#将图像复制一份并转为灰度图
img = cv.imread("zebra.jpg")
img_copy = img.copy()
img_copy = cv.resize(img_copy,(640,480))
gray = cv.cvtColor(img_copy,cv.COLOR_BGR2GRAY)
#模糊去噪与二值化
img_Blur = cv.GaussianBlur(gray,(5,5),10)
ret,thresh = cv.threshold(img_Blur,150,255,cv.THRESH_BINARY)
#形态学腐蚀与膨胀
img_Ero = cv.erode(thresh,np.ones((3,1),np.uint8),iterations=3)
img_Dila = cv.dilate(img_Ero,np.ones((5,1),np.uint8),iterations=1)
#cv.imshow("TH",thresh)
#cv.imshow("Blur",img_Blur)
#cv.imshow("Ero",img_Ero)
#cv.imshow("Dila",img_Dila)
#cv.waitKey(0)
#绘制
contouts,h = cv.findContours(img_Dila,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
cnt = contouts
for i in cnt:
x,y,w,h = cv.boundingRect(i)
print(x,y,w,h)
if y>240 and w>35 and h>10:
zeb=cv.drawContours(img_copy,i,-1,(0,255,0),3)
cv.imshow('zebra',zeb)
cv.waitKey(0)
测试用图:
二值化效果:
腐蚀/膨胀处理后效果:
可以通过调整x,y限制斑马线范围。
最终效果: