| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 | import matplotlib.pyplot as pltimport numpy as npfrom skimage.measure import label, regionpropsfrom skimage.color import rgb2hsvfrom collections import defaultdictdef get_shapes(regions):    shapes = defaultdict(lambda: 0)    for _, region in enumerate(regions):        eccent = region.eccentricity        if eccent == 0:            if region.image.size == region.area:                key = "rect"            else:                key = "ball"        else:            key = "rect"        shapes[key] += 1    return shapesfile = "./balls_and_rects.png"img = plt.imread(file)binary = np.mean(img, 2)binary[binary > 0] = 1labeled = label(binary)print(f"Total f={labeled.max()}")hsv_image = rgb2hsv(img)c = 0prev = 0for index, i in enumerate(np.linspace(0, 1, 10)):    tmp_img = np.copy(hsv_image)    tmp_img[tmp_img[:, :, 0] < prev] = 0    tmp_img[tmp_img[:, :, 0] > i] = 0    tmp_img[tmp_img[:, :, 0] > 0] = 1    tmp_img = np.mean(tmp_img, 2)    labeled = label(tmp_img)    if labeled.max() > 0:        c += 1        print(f"Color {c}:")        regs = regionprops(labeled)        shapes = get_shapes(regs)        for cur_key in shapes:            print(f"\t{cur_key}s: {shapes[cur_key]}")    prev = i
 |