Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Find the minimum distance between two white lines
- # Mike Kerry - Jan 2022 - [email protected]
- # This is an improved algorithm that works in a wider set of cases
- import cv2
- import numpy as np
- def getdist(a , b):
- # compute the square of the distance between two coordinates
- dsq = (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
- return dsq
- img = cv2.imread("WhiteLines.jpg")
- dims = img.shape
- width = dims[1]
- height = dims[0]
- minsep = width // 20 # minimum separation allowed between lines is 5% of screen with
- minsepsq = minsep * minsep
- print("Width:", width, " Height:", height)
- cv2.imshow("img", img)
- array_upper = [] # This array will hold all the coordinates of white pixels of the upper line
- array_lower = [] # This array will hold all the coordinates of white pixels of the lower line
- # Scan down the image, line by line, looking for white pixels
- # separate into two arrays
- for y, line in enumerate(img): # y is line counter (vertical coordinate)
- for x, bgr in enumerate(line): # x is the horizontal coordinate
- # Is this pixel white?
- if sum(bgr) > 384: # look for pale pixels (765 would be pure white, 0 is black)
- # Is this pixel close to the last pixel for upper line array? (if any)
- i = len(array_upper)
- if i and getdist((y, x), array_upper[i - 1]) > minsepsq:
- # this white pixel is not close to the previous pixel in array_upper
- # therefore it belongs in the array for the lower line
- array_lower.append((y, x))
- else:
- # pixel is near previous pixel in array_upper (or is the first white pixel found)
- # therefore it belongs to the array for the upper line
- array_upper.append((y, x))
- # Find the closest distance between the two lines (i.e. the two arrays)
- mindistsq = 999999 # square of the minimum distance so far
- mincoord1 = (0, 0)
- mincoord2 = (0, 0)
- for coord1 in array_lower:
- for coord2 in array_upper:
- distsq = getdist(coord1, coord2) # compute the distance squared, in pixels
- if distsq < mindistsq:
- mindistsq = distsq
- mincoord1 = coord1 # Remember the coordinates of the closest white points
- mincoord2 = coord2
- # Make the closest points red
- y, x = mincoord1
- for my in range(5):
- for mx in range(5):
- img[y - 2 + my, x - 2 + mx] = (0, 0, 255) # make pixels red
- y, x = mincoord2
- for my in range(5):
- for mx in range(5):
- img[y - 2 + my, x - 2 + mx] = (0, 0, 255)
- # Draw a red line between the closest points
- diffy = mincoord1[0] - mincoord2[0] # vertical distance
- diffx = mincoord1[1] - mincoord2[1] # horizontal distance
- for dy in range(diffy):
- y = mincoord2[0] + dy
- dx = int((diffx * dy) / diffy)
- x = mincoord2[1] + dx
- img[y][x] = (0, 0, 255) # set pixel colour red
- mindist = int(mindistsq ** 0.5)
- print("Minimum distance beteween the lines is:", mindist)
- cv2.imshow("img", img)
- cv2.waitKey(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement