【问题标题】:How to Format the Output of you numpy array in Python3?如何在 Python3 中格式化 numpy 数组的输出?
【发布时间】:2017-05-08 17:35:28
【问题描述】:

我无法按照我想要的方式格式化我的 numpy 数组。我检查了几篇像 How to remove specific elements in a numpy array 这样的帖子,大多数看起来很接近,但没有一个有我想要的。如果这个问题是一个重复,那么我将朝着正确的方向前进。

im2, contours, hierarchy = cv2.findContours(th2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

轮廓给了我这个:

print(contours)

我明白了:

[array([[[618, 737]]], dtype=int32), array([[[615, 737]]], dtype=int32), array([[[656, 731]],
   [[655, 732]],

   [[651, 732]],

   [[649, 734]],

   [[648, 734]],

   [[647, 735]],

   [[646, 734]],

   [[645, 735]],

   [[644, 735]],

   [[643, 736]],

   [[641, 736]],

   [[640, 737]],

       [[686, 737]],

       [[686, 734]],

但我想得到一个可以给我这种格式的元组的输出:

(x, y)

或者如果有另一种方法可以访问数组中的整数,我已经尝试过但没有得到我想要的东西

contours = tuple(map(tuple, contours))

contours = totuple(contours)

请帮助我是新手

【问题讨论】:

  • 据我所知,contourslist,而不是数组。
  • 那不是数组。那是 3 个数组,我不知道您想如何将其转换为单个 x, y 元组。
  • 好吧 @user2357112 如果它是 3 个数组,那么为什么我不能将 3 个数组的内容提取到一个元组列表中,这正是我想要的

标签: python arrays opencv numpy


【解决方案1】:

你在寻找这样的东西吗?

[[tuple(xy[0]) for xy in contour] for contour in contours]

#[[(618, 737)],
# [(615, 737)],
# [(656, 731), (655, 732), (651, 732), (649, 734), (648, 734)]]

如果你想要一个平面列表:

[tuple(xy[0]) for contour in contours for xy in contour]

#[(618, 737),
# (615, 737),
# (656, 731),
# (655, 732),
# (651, 732),
# (649, 734),
# (648, 734)]

【讨论】:

  • 我正在寻找更像 {(618, 737),(615,737),(656, 731), (655, 732), (651, 732), (649, 734) 的东西, (648, 734)} 这可能吗
  • 您可以将内部 for 循环移动到列表理解的末尾,这将生成一个扁平列表。如果你想要一个集合,请使用集合理解 {tuple(xy[0]) for contour in contours for xy in contour}
  • 结果还是一样。我试过这个:co_ord = {}co_ord.update([tuple(xy[0]) for contour in contours for xy in contour]) 得到了类似的东西{618: 20, 615: 19, 656: 75, 655: 55, 651: 3, 649: 3, 648: 53, 647: 54, 646: 54,.....}
  • 最后需要什么?一本字典?而且列表理解也不会改变contours,如果你想要一个新的轮廓,你需要将结果分配回去。 contours = [tuple(xy[0]) for contour in contours for xy in contour].
  • 现在可以用了吗?也许co_ord.extend([...]) 是你需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多