手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

python如何提取图片的特定区域

时间:2024-10-18 14:20:01

1、crop 方法函数原型为:Image.crop(box=None)Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.This is a lazy operation. Changes to the source image may or may not be reflected in the cropped image. To break the connection, call the load() method on the cropped copy.Parameters: box – The crop rectangle, as a (left, upper, right, lower)-tuple.Return type: ImageReturns: An Image object.

2、通过矩形的左上角的坐标和右下角的坐标,即可构造box,例如下面的代码:box = (100, 100, 400, 400)region = im.crop(box)

3、通过提取除ROI时,上面例子为 region,保存ROI到图像则使用类 Image 的 save 方法:region.save(filename)

4、写一个Demo例子,捂执涡扔使用人脸数据库GENKI部分的图像做实验,该数据的数字子集GENKI-SZSL提供人脸区域的坐标和大小。提取代码如下:from PIL import Imageimport ossrc = '.'imlist = open(src + '/GENKI-SZSL_Images.txt', 'r').readlines()rs = [float(line.split()[1]) for line in open(src + '/GENKI-SZSL_labels.txt', 'r').readlines()]cs = [float(line.split()[0]) for line in open(src + '/GENKI-SZSL_labels.txt', 'r').readlines()]ss = [float(line.split()[2]) for line in open(src + '/GENKI-SZSL_labels.txt', 'r').readlines()]for i in range(0, len(rs)): path = src + '/images/' + imlist[i].strip() filename = src + '/output/' + imlist[i].strip() try: im = Image.open(path) except: continue r = rs[i] c = cs[i] s = ss[i] xLeft = int(c - s/2) yUpper = int(r - s/2) xRight = int(c + s/2) yLower = int(r + s/2) region = im.crop((xLeft, yUpper, xRight, yLower)) region.save(filename)

© 手抄报圈