Regions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import pandas as pd
  2. from image_features_extraction import my_iterator
  3. from image_features_extraction import Region
  4. from image_features_extraction import MyException
  5. from image_features_extraction import Features
  6. from skimage.measure import label, regionprops
  7. from image_features_extraction import Utils
  8. class Regions(my_iterator.my_iterator):
  9. """
  10. This class represent a collection of regions: segmented image elements
  11. It cannot be instanced directly. It is returned from the object :class:`Image` through the function
  12. Regions(...)
  13. :example:
  14. >>> import image_features_extraction as fe
  15. >>> imgs = fe.Images(folder_name)
  16. >>> img = imgs.item(1)
  17. >>> regs = img.Regions()
  18. """
  19. def __init__(self, obj_regions):
  20. try:
  21. #self.__iterator_init__()
  22. super().__init__()
  23. self.__obj_regions_org = obj_regions
  24. self.__obj_regions = regionprops(obj_regions) # used regionprops from skimage
  25. self.count_update(len(self.__obj_regions))
  26. except MyException.MyException as e:
  27. print(e.args)
  28. def __regions_obj(self):
  29. """
  30. This function returns the Internal object regions. it is used only for debugging
  31. """
  32. return self.__obj_regions_org
  33. def item(self, i):
  34. """
  35. Item(..) returns the i-th image element of the regions.
  36. :param i: the i-th element of the collection region
  37. :type i: int
  38. :returns: Region
  39. :rtype: object
  40. :example:
  41. >>> import image_features_extraction as fe
  42. >>> imgs = fe.Images(folder_name)
  43. >>> img = imgs.item(1)
  44. >>> regs = img.Regions()
  45. >>> reg = regs.item(1)
  46. """
  47. try:
  48. if i >= self.count():
  49. raise MyException.MyException("error: index out of bound")
  50. return Region.Region(self.__obj_regions[i])
  51. except MyException.MyException as e:
  52. print(e.args)
  53. return None
  54. def prop_values(self, prop_name):
  55. """
  56. Measure the values of the specified property/measure name (e.g., 'area') for all
  57. elements contained in the object Regions.
  58. :param prop_name: name of the property to measure (e.g, 'area')
  59. :type prop_name: string
  60. :returns: property name values
  61. :rtype: List
  62. :example:
  63. >>> import image_features_extraction as fe
  64. >>> imgs = fe.Images(folder_name)
  65. >>> img = imgs.item(1)
  66. >>> regs = img.Regions()
  67. >>> areas = regs.prop_values('area')
  68. The following properties can be accessed as attributes or keys:
  69. **area** : int
  70. Number of pixels of region.
  71. **bbox** : tuple
  72. Bounding box ``(min_row, min_col, max_row, max_col)``.
  73. Pixels belonging to the bounding box are in the half-open interval
  74. ``[min_row; max_row)`` and ``[min_col; max_col)``.
  75. **bbox_area** : int
  76. Number of pixels of bounding box.
  77. **centroid** : array
  78. Centroid coordinate tuple ``(row, col)``.
  79. **convex_area** : int
  80. Number of pixels of convex hull image.
  81. **convex_image** : (H, J) ndarray
  82. Binary convex hull image which has the same size as bounding box.
  83. **coords** : (N, 2) ndarray
  84. Coordinate list ``(row, col)`` of the region.
  85. **eccentricity** : float
  86. Eccentricity of the ellipse that has the same second-moments as the
  87. region. The eccentricity is the ratio of the focal distance
  88. (distance between focal points) over the major axis length.
  89. The value is in the interval [0, 1).
  90. When it is 0, the ellipse becomes a circle.
  91. **equivalent_diameter** : float
  92. The diameter of a circle with the same area as the region.
  93. **euler_number** : int
  94. Euler characteristic of region. Computed as number of objects (= 1)
  95. subtracted by number of holes (8-connectivity).
  96. **extent** : float
  97. Ratio of pixels in the region to pixels in the total bounding box.
  98. Computed as ``area / (rows * cols)``
  99. **filled_area** : int
  100. Number of pixels of filled region.
  101. **filled_image** : (H, J) ndarray
  102. Binary region image with filled holes which has the same size as
  103. bounding box.
  104. **image** : (H, J) ndarray
  105. Sliced binary region image which has the same size as bounding box.
  106. **inertia_tensor** : (2, 2) ndarray
  107. Inertia tensor of the region for the rotation around its mass.
  108. **inertia_tensor_eigvals** : tuple
  109. The two eigen values of the inertia tensor in decreasing order.
  110. **intensity_image** : ndarray
  111. Image inside region bounding box.
  112. **label** : int
  113. The label in the labeled input image.
  114. **local_centroid** : array
  115. Centroid coordinate tuple ``(row, col)``, relative to region bounding
  116. box.
  117. **major_axis_length** : float
  118. The length of the major axis of the ellipse that has the same
  119. normalized second central moments as the region.
  120. **max_intensity** : float
  121. Value with the greatest intensity in the region.
  122. **mean_intensity** : float
  123. Value with the mean intensity in the region.
  124. **min_intensity** : float
  125. Value with the least intensity in the region.
  126. **minor_axis_length** : float
  127. The length of the minor axis of the ellipse that has the same
  128. normalized second central moments as the region.
  129. **moments** : (3, 3) ndarray
  130. Spatial moments up to 3rd order::
  131. m_ji = sum{ array(x, y) * x^j * y^i }
  132. where the sum is over the `x`, `y` coordinates of the region.
  133. **moments_central** : (3, 3) ndarray
  134. Central moments (translation invariant) up to 3rd order::
  135. mu_ji = sum{ array(x, y) * (x - x_c)^j * (y - y_c)^i }
  136. where the sum is over the `x`, `y` coordinates of the region,
  137. and `x_c` and `y_c` are the coordinates of the region's centroid.
  138. **moments_hu** : tuple
  139. Hu moments (translation, scale and rotation invariant).
  140. **moments_normalized** : (3, 3) ndarray
  141. Normalized moments (translation and scale invariant) up to 3rd order::
  142. nu_ji = mu_ji / m_00^[(i+j)/2 + 1]
  143. where `m_00` is the zeroth spatial moment.
  144. **orientation** : float
  145. Angle between the X-axis and the major axis of the ellipse that has
  146. the same second-moments as the region. Ranging from `-pi/2` to
  147. `pi/2` in counter-clockwise direction.
  148. **perimeter** : float
  149. Perimeter of object which approximates the contour as a line
  150. through the centers of border pixels using a 4-connectivity.
  151. **solidity** : float
  152. Ratio of pixels in the region to pixels of the convex hull image.
  153. **weighted_centroid** : array
  154. Centroid coordinate tuple ``(row, col)`` weighted with intensity
  155. image.
  156. **weighted_local_centroid** : array
  157. Centroid coordinate tuple ``(row, col)``, relative to region bounding
  158. box, weighted with intensity image.
  159. **weighted_moments** : (3, 3) ndarray
  160. Spatial moments of intensity image up to 3rd order::
  161. wm_ji = sum{ array(x, y) * x^j * y^i }
  162. where the sum is over the `x`, `y` coordinates of the region.
  163. **weighted_moments_central** : (3, 3) ndarray
  164. Central moments (translation invariant) of intensity image up to
  165. 3rd order::
  166. wmu_ji = sum{ array(x, y) * (x - x_c)^j * (y - y_c)^i }
  167. where the sum is over the `x`, `y` coordinates of the region,
  168. and `x_c` and `y_c` are the coordinates of the region's weighted
  169. centroid.
  170. **weighted_moments_hu** : tuple
  171. Hu moments (translation, scale and rotation invariant) of intensity
  172. image.
  173. **weighted_moments_normalized** : (3, 3) ndarray
  174. Normalized moments (translation and scale invariant) of intensity
  175. image up to 3rd order::
  176. wnu_ji = wmu_ji / wm_00^[(i+j)/2 + 1]
  177. where ``wm_00`` is the zeroth spatial moment (intensity-weighted area).
  178. .. [1] http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops
  179. """
  180. try:
  181. vals = []
  182. for i in self.__obj_regions:
  183. vals.append(getattr(i, prop_name))
  184. return vals
  185. except Exception as e:
  186. print(e.args)
  187. return None
  188. def features(self, feature_list):
  189. """
  190. get_features(...) returns a table with all values for the property names given in input, and supplies an
  191. additional parameter for feature classification
  192. :param features: list of property/measure names (e.g, 'area', 'centroid', etc )
  193. :type features: List
  194. :param class_value: classification label
  195. :type class_value: int, string (default=None)
  196. : param image_mask: expernal Image mask to be used for the segmentation
  197. :type image_mask: Image
  198. :returns: table cointaining all property values (columns) for all elements in the regions object (rows)
  199. :rtype: Pandas.DataFrame
  200. :example:
  201. >>> import image_features_extraction as fe
  202. >>> imgs = fe.Images(folder_name)
  203. >>> img = imgs.item(1)
  204. >>> regs = img.Regions()
  205. >>> feature = regs.get_features(['label', 'area','perimeter', 'centroid'], class_value=1)
  206. >>>
  207. >>> # external image mask
  208. >>> img_masks = fe.Images(folder_name)
  209. >>> features = regs.get_features(['label', 'area','perimeter', 'centroid'], class_value=1, image_mask=img_masks.item(1))
  210. """
  211. df = pd.DataFrame()
  212. try:
  213. for feature_name in feature_list:
  214. values = self.prop_values(feature_name)
  215. Utils.insert_values(feature_name, df, values)
  216. return Features.Features(df)
  217. except Exception as e:
  218. print("one or more input labels might be wrong:{}".format(e))
  219. return None