Как использовать OpenCV, чтобы нарисовать линию на бордюре? - PullRequest
1 голос
/ 19 января 2020

Я использую этот код для обнаружения линий с хитрым и грубым, но эффект не очень хороший.

Я хочу нарисовать линию на бордюре. Цель рисования прямой линии - определить положение линии на изображении, потому что, когда я еду самостоятельно, я хочу, чтобы моя машина ROS ехала по обочине. Моя страна едет по правой стороне.

import cv2
import numpy as np

img = cv2.imread(r"E:\test_opencv\images\testcanny.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
edges = cv2.Canny(blur_img, 250, 450, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 118)
minLineLength = 800
maxLineGap = 15
threshold=80
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold, minLineLength, maxLineGap)
for i in range(len(lines)):
    for x1, y1, x2, y2 in lines[i]:
        cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 4)
cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Исходное изображение:

enter image description here

Картинка с рисунком:

enter image description here

Результирующее изображение:

enter image description here

Только несколько коротких зеленых линий на результирующем изображении.

На самом деле, я просто хочу красный часть бордюра, чтобы стать зеленой линией. enter image description here

Точно так же:

enter image description here

Как исправить код?

Ответы [ 2 ]

1 голос
/ 19 января 2020

Использование classi c Преобразование Хафа (HoughLines) дает лучший результат, отличный от вероятностного c Преобразование Хафа (HoughLinesP). Я запустил этот код на вашем точном изображении и получил эти результаты. Пороговое значение для первого изображения составляет 100 , а для следующее изображение составляет 200

enter image description here

enter image description here

Код:

import cv2
import numpy as np

img = cv2.imread("D:\\1.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
edges = cv2.Canny(blur_img, 250, 450, apertureSize=3)

rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 200 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).

lines = cv2.HoughLines(edges, rho, theta, threshold)

for i in range(len(lines)):
    for r,th in lines[i]:
        a = np.cos(th)
        b = np.sin(th)
        x0 = a*r
        y0 = b*r
        x1 = int(x0 + 1000*(-b))
        y1 = int(y0 + 1000*(a))
        x2 = int(x0 - 1000*(-b))
        y2 = int(y0 - 1000*(a))

        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

И дополнительная информация о преобразовании Хафа:

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html

0 голосов
/ 20 января 2020

Для этой картинки я использую этот код для лучшего эффекта.

import cv2
import numpy as np

img = cv2.imread(r"E:\test_opencv\images\testcanny.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
gray = cv2.cvtColor(blur_img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 250, 350, apertureSize=3)
rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 300 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).
lines = cv2.HoughLines(edges, rho, theta, threshold)
if lines is not None:
    for i in range(len(lines)):
        for r,th in lines[i]:
            a = np.cos(th)
            b = np.sin(th)
            x0 = a*r
            y0 = b*r
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))
            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Результат изображения:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...