简体   繁体   English

在 Open CV Python 中从 cv2.contour 获取 x 和 y 坐标并将其存储到不同的变量中

[英]Getting the x and y coordinates from cv2.contour in Open CV Python and store it to different variables

I'm printing the contour from cv2.findContours.我正在从 cv2.findContours 打印轮廓。 It prints out something like these: [[370 269]] What i want is to get the 370 and store it into a variable.它打印出如下内容: [[370 269]] 我想要的是获取 370 并将其存储到变量中。

import cv2
import numpy as np
cap = cv2.VideoCapture(0)

while True:
    _, frame = cap.read()


    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    lower = np.array([0,0,255]) 
    upper = np.array([255,255,255])

    imgThreshHigh = cv2.inRange(hsv, lower, upper)
    thresh = imgThreshHigh.copy()

    _,contours,_ = cv2.findContours(thresh, 
                cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

    print(contours)

    cv2.imshow('frame',frame)
    cv2.imshow('Object',thresh)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()

Do you know destructuring ?你知道解构吗?

data = [370, 269]
x, y = data

print(x)
# 370

print(y)
#269

Or, if data is a list of list:或者,如果数据是列表列表:

data = [[370, 269]]
[[x, y]] = data

print(x)
# 370

print(y)
#269

This might be late for you, I guess it will help someone.这对你来说可能晚了,我想它会帮助某人。 To get the x, y value of a contour I used this为了获得轮廓的 x, y 值,我使用了这个

for contour in contours:
    x, y, _, _ = cv2.boundingRect(contour)
    print(x, " ", y)

This gets the x, y coordinates of the starting point of the contour.这将获得轮廓起点的 x、y 坐标。 The two underscores are width and height, ignored as we don't need them.两个下划线是宽度和高度,因为我们不需要它们而被忽略。

I worked out the following for storing all x and y coordinates for a single contour:我计算出以下用于存储单个轮廓的所有xy坐标:

x = []
y = []
for k in contours:
    for i in k:
        for j in i:
            x.append(j[0])
            y.append(j[1])

I am sure there must be a faster way !!我相信一定有更快的方法!

kx = contours[k][:,0,0]
ky = contours[k][:,0,1]

Here is a function I wrote to write the coordinates into a nested list.这是我编写的将坐标写入嵌套列表的函数。 The list contains as many lists as contours.该列表包含与轮廓一样多的列表。 Each individual list hosts a list of XY coordinate of the contour.每个单独的列表都包含一个轮廓的 XY 坐标列表。

def get_xy_list_from_contour(contours):
    full_dastaset = []
    for contour in contours:
        xy_list=[]
        for position in contour:
            [[x,y]] = position
            xy_list.append([x,y])
        full_dastaset.append(xy_list)
    return full_dastaset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM