PIL库的crop函数(图片裁剪操作)

from PIL import Image

使用PIL裁切图片使用PIL需要引用Image,使用Image的open(file)方法可以返回打开的图片,使用crop((x0,y0,x1,y1))方法可以对图片做裁切。

crop((x0,y0,x1,y1)), x0是距离左边界|的距离,y0是距离上边界—的距离,x1是x0+要截的宽度,y1是y0+要截的高度

区域由一个4元组定义,表示为坐标是 (left, upper, right, lower),Python Imaging Library 使用左上角为 (0, 0)的坐标系统

box(100,100,200,200)就表示矩形最左侧的竖线离左轴的距离为100,最上侧的横线离上轴的距离为100,最右侧的竖线离左轴的距离为200,最下侧的横线离上轴的距离为200(就是截取矩形的左上顶点的坐标为(100,100),右下顶点的坐标为(200,200)

 


实例:

img的大小为(222,222)

    # Returns a rectangular region from this image.
    def get_tile(self, img, n):
        w = float(img.size[0]) / self.grid_size # w = 222/3 = 74
        y = int(n / self.grid_size)             # y = 0,0,0,1,1,1,2,2,2
        x = n % self.grid_size                  # x = 0,1,2,0,1,2,0,1,2
        tile = img.crop([x * w, y * w, (x + 1) * w, (y + 1) * w]) # Returns a rectangular region from this image.
        return tile
        for n in range(n_grids): # n=0,1,2,3,4,5,6,7,8
            tiles[n] = self.get_tile(img, n)

下面为总共9次截取矩形的四个坐标: 

0 0 74 74

74 0 148 74

148 0 222 74

0 74 74 148

74 74 148 148

148 74 222 148

0 148 74 222

74 148 148 222

148 148 222 222

那么截取的矩形顺序依次为下图的1,2,3,4,5,6,7,8,9

 python PIL库的crop函数--图片裁剪操作_banxia1995的博客-CSDN博客_crop函数

猜你喜欢

转载自blog.csdn.net/weixin_43135178/article/details/126418747