Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Find the minimum distanve between two white lines
- # Mike Kerry - Jan 2022 - acclivity2@gmail.com
- import cv2
- import numpy as np
- img = cv2.imread("WhiteLinesCrop.jpg")
- dims = img.shape
- width = dims[1]
- height = dims[0]
- print("Width:", width, " Height:", height)
- cv2.imshow("img", img)
- array_tr = [] # This array will hold all the coordinates of white pixels in the upper right line
- array_bl = [] # This array will hold all the coordinates of white pixels in the lower left line
- for y, line in enumerate(img): # y is line counter (vertical coordinate)
- for x, rgb in enumerate(line): # x is the horizontal coordinate
- # Is this pixel white?
- if sum(rgb) > 384: # look for pale pixels (765 would be pure white, 0 is black)
- # Got a white pixel
- # Is this pixel nearer to the top right, or the bottom left?
- dist_bl = (height - y) ** 2 + x ** 2
- dist_tr = y ** 2 + (width - x) ** 2
- if dist_bl < dist_tr:
- # This pixel is in the lower left line. Add its coordinates to the bottom left array
- array_bl.append((y, x))
- # TESTING ... make bottom left BLUE
- # img[y, x] = (255, 0, 0)
- else:
- # this pixel is in the upper right line
- array_tr.append((y, x)) # Add its coordinates to the top right array
- # Find the closest distance between the two lines (i.e. the two arrays)
- mindistsq = 999999 # square of the minimum distance
- mincoord1 = (0, 0)
- mincoord2 = (0, 0)
- for coord1 in array_bl:
- for coord2 in array_tr:
- # compute the distance squared, in pixels
- distsq = (coord1[0] - coord2[0]) ** 2 + (coord1[1] - coord2[1]) ** 2
- 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)
- mindist = int(mindistsq ** 0.5)
- print("Minimum distance beteween the lines is:", mindist)
- cv2.imshow("img", img)
- cv2.waitKey(0)
- input("Enter:")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement