2

I have an function to detect shapes in an image, this returns the shape name, from that I have an array of the returned shapes but was wondering how I could add a count to each shape detected?

So it would show:

rectangle 1

rectangle 2

rectangle 3

rectangle 4

and so on for each rectangle detected. The code I have at the moment is:

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)
A Popat
  • 23
  • 2

2 Answers2

4

You could maintain a count variable (which you can increment) and return a list of tuples

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

or

when iterating through your list use enumerate

for indx, shape in enumerate(rectangles):
    print indx,shape
Nilav Baran Ghosh
  • 1,111
  • 9
  • 17
  • 1
    Thank you very much! the enumerate function worked perfectly! – A Popat Feb 12 '18 at 19:30
  • 1
    You can pass a second argument to specify the number you want to start with. For instance, if you want to start from `1` (instead of `0`): `enumerate(rectangles, 1)` – pault Feb 12 '18 at 19:33
0

You can use 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}')

Returns:

Count of rectangle: 2
rectangle #1
rectangle #2
Count of circle: 1
circle #1
ADR
  • 1,125
  • 7
  • 17