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

时间:2018-02-12 19:20:18

标签: python python-3.x counter

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

所以它会显示:

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)

2 个答案:

答案 0 :(得分:4)

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

func connectToDevice(_ device: GCKDevice, sessionId: String?) {
    if let session = sessionManager.currentSession {
        sessionManager.endSession()  // This doesn't help
    }
    DispatchQueue.main.asyncAfter(.now()+5.0) {   // endSession() is asynchronous, so need to give some time  
        sessionManager.startSession(with: device) // This will fail in situations where 'session' isn't nil
    }
}

在遍历列表时使用枚举

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

答案 1 :(得分:0)

您可以使用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