我正在尝试制作一个圆圈检测程序,该程序将在检测控制/测试之后是否确实存在圆圈。我试图通过将圆形的x和y一次放入列表中来做到这一点-这是控制列表。对象列表是连续插入的每个x和y圆,而不仅仅是一次。然后它将计数/比较控制列表ObjectList.count(ControlList[i])
x和y在对象列表中出现了多少次。如果出现超过5次,则将其绘制。
我的问题是如何从中获得x和y:
['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87']
第一个是x,第二个是y
if pregled == 0: # Checks if ControlList was wiped clear after 10 checks
if count < 11: # counts to 10 the sets pregled = 1
count = count + 1
for cnt1 in contours1:
#ret = cv2.matchShapes(cnt,cnt1,1,0.0)
area = cv2.contourArea(cnt1)
if area > 500:
ret = cv2.matchShapes(cnt,cnt1,1,0.0)
if ret < 0.02:
if len(cnt1) > 0:
M = cv2.moments(cnt1)
if M["m00"] != 0:
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#Conturji = '('+str(cx)+','+str(cy)+')'
Conturji = str(cx) +','+ str(cy) # Puts everything in string
if Conturji not in ControlList: # Checks if it already is in ControlList
ControlList.append(Conturji)
print(ControlList)
`
答案 0 :(得分:0)
x_y= ['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87']
new_list = [value.split(",") for value in x_y]
print(new_list)
输出:
[['46', '101'], ['91', '86'], ['46', '100'], ['137', '64'], ['54',
'53'], ['99', '31'], ['91', '85'], ['91', '87']]
因此,您有2个元素列表的列表,可以将其强制转换为元组或任何其他对象。
如果您只想选择一个元素并将其拆包,则可以这样做:
x,y = x_y[0].split(",")
但是,如果您更改此行,效率会更高:
Conturji = str(cx) +','+ str(cy)
收件人
Conturji = (cx,cy)
快速而高效的事理,以后您甚至可以立即打印:
tuple = (1,2)
print(tuple)
(1,2)
答案 1 :(得分:0)
您可以使用split功能
a = ['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87']
x = list(i.split(',')[0] for i in a)
y = list(i.split(',')[1] for i in a)
print(x) #['46', '91', '46', '137', '54', '99', '91', '91']
print(y) #['101', '86', '100', '64', '53', '31', '85', '87']
答案 2 :(得分:0)
简单的答案是永远不要将它们放在字符串的首位,您应该让循环将它们作为元组添加到列表中,以免不得不对其进行后期处理以获得实际输出
Conturji = str(cx) +','+ str(cy) # Puts everything in string
应该是
Conturji = cx, cy
您的输出将变成
[ (46, 101), (91, 86), (46,100), ...
答案 3 :(得分:0)
map
:
x_y= ['46,101', '91,86', '46,100', '137,64', '54,53', '99,31', '91,85', '91,87']
new_list = list(map(lambda x: x.split(','),x_y))
print(new_list)
或者:
x,y= list(map(lambda x: x.split(','),x_y))
print(x)
print(y)
但是最好的方法仍然是:
替换:
Conturji = str(cx) +','+ str(cy) # Puts everything in string
使用:
Conturji = cx,cy