Crop an image in the centre using PIL

后端 未结 7 1235
闹比i
闹比i 2021-01-31 03:41

How can I crop an image in the center? Because I know that the box is a 4-tuple defining the left, upper, right, and lower pixel coordinate but I don\'t know how to get these co

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 04:13

    One potential problem with the proposed solution is in the case there is an odd difference between the desired size, and old size. You can't have a half pixel on each side. One has to choose a side to put an extra pixel on.

    If there is an odd difference for the horizontal the code below will put the extra pixel to the right, and if there is and odd difference on the vertical the extra pixel goes to the bottom.

    import numpy as np
    
    def center_crop(img, new_width=None, new_height=None):        
    
        width = img.shape[1]
        height = img.shape[0]
    
        if new_width is None:
            new_width = min(width, height)
    
        if new_height is None:
            new_height = min(width, height)
    
        left = int(np.ceil((width - new_width) / 2))
        right = width - int(np.floor((width - new_width) / 2))
    
        top = int(np.ceil((height - new_height) / 2))
        bottom = height - int(np.floor((height - new_height) / 2))
    
        if len(img.shape) == 2:
            center_cropped_img = img[top:bottom, left:right]
        else:
            center_cropped_img = img[top:bottom, left:right, ...]
    
        return center_cropped_img
    

提交回复
热议问题