Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

68 lines
2.1KB

  1. import logging
  2. import os
  3. import random as rd
  4. from functools import partial
  5. import cv2
  6. logger = logging.getLogger("elements")
  7. def add_elements(img):
  8. min_elements = 2
  9. max_elements = 4
  10. base_dir = "elements/black/"
  11. all_files = os.listdir(base_dir)
  12. rd.shuffle(all_files)
  13. # randomize number of elements added
  14. num_elements = rd.randint(min_elements, max_elements)
  15. # create a set to prevent element repetition
  16. added_counter = 0
  17. logger.info("Adding %d elements" % (num_elements, ))
  18. for file_name in map(partial(os.path.join, base_dir), all_files):
  19. if added_counter == num_elements:
  20. return
  21. success = add_single_element(img, file_name)
  22. if success:
  23. added_counter += 1
  24. def add_single_element(img, file_name):
  25. imh, imw, imd = img.shape
  26. element = cv2.imread(file_name, -1)
  27. if element is None:
  28. logger.warning("Could not read file %s" % (file_name,))
  29. return False
  30. original_height, original_width, original_depth = element.shape
  31. # adjust size if too big
  32. if original_height > imh * .5 or original_width > imw * .5:
  33. element = cv2.resize(element, (int(.5 * original_width), int(.5 * original_height)))
  34. resized_height, resized_width, _ = element.shape
  35. # refuse to use this image, if this failed
  36. if resized_height > imh or resized_width > imw:
  37. logger.warning("Element %s too big, moving on" % (file_name,))
  38. return False
  39. # get x coord and y coord on the image
  40. from_x_pos = rd.randint(1, imw - resized_width - 1)
  41. from_y_pos = rd.randint(1, imh - resized_height - 1)
  42. # make alpha channel
  43. alpha_s = element[:, :, 2] / 255.0
  44. alpha_1 = 1.0 - alpha_s
  45. for c in range(0, 3):
  46. to_y_pos = from_y_pos + resized_height
  47. to_x_pos = from_x_pos + resized_width
  48. with_alpha_s = alpha_s * element[:, :, c]
  49. with_alpha_1 = alpha_1 * img[from_y_pos:to_y_pos, from_x_pos:to_x_pos, c]
  50. img[from_y_pos:to_y_pos, from_x_pos:to_x_pos, c] = with_alpha_s + with_alpha_1
  51. return True