Как удалить маленькие цветные пиксели с изображения с помощью OpenCV - PullRequest
0 голосов
/ 02 октября 2019

Я работаю над проектом, в котором мне нужно обработать изображение и получить значения rgb для цветной линии, как показано на рисунке. я обнаруживаю строки и получаю значения, обрабатывая изображение слева направо построчно. но там есть любой цветной пиксель перед полной строкой. тогда мой алгоритм может дать неправильный вывод для меня.

Вот оригинал

enter image description here

А вот изображение после запуска моего кода, в котором некоторые пиксели находятся до и после левогострока:

enter image description here

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

Вот мой код:

import cv2
import numpy as np


def image_processing(img):
    msg = ''
    try:
        img = cv2.imread(img)
        # img = cv2.resize(img, (650, 120), interpolation=cv2.INTER_AREA)
        img_hsv = cv2.cvtColor(255 - img, cv2.COLOR_BGR2HSV)
    except Exception as e:
        msg += 'Unable to read image.'
    else:
        lower_red = np.array([40, 0, 0])  # lower range for red values
        upper_red = np.array([95, 255, 255])  # upper range for red values

        # mask on red color lines to find them
        mask = cv2.inRange(img_hsv, lower_red, upper_red)
        # original image with just red color pixels all other pixels will be set to 0(black)
        color_detected_img = cv2.bitwise_and(img, img, mask=mask)

        # finding the pixel where color is detected in [colored_detected_img]
        img_dimensions = color_detected_img.shape  # height & width of the image
        left_line_colors = []
        right_line_colors = []
        y_color_index = 10
        x_color_index = 0
        left_line_detected = False
        right_line_detected = False

        # getting left line values
        while x_color_index < img_dimensions[1] - 1:
            x_color_index += 1
            if color_detected_img[y_color_index, x_color_index].all() > 0:  # checking if color values are not 0 (0 is black)
                left_line_detected = True
                for y in range(img_dimensions[0] - 1):
                    # print(y, x_color_index)
                    left_line_colors.append(
                    color_detected_img[y,x_color_index].tolist())
            elif left_line_detected:
                break
            else:
                continue

        #  ---- Getting final results of left line ----
        try:
            left_line_colors = [l for l in left_line_colors if (l[0] != 0 and l[1] != 0 and l[2] != 0)]
            # adding all the rgb list values together i.e if -> [[1, 2, 3], [2, 4, 1]] then sum -> [3, 6, 4]
            sum_of_left_rgb = [sum(i) for i in zip(*left_line_colors)]
            left_rgb = [int(sum_of_left_rgb[0] / len(left_line_colors)),
                    int(sum_of_left_rgb[1] / len(left_line_colors)),
                    int(sum_of_left_rgb[2] / len(left_line_colors))]
            print(left_rgb[2], left_rgb[1], left_rgb[0])
        except:
            msg += 'No left line found.'

        cv2.imshow("Cropped", color_detected_img)

        cv2.waitKey(0)
        cv2.destroyAllWindows()

    return msg


print(image_processing('C:/Users/Rizwan/Desktop/example_strip1.jpg'))

Это должно дать мне результат

enter image description here

Но этот результат imageя получаю, внедряя фильтр medianblur, и он изменяет значения rgb, которые дают неправильный результат.

1 Ответ

0 голосов
/ 03 октября 2019

попытайтесь использовать эрозию с последующим расширением Нажмите здесь, чтобы узнать об эрозии и наборе

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