You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

411 lines
14 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file slic.c
  2. ** @brief SLIC superpixels - Definition
  3. ** @author Andrea Vedaldi
  4. **/
  5. /*
  6. Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
  7. All rights reserved.
  8. This file is part of the VLFeat library and is made available under
  9. the terms of the BSD license (see the COPYING file).
  10. */
  11. /**
  12. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  13. @page slic Simple Linear Iterative Clustering (SLIC)
  14. @author Andrea Vedaldi
  15. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  16. @ref slic.h implements the *Simple Linear Iterative Clustering* (SLIC)
  17. algorithm, an image segmentation method described in @cite{achanta10slic}.
  18. - @ref slic-overview
  19. - @ref slic-usage
  20. - @ref slic-tech
  21. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  22. @section slic-overview Overview
  23. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  24. SLIC @cite{achanta10slic} is a simple and efficient method to decompose
  25. an image in visually homogeneous regions. It is based on a spatially
  26. localized version of k-means clustering. Similar to mean shift or
  27. quick shift (@ref quickshift.h), each pixel is associated to a feature
  28. vector
  29. @f[
  30. \Psi(x,y) =
  31. \left[
  32. \begin{array}{c}
  33. \lambda x \\
  34. \lambda y \\
  35. I(x,y)
  36. \end{array}
  37. \right]
  38. @f]
  39. and then k-means clustering is run on those. As discussed below, the
  40. coefficient @f$ \lambda @f$ balances the spatial and appearance
  41. components of the feature vectors, imposing a degree of spatial
  42. regularization to the extracted regions.
  43. SLIC takes two parameters: the nominal size of the regions
  44. (superpixels) @c regionSize and the strength of the spatial
  45. regularization @c regularizer. The image is first divided into a grid
  46. with step @c regionSize. The center of each grid tile is then used to
  47. initialize a corresponding k-means (up to a small shift to avoid
  48. image edges). Finally, the k-means centers and clusters are refined by
  49. using the Lloyd algorithm, yielding segmenting the image. As a
  50. further restriction and simplification, during the k-means iterations
  51. each pixel can be assigned to only the <em>2 x 2</em> centers
  52. corresponding to grid tiles adjacent to the pixel.
  53. The parameter @c regularizer sets the trade-off between clustering
  54. appearance and spatial regularization. This is obtained by setting
  55. @f[
  56. \lambda = \frac{\mathtt{regularizer}}{\mathtt{regionSize}}
  57. @f]
  58. in the definition of the feature @f$ \psi(x,y) @f$.
  59. After the k-means step, SLIC optionally
  60. removes any segment whose area is smaller than a threshld @c minRegionSize
  61. by merging them into larger ones.
  62. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  63. @section slic-usage Usage from the C library
  64. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  65. To compute the SLIC superpixels of an image use the function
  66. ::vl_slic_segment.
  67. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  68. @section slic-tech Technical details
  69. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  70. SLIC starts by dividing the image domain into a regular grid with @f$
  71. M \times N @f$ tiles, where
  72. @f[
  73. M = \lceil \frac{\mathtt{imageWidth}}{\mathtt{regionSize}} \rceil,
  74. \quad
  75. N = \lceil \frac{\mathtt{imageHeight}}{\mathtt{regionSize}} \rceil.
  76. @f]
  77. A region (superpixel or k-means cluster) is initialized from each grid
  78. center
  79. @f[
  80. x_i = \operatorname{round} i \frac{\mathtt{imageWidth}}{\mathtt{regionSize}}
  81. \quad
  82. y_j = \operatorname{round} j \frac{\mathtt{imageWidth}}{\mathtt{regionSize}}.
  83. @f]
  84. In order to avoid placing these centers on top of image
  85. discontinuities, the centers are then moved in a 3 x 3
  86. neighbourohood to minimize the edge strength
  87. @f[
  88. \operatorname{edge}(x,y) =
  89. \| I(x+1,y) - I(x-1,y) \|_2^2 +
  90. \| I(x,y+1) - I(x,y-1) \|_2^2.
  91. @f]
  92. Then the regions are obtained by running k-means clustering, started
  93. from the centers
  94. @f[
  95. C = \{ \Psi(x_i,y_j), i=0,1,\dots,M-1\ j=0,1,\dots,N-1 \}
  96. @f]
  97. thus obtained. K-means uses the standard LLoyd algorithm alternating
  98. assigning pixels to the clostest centers a re-estiamting the centers
  99. as the average of the corresponding feature vectors of the pixel
  100. assigned to them. The only difference compared to standard k-means is
  101. that each pixel can be assigned only to the center originated from the
  102. neighbour tiles. This guarantees that there are exactly four
  103. pixel-to-center comparisons at each round of minimization, which
  104. threfore cost @f$ O(n) @f$, where @f$ n @f$ is the number of
  105. superpixels.
  106. After k-means has converged, SLIC eliminates any connected region whose
  107. area is less than @c minRegionSize pixels. This is done by greedily
  108. merging regions to neighbour ones: the pixels @f$ p @f$ are scanned in
  109. lexicographical order and the corresponding connected components
  110. are visited. If a region has already been visited, it is skipped; if not,
  111. its area is computed and if this is less than @c minRegionSize its label
  112. is changed to the one of a neighbour
  113. region at @f$ p @f$ that has already been vistied (there is always one
  114. except for the very first pixel).
  115. */
  116. #include "slic.h"
  117. #include "mathop.h"
  118. #include <math.h>
  119. #include <string.h>
  120. /** @brief SLIC superpixel segmentation
  121. ** @param segmentation segmentation.
  122. ** @param image image to segment.
  123. ** @param width image width.
  124. ** @param height image height.
  125. ** @param numChannels number of image channels (depth).
  126. ** @param regionSize nominal size of the regions.
  127. ** @param regularization trade-off between appearance and spatial terms.
  128. ** @param minRegionSize minimum size of a segment.
  129. **
  130. ** The function computes the SLIC superpixels of the specified image @a image.
  131. ** @a image is a pointer to an @c width by @c height by @c by numChannles array of @c float.
  132. ** @a segmentation is a pointer to a @c width by @c height array of @c vl_uint32.
  133. ** @a segmentation contain the labels of each image pixels, from 0 to
  134. ** the number of regions minus one.
  135. **
  136. ** @sa @ref slic-overview, @ref slic-tech
  137. **/
  138. void
  139. vl_slic_segment (vl_uint32 * segmentation,
  140. float const * image,
  141. vl_size width,
  142. vl_size height,
  143. vl_size numChannels,
  144. vl_size regionSize,
  145. float regularization,
  146. vl_size minRegionSize)
  147. {
  148. vl_index i, x, y, u, v, k, region ;
  149. vl_uindex iter ;
  150. vl_size const numRegionsX = (vl_size) ceil((double) width / regionSize) ;
  151. vl_size const numRegionsY = (vl_size) ceil((double) height / regionSize) ;
  152. vl_size const numRegions = numRegionsX * numRegionsY ;
  153. vl_size const numPixels = width * height ;
  154. float * centers ;
  155. float * edgeMap ;
  156. float previousEnergy = VL_INFINITY_F ;
  157. float startingEnergy ;
  158. vl_uint32 * masses ;
  159. vl_size const maxNumIterations = 100 ;
  160. assert(segmentation) ;
  161. assert(image) ;
  162. assert(width >= 1) ;
  163. assert(height >= 1) ;
  164. assert(numChannels >= 1) ;
  165. assert(regionSize >= 1) ;
  166. assert(regularization >= 0) ;
  167. #define atimage(x,y,k) image[(x)+(y)*width+(k)*width*height]
  168. #define atEdgeMap(x,y) edgeMap[(x)+(y)*width]
  169. edgeMap = (float*)vl_calloc(numPixels, sizeof(float)) ;
  170. masses = (vl_uint32*)vl_malloc(sizeof(vl_uint32) * numPixels) ;
  171. centers = (float*)vl_malloc(sizeof(float) * (2 + numChannels) * numRegions) ;
  172. /* compute edge map (gradient strength) */
  173. for (k = 0 ; k < (signed)numChannels ; ++k) {
  174. for (y = 1 ; y < (signed)height-1 ; ++y) {
  175. for (x = 1 ; x < (signed)width-1 ; ++x) {
  176. float a = atimage(x-1,y,k) ;
  177. float b = atimage(x+1,y,k) ;
  178. float c = atimage(x,y+1,k) ;
  179. float d = atimage(x,y-1,k) ;
  180. atEdgeMap(x,y) += (a - b) * (a - b) + (c - d) * (c - d) ;
  181. }
  182. }
  183. }
  184. /* initialize K-means centers */
  185. i = 0 ;
  186. for (v = 0 ; v < (signed)numRegionsY ; ++v) {
  187. for (u = 0 ; u < (signed)numRegionsX ; ++u) {
  188. vl_index xp ;
  189. vl_index yp ;
  190. vl_index centerx = 0 ;
  191. vl_index centery = 0 ;
  192. float minEdgeValue = VL_INFINITY_F ;
  193. x = (vl_index) vl_round_d(regionSize * (u + 0.5)) ;
  194. y = (vl_index) vl_round_d(regionSize * (v + 0.5)) ;
  195. x = VL_MAX(VL_MIN(x, (signed)width-1),0) ;
  196. y = VL_MAX(VL_MIN(y, (signed)height-1),0) ;
  197. /* search in a 3x3 neighbourhood the smallest edge response */
  198. for (yp = VL_MAX(0, y-1) ; yp <= VL_MIN((signed)height-1, y+1) ; ++ yp) {
  199. for (xp = VL_MAX(0, x-1) ; xp <= VL_MIN((signed)width-1, x+1) ; ++ xp) {
  200. float thisEdgeValue = atEdgeMap(xp,yp) ;
  201. if (thisEdgeValue < minEdgeValue) {
  202. minEdgeValue = thisEdgeValue ;
  203. centerx = xp ;
  204. centery = yp ;
  205. }
  206. }
  207. }
  208. /* initialize the new center at this location */
  209. centers[i++] = (float) centerx ;
  210. centers[i++] = (float) centery ;
  211. for (k = 0 ; k < (signed)numChannels ; ++k) {
  212. centers[i++] = atimage(centerx,centery,k) ;
  213. }
  214. }
  215. }
  216. /* run k-means iterations */
  217. for (iter = 0 ; iter < maxNumIterations ; ++iter) {
  218. float factor = regularization / (regionSize * regionSize) ;
  219. float energy = 0 ;
  220. /* assign pixels to centers */
  221. for (y = 0 ; y < (signed)height ; ++y) {
  222. for (x = 0 ; x < (signed)width ; ++x) {
  223. vl_index u = floor((double)x / regionSize - 0.5) ;
  224. vl_index v = floor((double)y / regionSize - 0.5) ;
  225. vl_index up, vp ;
  226. float minDistance = VL_INFINITY_F ;
  227. for (vp = VL_MAX(0, v) ; vp <= VL_MIN((signed)numRegionsY-1, v+1) ; ++vp) {
  228. for (up = VL_MAX(0, u) ; up <= VL_MIN((signed)numRegionsX-1, u+1) ; ++up) {
  229. vl_index region = up + vp * numRegionsX ;
  230. float centerx = centers[(2 + numChannels) * region + 0] ;
  231. float centery = centers[(2 + numChannels) * region + 1] ;
  232. float spatial = (x - centerx) * (x - centerx) + (y - centery) * (y - centery) ;
  233. float appearance = 0 ;
  234. float distance ;
  235. for (k = 0 ; k < (signed)numChannels ; ++k) {
  236. float centerz = centers[(2 + numChannels) * region + k + 2] ;
  237. float z = atimage(x,y,k) ;
  238. appearance += (z - centerz) * (z - centerz) ;
  239. }
  240. distance = appearance + factor * spatial ;
  241. if (minDistance > distance) {
  242. minDistance = distance ;
  243. segmentation[x + y * width] = (vl_uint32)region ;
  244. }
  245. }
  246. }
  247. energy += minDistance ;
  248. }
  249. }
  250. /*
  251. VL_PRINTF("vl:slic: iter %d: energy: %g\n", iter, energy) ;
  252. */
  253. /* check energy termination conditions */
  254. if (iter == 0) {
  255. startingEnergy = energy ;
  256. } else {
  257. if ((previousEnergy - energy) < 1e-5 * (startingEnergy - energy)) {
  258. break ;
  259. }
  260. }
  261. previousEnergy = energy ;
  262. /* recompute centers */
  263. memset(masses, 0, sizeof(vl_uint32) * width * height) ;
  264. memset(centers, 0, sizeof(float) * (2 + numChannels) * numRegions) ;
  265. for (y = 0 ; y < (signed)height ; ++y) {
  266. for (x = 0 ; x < (signed)width ; ++x) {
  267. vl_index pixel = x + y * width ;
  268. vl_index region = segmentation[pixel] ;
  269. masses[region] ++ ;
  270. centers[region * (2 + numChannels) + 0] += x ;
  271. centers[region * (2 + numChannels) + 1] += y ;
  272. for (k = 0 ; k < (signed)numChannels ; ++k) {
  273. centers[region * (2 + numChannels) + k + 2] += atimage(x,y,k) ;
  274. }
  275. }
  276. }
  277. for (region = 0 ; region < (signed)numRegions ; ++region) {
  278. float mass = VL_MAX(masses[region], 1e-8) ;
  279. for (i = (2 + numChannels) * region ;
  280. i < (signed)(2 + numChannels) * (region + 1) ;
  281. ++i) {
  282. centers[i] /= mass ;
  283. }
  284. }
  285. }
  286. vl_free(masses) ;
  287. vl_free(centers) ;
  288. vl_free(edgeMap) ;
  289. /* elimiate small regions */
  290. {
  291. vl_uint32 * cleaned = (vl_uint32*)vl_calloc(numPixels, sizeof(vl_uint32)) ;
  292. vl_uindex * segment = (vl_uindex*)vl_malloc(sizeof(vl_uindex) * numPixels) ;
  293. vl_size segmentSize ;
  294. vl_uint32 label ;
  295. vl_uint32 cleanedLabel ;
  296. vl_size numExpanded ;
  297. vl_index const dx [] = {+1, -1, 0, 0} ;
  298. vl_index const dy [] = { 0, 0, +1, -1} ;
  299. vl_index direction ;
  300. vl_index pixel ;
  301. for (pixel = 0 ; pixel < (signed)numPixels ; ++pixel) {
  302. if (cleaned[pixel]) continue ;
  303. label = segmentation[pixel] ;
  304. numExpanded = 0 ;
  305. segmentSize = 0 ;
  306. segment[segmentSize++] = pixel ;
  307. /*
  308. find cleanedLabel as the label of an already cleaned
  309. region neihbour of this pixel
  310. */
  311. cleanedLabel = label + 1 ;
  312. cleaned[pixel] = label + 1 ;
  313. x = pixel % width ;
  314. y = pixel / width ;
  315. for (direction = 0 ; direction < 4 ; ++direction) {
  316. vl_index xp = x + dx[direction] ;
  317. vl_index yp = y + dy[direction] ;
  318. vl_index neighbor = xp + yp * width ;
  319. if (0 <= xp && xp < (signed)width &&
  320. 0 <= yp && yp < (signed)height &&
  321. cleaned[neighbor]) {
  322. cleanedLabel = cleaned[neighbor] ;
  323. }
  324. }
  325. /* expand the segment */
  326. while (numExpanded < segmentSize) {
  327. vl_index open = segment[numExpanded++] ;
  328. x = open % width ;
  329. y = open / width ;
  330. for (direction = 0 ; direction < 4 ; ++direction) {
  331. vl_index xp = x + dx[direction] ;
  332. vl_index yp = y + dy[direction] ;
  333. vl_index neighbor = xp + yp * width ;
  334. if (0 <= xp && xp < (signed)width &&
  335. 0 <= yp && yp < (signed)height &&
  336. cleaned[neighbor] == 0 &&
  337. segmentation[neighbor] == label) {
  338. cleaned[neighbor] = label + 1 ;
  339. segment[segmentSize++] = neighbor ;
  340. }
  341. }
  342. }
  343. /* change label to cleanedLabel if the semgent is too small */
  344. if (segmentSize < minRegionSize) {
  345. while (segmentSize > 0) {
  346. cleaned[segment[--segmentSize]] = cleanedLabel ;
  347. }
  348. }
  349. }
  350. /* restore base 0 indexing of the regions */
  351. for (pixel = 0 ; pixel < (signed)numPixels ; ++pixel) cleaned[pixel] -- ;
  352. memcpy(segmentation, cleaned, numPixels * sizeof(vl_uint32)) ;
  353. vl_free(cleaned) ;
  354. vl_free(segment) ;
  355. }
  356. }