如何给数组中的每个项目编号?

2024-06-16 09:40:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以它会显示:

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)

Tags: andofthe函数nameifiscv2
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

您可以维护一个count变量(可以递增)并返回一个元组列表

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

或者

在遍历列表时,请使用枚举

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

相关问题 更多 >