[英]How to extract coordinates from contour lines in python and store them in new x and y variables?
[英]Getting the x and y coordinates from cv2.contour in Open CV Python and store it to different variables
我正在从 cv2.findContours 打印轮廓。 它打印出如下内容: [[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()
你知道解构吗?
data = [370, 269]
x, y = data
print(x)
# 370
print(y)
#269
或者,如果数据是列表列表:
data = [[370, 269]]
[[x, y]] = data
print(x)
# 370
print(y)
#269
这对你来说可能晚了,我想它会帮助某人。 为了获得轮廓的 x, y 值,我使用了这个
for contour in contours:
x, y, _, _ = cv2.boundingRect(contour)
print(x, " ", y)
这将获得轮廓起点的 x、y 坐标。 两个下划线是宽度和高度,因为我们不需要它们而被忽略。
我计算出以下用于存储单个轮廓的所有x
和y
坐标:
x = []
y = []
for k in contours:
for i in k:
for j in i:
x.append(j[0])
y.append(j[1])
我相信一定有更快的方法!
kx = contours[k][:,0,0]
ky = contours[k][:,0,1]
这是我编写的将坐标写入嵌套列表的函数。 该列表包含与轮廓一样多的列表。 每个单独的列表都包含一个轮廓的 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.