|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +import cv2 |
| 4 | +image=cv2.imread('image.jfif') |
| 5 | +img=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
| 6 | +edges = cv2.Canny(img,100,200) |
| 7 | + |
| 8 | +def hough_line(edges): |
| 9 | + theta= np.arange(0,180,1) ## Theta 0 - 180 degree |
| 10 | + cos = np.cos(np.deg2rad(theta)) |
| 11 | + sin = np.sin(np.deg2rad(theta)) |
| 12 | + |
| 13 | + # Generate a accumulator matrix to store the values |
| 14 | + rho_range = int(np.hypot(edges.shape[0] , edges.shape[1])) #max value of rho size =2*diagonal_length |
| 15 | + accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) |
| 16 | + |
| 17 | + # Threshold to get edges pixel location (x,y) |
| 18 | + edge_pixels = np.where(edges == 255) #returns b bool matrix (True if edge_point=255; False is edge_point!=255) |
| 19 | + coordinates = list(zip(edge_pixels[0], edge_pixels[1])) #to access the edge points |
| 20 | + |
| 21 | + # Calculate rho value for each edge location (x,y) with all the theta range |
| 22 | + for p in range(len(coordinates)): |
| 23 | + for t in range(len(theta)): |
| 24 | + rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) #compute rho=x*cost+y*sint |
| 25 | + accumulator[rho, t] += 1 #increment the accumulator cell |
| 26 | + return accumulator |
| 27 | + |
| 28 | +accumulator=hough_line(edges) |
| 29 | + |
| 30 | +# Function to do hough line transform\ |
| 31 | + |
| 32 | +#print(len(accumulator>=90) |
| 33 | +# Threshold some high values then draw the line |
| 34 | +edge_pixels = np.where(accumulator > 75) |
| 35 | + |
| 36 | +coordinates = list(zip(edge_pixels[0], edge_pixels[1])) |
| 37 | + |
| 38 | +# Use line equation to draw detected line on an original image |
| 39 | +for i in range(0, len(coordinates)): |
| 40 | + a = np.cos(np.deg2rad(coordinates[i][1])) |
| 41 | + b = np.sin(np.deg2rad(coordinates[i][1])) |
| 42 | + x0 = a*coordinates[i][0] |
| 43 | + y0 = b*coordinates[i][0] |
| 44 | + |
| 45 | + x1 = int(x0 + 255*(-b)) #here 255(any constant) is multiplied to strech the lines over the edges |
| 46 | + y1 = int(y0 + 255*(a)) |
| 47 | + x2 = int(x0 - 255*(-b)) |
| 48 | + y2 = int(y0 - 255*(a)) |
| 49 | + |
| 50 | + |
| 51 | + cv2.line(image,(x1,y1),(x2,y2),(0,255,0),1) |
| 52 | + |
| 53 | +cv2.imwrite('Linedetection_without_opencv.png',image) |
0 commit comments