[英]How to locate pixel coordinates of a rectangle using Opencv?
我必须使用 Chrome 颜色选择器确保矩形完全是绿色的。
因为颜色是十六进制格式#00FF00,相当于RGB符号RGB(0, 255, 0)。 但是在 OpenCV 中,颜色以 BGR 表示法表示,然后要在 OpenCV 中得到绿色,我们有以下定义:BGR(0, 255, 0)。
我们应该做的是遍历每个像素并检查其值。 当我们第一次找到一个匹配 BGR(0, 255, 0) 的像素时,我们存储这个坐标,它将是绿色矩形的左上角,因为循环从图像的左上角开始并向右移动直到结束,然后它向下移动 1 px 并从左到右再次开始,依此类推,直到到达最后一个图像的像素。
每次像素为绿色时,我都会存储它的坐标,因为在绿色矩形的末端,我将拥有右下角绿色矩形的坐标。 我决定在下面的代码中逐步解释:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.