Обнаружение перекрывающихся шумных кругов на изображении - PullRequest
2 голосов
/ 27 мая 2020

Я пытаюсь распознать две области на следующем изображении. Область внутри внутреннего и область между внешним и внутренним - граница - круг с python openCV.

enter image description here

Я пробовал разные подходы, например :

Это не очень хорошо.

Возможно ли это даже с классической обработкой изображений или мне нужны нейронные сети?

Изменить: Обнаружение изображений кругов с помощью opencv hough circle

# import the necessary packages
import numpy as np
import argparse
import cv2
from PIL import Image

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread(args["image"])
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 500)
# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")
    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    # show the output image
    img = Image.fromarray(image)
    if img.height > 1500:
        imS = cv2.resize(np.hstack([image, output]), (round((img.width * 2) / 3), round(img.height / 3)))
    else:
        imS = np.hstack([image, output])
    # Resize image
    cv2.imshow("gray", gray)
    cv2.imshow("output", imS)
    cv2.waitKey(0)
else:
    print("No circle detected")

Тест: Testimage

1 Ответ

3 голосов
/ 27 мая 2020

Общая ошибка: При использовании HoughCircles() параметры следует выбирать соответствующим образом. Я вижу, что вы используете в своем коде только первые 4 параметра. Ypu может проверить здесь , чтобы получить хорошее представление об этих параметрах.

Опытная идея: При использовании HoughCircles, я заметил, что если 2 центра 2 окружностей одинаковые или почти близкие друг к другу, HoughCircles не может их обнаружить. Даже если присвоить min_dist parameter маленькому значению. В вашем случае центр кругов тоже такой же.

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

Для результата внешнего круга и параметров, включенных в код:

Результат:

enter image description here

# import the necessary packages
import numpy as np
import argparse
import cv2
from PIL import Image

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread('image.jpg')
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gray = cv2.medianBlur(gray,15)
rows = gray.shape[0]

# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,1, rows / 8,
                               param1=100, param2=30,
                               minRadius=200, maxRadius=260)
# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")
    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    # show the output image
    img = Image.fromarray(image)
    if img.height > 1500:
        imS = cv2.resize(np.hstack([image, output]), (round((img.width * 2) / 3), round(img.height / 3)))
    else:
        imS = np.hstack([image, output])
    # Resize image
    cv2.imshow("gray", gray)
    cv2.imshow("output", imS)
    cv2.waitKey(0)
else:
    print("No circle detected")

Для внутреннего круга параметры:

circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT,1, rows / 8,
                                   param1=100, param2=30,
                                   minRadius=100, maxRadius=200)

Результат:

enter image description here

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