Challenge

Project 4

Hough Transfomation

This project explains in details the hough transformation on image grabbed

# Import the required libraries to perform operations required for edge detectionand transformation
import cv2 # import open CV
import numpy as np

# Apply canny edge detection on the image loaded
def convert2canny_image(image):
#convert colour image to grayscale image
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

#remove noise from image
blurred_image = cv2.GaussianBlur(gray_image,(5,5),0)

#detect intensity gradient in image
canny_image = cv2.Canny(blurred_image,50,150)

return canny_image # return canny image

'''this function to ensure that Hough functions sees only what is relevant to it
# this function takes
image on which masking to be applied
'''

def region_of_interest(image):
#extract height of image to define region of interest
height = image.shape[0]

#define region of interest
triangle = np.array([[(200,height),(1100,height),(550,250)]])

#creating black image
black_image = np.zeros_like(image)

#creating mask-- 255 is white color lines
mask = cv2.fillPoly(black_image,triangle,255) # overlap the triangular roi over black area created of size of image

#applying mask on original image
masked_image = cv2.bitwise_and(image,mask) # consiider only part of image that falls in mask as we need lane details of road

return masked_image

#display lines over a image
def display_lines(image,lines):
line_image = np.zeros_like(image) #black image
if lines is not None:
for line in lines:
x1,y1,x2,y2 = line.reshape(4) #converting to 1d array []
#draw line over black image --(0,0,255) tells we want to draw red line (b,g,r) values
#10 is line thickness
cv2.line(line_image,(x1,y1),(x2,y2),(0,0,255),10)
return line_image

def get_smooth_lines(image,lines):
left_fit = [] #will hold m,c parameters for left side lines
right_fit = [] #will hold m,c parameters for right side lines

for line in lines:
x1,y1,x2,y2 = line.reshape(4)
#polyfit gives slope(m) and intercept(c) values from input points
#last parameter 1 is for linear..so it will give linear parameters m,c
parameters = np.polyfit((x1,x2),(y1,y2),1)
slope = parameters[0]
intercept = parameters[1]

if slope < 0:
left_fit.append((slope,intercept))
else:
right_fit.append((slope,intercept))

#take averages of all intercepts and slopes separately and get 1 single value for slope,intercept
#axis = 0 means vertically(row,column)...so row is always 0 position.
#so axis 0 means over row(vertically)
left_fit_average = np.average(left_fit,axis = 0)
right_fit_average = np.average(right_fit,axis = 0)

#now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters
left_line = get_linecoordinates_from_param(image,left_fit_average)
right_line = get_linecoordinates_from_param(image,right_fit_average)
return np.array([left_line,right_line])

def get_linecoordinates_from_param(image,line_parameters):
slope = line_parameters[0]
intercept = line_parameters[1]
y1 = image.shape[0] #since line willl always start from bottom of image
y2 = int(y1*(3/5)) #some random point at 3/5
x1 = int((y1-intercept)/slope)
x2 = int((y2-intercept)/slope)
return np.array([x1,y1,x2,y2])

'''This section of code does following:
1. reads the video
2. finds total number of frame in video using its metadata and confirms we have valid number of frames
3. check grabbed frame number to ensure we have capture all the frames
4. passs the grabbed image from video for canny edge detection
5. overlay the mask on image after canny edge detection applied
6. find probabilistic hough transformation
7. overlay the hough lines on grabbed frame of video
8. loop through to grab all the frame and perform steps 1 through 7 on all grabbed frames
9. save the the hough transformed images in form of video

'''
#video input
cap = cv2.VideoCapture("test_video.mp4")

writer = None #Initialize video writer

# try to determine the total number of frames in the video file
try:
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print("[INFO] {} total frames in video".format(total_frames))
except:
# an error occurred while trying to determine the total number of frames in the video file
print("[INFO] could not determine # of frames in video")
print("[INFO] no approx. completion time can be provided")
total = -1

currentFrameNumber = 1

try:
while(cap.isOpened()):
(grabbed, frame) = cap.read()

# if the frame was not grabbed, then we have reached the end of the stream
# if not grabbed:
# break
#break if current frame count exceeds total count
# if(currentFrameNumber > total_frames):
# break

#break if q from keyboard is read
# if(cv2.waitKey(1) == ord('q')):
# break

print("Grabbed frame.....{}".format(currentFrameNumber))


canny_image = convert2canny_image(frame)

masked_image = region_of_interest(canny_image)
#find probabilistic Hough line
lines = cv2.HoughLinesP(masked_image,6,np.pi/180,60,np.array([]),minLineLength = 50,maxLineGap = 150)

lines_image = display_lines(frame,lines) #lines over black image

combo_image = cv2.addWeighted(frame,0.8,lines_image,1,1)

smooth_lines = get_smooth_lines(frame,lines)
smooth_lines_image = display_lines(frame,smooth_lines) #lines over black image
smooth_lines_combo_image = cv2.addWeighted(frame,0.8,smooth_lines_image,1,1)

# check if the video writer is None
if writer is None:
# initialize our video writer
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter("lane_video.avi", fourcc, 30,(smooth_lines_combo_image.shape[1], smooth_lines_combo_image.shape[0]), True)

# write the output frame to disk
writer.write(smooth_lines_combo_image)

currentFrameNumber = currentFrameNumber + 1

except:
#traceback.print_exc()
pass

# release the file pointers
print("[INFO] cleaning up...")

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.