@@ -376,7 +376,7 @@ def get_params(img, output_size):
376376 # # randomized cropping
377377 # i = np.random.randint(i-3, i+4)
378378 # j = np.random.randint(j-3, j+4)
379-
379+
380380 return i , j , th , tw
381381
382382 def __call__ (self , img ):
@@ -514,3 +514,47 @@ def __call__(self, img):
514514 transform = self .get_params (self .brightness , self .contrast ,
515515 self .saturation , self .hue )
516516 return np .array (transform (pil ))
517+
518+ class Crop (object ):
519+ """Crops the given PIL Image to a rectangular region based on a given
520+ 4-tuple defining the left, upper pixel coordinated, hight and width size.
521+
522+ Args:
523+ a tuple: (upper pixel coordinate, left pixel coordinate, hight, width)-tuple
524+ """
525+
526+ def __init__ (self , i , j , h , w ):
527+ """
528+ i: Upper pixel coordinate.
529+ j: Left pixel coordinate.
530+ h: Height of the cropped image.
531+ w: Width of the cropped image.
532+ """
533+ self .i = i
534+ self .j = j
535+ self .h = h
536+ self .w = w
537+
538+ def __call__ (self , img ):
539+ """
540+ Args:
541+ img (numpy.ndarray (C x H x W)): Image to be cropped.
542+ Returns:
543+ img (numpy.ndarray (C x H x W)): Cropped image.
544+ """
545+
546+ i , j , h , w = self .i , self .j , self .h , self .w
547+
548+ if not (_is_numpy_image (img )):
549+ raise TypeError ('img should be ndarray. Got {}' .format (type (img )))
550+ if img .ndim == 3 :
551+ return img [i :i + h , j :j + w , :]
552+ elif img .ndim == 2 :
553+ return img [i :i + h , j :j + w ]
554+ else :
555+ raise RuntimeError (
556+ 'img should be ndarray with 2 or 3 dimensions. Got {}' .format (img .ndim ))
557+
558+ def __repr__ (self ):
559+ return self .__class__ .__name__ + '(i={0},j={1},h={2},w={3})' .format (
560+ self .i , self .j , self .h , self .w )
0 commit comments