Python提取图片的ROI

图像处理经常需要提取图片的ROI,本文使用Python提取图片的ROI。

使用的Module是PIL (Pillow),一个图像处理库,用到的函数为类 Image 中的 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:    Image
Returns:    An Image object.

知道矩形的左上角的坐标和右下角的坐标,即可构造box,例如下面的代码

box = (100, 100, 400, 400)
region = im.crop(box)

知道如何提取除ROI时,上面例子为 region,保存ROI到图像则使用类 Image 的 save 方法

region.save(filename)

 

给出一个Demo,使用人脸数据库GENKI部分的图像做实验,该数据的数字子集GENKI-SZSL提供人脸区域的坐标和大小。提取代码提供如下

from PIL import Image
import os

src = '.'

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)

代码打包下载:http://pan.baidu.com/s/1dD4opKP 密码:ygu7

Pillow的项目文档地址: http://pillow.readthedocs.org

转载于:https://www.cnblogs.com/cpointer/p/4899800.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值