segmentation.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. All segmentation methods applied on images
  3. """
  4. # main imports
  5. import numpy as np
  6. # image processing imports
  7. from PIL import Image
  8. def divide_in_blocks(image, block_size, pil=True):
  9. '''Divide image into equal size blocks
  10. Args:
  11. image: PIL Image or Numpy array
  12. block: tuple (width, height) representing the size of each dimension of the block
  13. pil: block type returned as PIL Image (default True)
  14. Returns:
  15. list containing all 2D Numpy blocks (in RGB or not)
  16. Raises:
  17. ValueError: If `image_width` or `image_height` are not compatible to produce correct block sizes
  18. Example:
  19. >>> import numpy as np
  20. >>> from PIL import Image
  21. >>> from ipfml.processing import transform, segmentation
  22. >>> image_values = np.random.randint(255, size=(800, 800, 3))
  23. >>> blocks = segmentation.divide_in_blocks(image_values, (20, 20))
  24. >>> len(blocks)
  25. 1600
  26. >>> blocks[0].width
  27. 20
  28. >>> blocks[0].height
  29. 20
  30. >>> img_l = Image.open('./images/test_img.png')
  31. >>> L = transform.get_LAB_L(img_l)
  32. >>> blocks_L = segmentation.divide_in_blocks(L, (100, 100))
  33. >>> len(blocks_L)
  34. 4
  35. >>> blocks_L[0].width
  36. 100
  37. '''
  38. blocks = []
  39. mode = 'RGB'
  40. # convert in Numpy array
  41. image_array = np.array(image)
  42. # check dimension of input image
  43. if image_array.ndim != 3:
  44. mode = 'L'
  45. image_width, image_height = image_array.shape
  46. else:
  47. image_width, image_height, _ = image_array.shape
  48. # check size compatibility
  49. width, height = block_size
  50. if (image_width % width != 0):
  51. raise ValueError("Width size issue, block size not compatible")
  52. if (image_height % height != 0):
  53. raise ValueError("Height size issue, block size not compatible")
  54. nb_block_width = image_width / width
  55. nb_block_height = image_height / height
  56. for i in range(int(nb_block_width)):
  57. begin_x = i * width
  58. for j in range(int(nb_block_height)):
  59. begin_y = j * height
  60. # getting sub block information
  61. current_block = image_array[begin_x:(begin_x + width), begin_y:(
  62. begin_y + height)]
  63. if pil:
  64. blocks.append(
  65. Image.fromarray(current_block.astype('uint8'), mode))
  66. else:
  67. blocks.append(current_block)
  68. return blocks