【问题标题】:How to number each item in an array? [duplicate]如何对数组中的每个项目进行编号? [复制]
【发布时间】:2018-02-12 19:20:18
【问题描述】:

我有一个检测图像中形状的函数,它返回形状名称,从中我有一个返回形状的数组,但想知道如何为检测到的每个形状添加计数?

所以它会显示:

rectangle 1

rectangle 2

rectangle 3

rectangle 4

对于检测到的每个矩形,依此类推。 我现在的代码是:

def detect(c):
    # initialize the shape name and approximate the contour
    shape = ""
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)

    # if the shape has 4 vertices, it is a rectangle
    if len(approx) == 4:
        # compute the bounding box of the contour and use the
        # bounding box to compute the aspect ratio
        (x, y, w, h) = cv2.boundingRect(approx)
        ar = w / float(h)
        #the shape is a rectangle
        shape = "rectangle"

    # otherwise the shape is a circle
    else:
        shape = "circle"

    # return the name of the shape
    return shape

# detect the shape
shape = detect(c)

#array of rectangles
rectangles = []

#add each rectangle found to the array 'rectangles'
if shape == 'rectangle':
    rectangles.append(shape)

【问题讨论】:

  • 看枚举
  • 你为什么需要给对象添加一个计数,只需迭代你的数组并用你的数组索引+1打印它的形状
  • 我想给每个对象贴上标签,这样它们就可以在图像上被唯一标识

标签: python python-3.x counter


【解决方案1】:

你可以维护一个计数变量(你可以递增)并返回一个元组列表

if shape == 'rectangle':
    rectangles.append((shape,count))

在遍历您的列表时使用枚举

for indx, shape in enumerate(rectangles):
    print indx,shape

【讨论】:

  • 非常感谢! enumerate 函数运行良好!
  • 你可以传递第二个参数来指定你想要开始的数字。例如,如果你想从1(而不是0)开始:enumerate(rectangles, 1)
【解决方案2】:

你可以使用Counter:

from typing import Counter

figures = ['rectangle', 'circle', 'rectangle']

for figure_type, figures_count in Counter(figures).items():
    print(f'Count of {figure_type}: {figures_count}')

    for index in range(figures_count):
        print(f'{figure_type} #{index + 1}')

返回:

Count of rectangle: 2
rectangle #1
rectangle #2
Count of circle: 1
circle #1

【讨论】:

    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2021-03-13
    • 2012-10-22
    • 2015-06-27
    相关资源
    最近更新 更多