Как найти пиксельные координаты прямоугольника с помощью Opencv? - PullRequest
0 голосов
/ 04 мая 2020

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

Первоначальный вопрос был:

Я пытаюсь получить координаты пикселя зеленого прямоугольника на изображении ниже. Я полагаю, это возможно с помощью OpenCV. (я размыл все личные детали) imageenter image description here">

1 Ответ

0 голосов
/ 04 мая 2020

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

Finding the rectangle color using Chrome color picker

Поскольку цвет в шестнадцатеричном виде формат # 00FF00, который эквивалентен RGB-обозначению RGB (0, 255, 0). Но в OpenCV цвет представлен в нотации BGR, а затем, чтобы получить зеленый цвет в OpenCV, у нас есть следующее определение: BGR (0, 255, 0).

Что нам нужно сделать, это перебрать каждый пиксель и проверить его значение. В первый раз, когда мы находим пиксель, который соответствует BGR (0, 255, 0), мы сохраняем эту координату, которая будет верхним левым углом зеленого прямоугольника, поскольку l oop начинается в верхнем левом углу изображения и идет вправо до конца, затем он перемещается на 1 пиксель вниз и начинается снова слева направо и так далее, пока не достигнет последнего пикселя изображения.

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

import cv2

coordinates = []  # list of the green rectangle coordinates
green_color = [0, 255, 0]
last_x_green, last_y_green = 0, 0  # store the last x and y green positions

# reads the image in the color mode
img = cv2.imread('original.jpg', 1)
rows, cols, _ = img.shape  # gets the image's rows and color, which are height and width

for x in range(rows):
    for y in range(cols):
        px = list(img[x, y])
        if px == green_color:
            # find the first coordinate of the green rectangle (top left corner)
            if len(coordinates) == 0:
                coordinates.append((y, x))  # top left corner of the green rectangle

            last_x_green, last_y_green = x, y

coordinates.append((last_y_green, last_x_green))

# Now we have the top left corner and the bottom right corner of the green rectangle
print(coordinates)

# As printed above, the coordinates of top left corner and bottom right corner of the green rectangle are (167, 2508)
# and (615, 2951), respectivelly.
# We can find the other coordinates based on these two coordinates the following way:
# Let's assume these coordinates are (x1, y1) and (x2, y2). The bottom left corner must be at (x1, y2) and the top
# right corner must be (x2, y1). Therefore, the bottom left coordinate is (167, 2951) and the top right coordinate is
# (615, 2580).
# Generically, we would have the four points represents in this form:
# coordinates: [(x1, y1), (x2, y2)]
top_left = coordinates[0]  # (x1, y1)
bottom_left = (coordinates[0][0], coordinates[1][1])  # (x1, y2)
top_right = (coordinates[1][0], coordinates[0][1])  # (x2, y1)
bottom_right = coordinates[1]

print('The coordinates of the green rectangle, from left to right and from top to bottom, are:')
print(f'Top Left: {top_left}, Top Right: {top_right}, Bottom Left: {bottom_left}, Bottom Right: {bottom_right}')

# Syntax: cv2.rectangle(image, start_point, end_point, color, thickness)
# Draw a 10 px red rectangle around the green rectangle and save the image.
# We only need the top left and bottom right corner to draw it
cv2.rectangle(img, coordinates[0], coordinates[len(coordinates) - 1], (0, 0, 255), 10)
cv2.imwrite('rectangle_detected.jpg', img)
[(167, 2508), (615, 2951)]
The coordinates of the green rectangle, from left to right and from top to bottom, are: 
Top Left: (167, 2508), Top Right: (615, 2508), Bottom Left: (167, 2951), Bottom Right: (615, 2951)
Process finished with exit code 0

Это результат изображения: A red rectangle around the green rectangle

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