Skip to content
Advertisement

How can I make an object that follows a route?

I have a red point where I can move around and a blank background that I can edit as I want. My goal is to move this point according to the route I will draw on the background.I can take my center point, plot or detect my route, but I have no idea how this point can follow this route. Can you share your ideas with me?

enter image description here

enter image description here

Advertisement

Answer

First, find the contours of the outlines of the route. If multiple lines exist, like 2, we can dilate (make thicker) the contours until they overlap each others, merging them into one, where we can erode the resulting contour into a thin line.

For your first image:

<>

You can dilate the contours with 3 iterations, and then erode them by 6 iterations. That’s because there are double contours forming the route:

import cv2
import numpy as np

img = cv2.imread("route.jpg")

def process(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.GaussianBlur(img_gray, (7, 7), 0)
    img_canny = cv2.Canny(img_blur, 10, 0)
    kernel = np.ones((9, 9))
    img_dilate = cv2.dilate(img_canny, kernel, iterations=3)
    img_erode = cv2.erode(img_dilate, kernel, iterations=6)
    return img_erode

contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

while True:
    for cnt in contours:
        for x, y in cnt.squeeze():
            img_new = img.copy()
            cv2.circle(img_new, (x, y), 8, (0, 0, 255), -1)
            cv2.imshow("Image", img_new)
            if cv2.waitKey(5) & 0xFF == ord('q'):
                quit()

For your second image:

<>

Simply replace the img_erode = cv2.erode(img_dilate, kernel, iterations=6) with img_erode = cv2.erode(img_dilate, kernel, iterations=3).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement