案例© Fu Xianjun. All Rights Reserved.
一:导包
import cv2
import numpy as np
二:定义边缘检测函数和感兴趣区域函数
def canny(image):
blur = cv2.GaussianBlur(image,(5,5),0)#降低噪点
canny = cv2.Canny(blur,50,150) #边缘检测
return canny
def region_of_interest(image):#应用遮罩
height = image.shape[0]
ploygons = np.array([[(200,height),(1100,height),(550,250)]])
mask = np.zeros_like(image) #生成一个和img.shape相同的全0
数组
cv2.fillPoly(mask,ploygons,255) #填充多边形
return mask
三:导图
image = cv2.imread('test_image.jpg',0)
imgcopy = image.copy()
四:图片处理
lane_image = np.copy(image)
canny = canny(lane_image)
roi = region_of_interest(canny) #ROI
masked_image = cv2.bitwise_and(image,roi)#通过 bitwise_and 对两个图像的每一个像素做与运算,来将遮罩应用图像
ret, thresh = cv2.threshold(masked_image, 130, 145, cv2.THRESH_BINARY) #图像阈值化
lines = cv2.HoughLinesP(thresh, 1, np.pi/180, 30, maxLineGap=200) #霍夫直线检测
四:画图
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(imgcopy, (x1, y1), (x2, y2), (255, 0, 0), 3) #绘制图像
cv2.imshow('image',imgcopy)
cv2.waitKey(0)
cv2.destroyAllWindows()
原图
效果图