import cv2
import numpy as np
import math
from matplotlib import pyplot as plt
# Read image
Irgb = cv2.imread('road.png')
I = Irgb[:,:,0]
# Find the gradient direction
sobelx = cv2.Sobel(I,cv2.CV_64F,1,0,ksize=1)
sobely = cv2.Sobel(I,cv2.CV_64F,0,1,ksize=1)
gradDirection = np.zeros(I.shape, np.float64)
for y in range(I.shape[0]):
for x in range(I.shape[1]):
gradDirection[y, x] = np.float64(math.atan2(sobely[y,x], sobelx[y,x]))
# Iterate on all points and do max suppression
points = np.nonzero(I)
points = zip(points[0], points[1])
maxSuppresion = np.zeros_like(I)
for point in points:
y = point[0]
x = point[1]
# Look at local line along the point in the grad direction
direction = gradDirection[y, x]
pointValues = []
for l in range(-1,2):
yLine = int(np.round(y + l * math.sin(direction)))
xLine = int(np.round(x + l * math.cos(direction)))
if(yLine < 0 or yLine >= maxSuppresion.shape[0] or xLine < 0 or xLine >= maxSuppresion.shape[1]):
continue
pointValues.append(I[yLine,xLine])
# Find maximum on line
maxVal = np.max(np.asarray(pointValues))
# Check if the current point is the max val
if I[y,x] == maxVal:
maxSuppresion[y, x] = 1
else:
maxSuppresion[y, x] = 0
# Remove small areas
im2, contours, hierarchy = cv2.findContours(maxSuppresion,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE )
minArea = 5
maxSuppresionFilter = np.zeros_like(maxSuppresion)
finalShapes = []
for contour in contours:
if contour.size > minArea:
finalShapes.append(contour)
cv2.fillPoly(maxSuppresionFilter, finalShapes, 1)
cv2.imshow('road',maxSuppresionFilter*255)