Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Script to find a white line, and draw a red blob that follows the line
- # Mike Kerry Jan 2022
- import cv2
- import numpy as np
- SPOTSIZE = 8
- BLOCKSIZE = 5
- def get_block_avg(y, x, dim):
- block = matrix[y: y + dim, x: x + dim] # Extract a block of integers from matrix
- return block.sum() // (dim * dim) # Find the average whiteness of the block
- def draw_red(y, x):
- # Draw a red spot of the desired size. y, x is the top left corner.
- for dy in range(0, SPOTSIZE):
- for dx in range(0, SPOTSIZE):
- img[y + dy][x + dx] = (0, 0, 255) # make the image pixels red
- # block the return path by setting already visited matrix positions negative
- for dy in range(0, BLOCKSIZE):
- for dx in range(0, BLOCKSIZE):
- matrix[y + dy][x + dx] = -666 # make that point blacker than black!
- def find_start():
- # Scan down and right looking for a block of pixels that are basically white
- for y in range(0, height - BLOCKSIZE, 3):
- for x in range(0, width - BLOCKSIZE, 3):
- v = get_block_avg(y, x, 5)
- if v > 650: # 650 was found empirically to be a good value to suggest white
- return y, x # Return the coords of the top left of a white block
- return(-1, -1)
- orig = cv2.imread('pyFollowLineMed.jpg')
- img = orig.copy()
- dims = img.shape
- height, width = dims[0], dims[1]
- matrix = img.sum(axis=2, dtype=np.int16) # Reduce number of axes (?) by summing BGR
- ypos, xpos = find_start() # Get the coordinates of the first block of white pixels found
- # Try and follow the line without retracing
- while True:
- cv2.imshow("img", img)
- cv2.waitKey(30) # pause for effect
- # scan around the current location, in 8 directions, looking for the whitest adjacent block of pixels
- best, besty, bestx = 0, 0, 0
- for incy in range(-BLOCKSIZE, BLOCKSIZE+1, BLOCKSIZE): # y becomes -5, 0, 5
- for incx in range(-BLOCKSIZE, BLOCKSIZE+1, BLOCKSIZE): # x becomes -5, 0, 5
- y2 = ypos + incy
- x2 = xpos + incx
- v = get_block_avg(y2, x2, BLOCKSIZE)
- if v > best:
- best, besty, bestx = v, y2, x2 # save the coords at top left of white block
- ypos, xpos = besty, bestx # top left of the whitest adjacent block of pixels
- img = orig.copy() # get the original image again (without any red spots)
- draw_red(ypos, xpos) # draw the new red spot and block the return path
- if best < 670: # 670 was found empirically to be a good value to end the loop
- break # No adjacent white block found. We have reached the end of the line
- cv2.waitKey(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement