main.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from skimage.filters import threshold_otsu
  2. from skimage.measure import label, regionprops
  3. from skimage.morphology import binary_closing, binary_dilation, binary_erosion, binary_opening
  4. import matplotlib.pyplot as plt
  5. import pathlib
  6. def binary_append(image, func, times: int = 1):
  7. result = image[:]
  8. for _ in range(times):
  9. result = func(result)
  10. return result
  11. all_pencils = 0
  12. for index in range(1, 12):
  13. image = plt.imread(f'pencils/images/img ({index}).jpg').mean(axis=2)
  14. thrashold = threshold_otsu(image)
  15. image[image < thrashold] = 1
  16. image[image > thrashold] = 0
  17. # Большой closing
  18. result = binary_append(image, binary_dilation, 25)
  19. result = binary_append(result, binary_erosion, 25)
  20. pen_count = 0
  21. labeled = label(result)
  22. regions = regionprops(labeled)
  23. for region in regions:
  24. min_row, min_col, max_row, max_col = region.bbox
  25. width = max_col - min_col
  26. height = max_row - min_row
  27. if (width / result.shape[1] > 0.4 or height / result.shape[0] > 0.4) and \
  28. not (max_row == result.shape[0] or max_col == result.shape[1]):
  29. pen_count += 1
  30. plt.subplot(3,4,index)
  31. plt.title(f'{pen_count} карандашей')
  32. plt.imshow(labeled)
  33. all_pencils += pen_count
  34. plt.show()