@@ -219,69 +219,3 @@ def _aff_is_diag(aff):
219
219
''' Utility function returning True if affine is nearly diagonal '''
220
220
rzs_aff = aff [:3 , :3 ]
221
221
return np .allclose (rzs_aff , np .diag (np .diag (rzs_aff )))
222
-
223
-
224
- def crop_image (img , bounds , margin = 0 ):
225
- ''' Crop ``img`` to specified bounds
226
-
227
- The image is cropped in the current orientation; no rotation or resampling
228
- is performed.
229
- The affine matrix is updated with the new intercept, so that all values are
230
- found at the same RAS locations.
231
-
232
- Parameters
233
- ----------
234
- img : ``spatialimage``
235
- Image to be cropped
236
- bounds : (3, 2) array-like
237
- Minimum and maximum (inclusive) voxel indices, in each dimension, to be
238
- included in cropped image
239
- margin : int, optional
240
- Margin, in voxels, to include on each side of cropped image
241
-
242
- Returns
243
- -------
244
- cropped_img : ``spatialimage``
245
- Version of `img` with cropped data array and updated affine matrix
246
- '''
247
-
248
- shape = np .reshape (img .shape [:3 ], (3 , 1 ))
249
- bounds = np .asanyarray (bounds )
250
- if bounds .shape != (3 , 2 ):
251
- raise ValueError ("bounds must be interpretable as a 3x2 array" )
252
- elif np .any (bounds > shape ):
253
- raise ValueError ("bounds must not exceed image dimensions" )
254
-
255
- # Permit negative bounds
256
- if np .any (bounds < 0 ):
257
- bounds = (bounds + shape ) % shape
258
-
259
- if np .any (bounds < 0 ):
260
- raise ValueError ("negative bounds may not exceed image dimensions" )
261
- elif np .any (bounds [:, 0 ] > bounds [:, 1 ]):
262
- raise ValueError ("degenerate (0 width) crops are not permitted" )
263
-
264
- # Add margin in all directions
265
- bounds += np .array ([- margin , margin ])
266
-
267
- # Set min/max
268
- bounds [bounds < 0 ] = 0
269
- over = bounds [:, 1 ] > shape .reshape (- 1 ) - 1
270
- bounds [over , 1 ] = shape [over , 0 ] - 1
271
-
272
- # Include upper bounds
273
- bounds [:, 1 ] += 1
274
-
275
- # Return original image if no cropping required
276
- if np .array_equal (bounds , np .hstack (([[0 ], [0 ], [0 ]], shape ))):
277
- return img
278
-
279
- x , y , z = bounds
280
- new_origin = np .vstack ((bounds [:, [0 ]], 1 ))
281
-
282
- bounded_data = img .get_data ()[x [0 ]:x [1 ], y [0 ]:y [1 ], z [0 ]:z [1 ]]
283
-
284
- new_aff = img .affine .copy ()
285
- new_aff [:, [3 ]] = img .affine .dot (new_origin )
286
-
287
- return img .__class__ (bounded_data , new_aff , img .header )
0 commit comments