[英]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.