crop center portion of a numpy image

后端 未结 5 1436
醉梦人生
醉梦人生 2020-12-08 13:52

Let\'s say I have a numpy image of some width x and height y. I have to crop the center portion of the image to width cropx and height cropy. Let\'s assume that cropx and cr

5条回答
  •  长情又很酷
    2020-12-08 14:21

    Something along these lines -

    def crop_center(img,cropx,cropy):
        y,x = img.shape
        startx = x//2-(cropx//2)
        starty = y//2-(cropy//2)    
        return img[starty:starty+cropy,startx:startx+cropx]
    

    Sample run -

    In [45]: img
    Out[45]: 
    array([[88, 93, 42, 25, 36, 14, 59, 46, 77, 13, 52, 58],
           [43, 47, 40, 48, 23, 74, 12, 33, 58, 93, 87, 87],
           [54, 75, 79, 21, 15, 44, 51, 68, 28, 94, 78, 48],
           [57, 46, 14, 98, 43, 76, 86, 56, 86, 88, 96, 49],
           [52, 83, 13, 18, 40, 33, 11, 87, 38, 74, 23, 88],
           [81, 28, 86, 89, 16, 28, 66, 67, 80, 23, 95, 98],
           [46, 30, 18, 31, 73, 15, 90, 77, 71, 57, 61, 78],
           [33, 58, 20, 11, 80, 25, 96, 80, 27, 40, 66, 92],
           [13, 59, 77, 53, 91, 16, 47, 79, 33, 78, 25, 66],
           [22, 80, 40, 24, 17, 85, 20, 70, 81, 68, 50, 80]])
    
    In [46]: crop_center(img,4,6)
    Out[46]: 
    array([[15, 44, 51, 68],
           [43, 76, 86, 56],
           [40, 33, 11, 87],
           [16, 28, 66, 67],
           [73, 15, 90, 77],
           [80, 25, 96, 80]])
    

提交回复
热议问题