LetterCropper.py 975 B

12345678910111213141516171819202122232425262728293031323334
  1. from copy import deepcopy
  2. from Rectangle import Rectangle
  3. class LetterCropper:
  4. def __init__(self, image, threshold = 0.9):
  5. self.source_image = image
  6. self.threshold = threshold
  7. def get_cropped_letter(self):
  8. self.determine_letter_bounds()
  9. self.result_image = deepcopy(self.source_image)
  10. self.result_image.crop(self.letter_bounds)
  11. return self.result_image
  12. def determine_letter_bounds(self):
  13. min_x = self.source_image.width
  14. max_x = 0
  15. min_y = self.source_image.height
  16. max_y = 0
  17. for y, x, value in self.source_image:
  18. if value < self.threshold:
  19. if x < min_x: min_x = x
  20. if y < min_y: min_y = y
  21. if x > max_x: max_x = x
  22. if y > max_y: max_y = y
  23. self.letter_bounds = Rectangle(
  24. min_x,
  25. min_y,
  26. max_x - min_x ,
  27. max_y - min_y
  28. )