I'm printing the contour from cv2.findContours. It prints out something like these: [[370 269]] What i want is to get the 370 and store it into a variable.
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
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. 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:
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.