码迷,mamicode.com
首页 > 编程语言 > 详细

Python提取图片的ROI

时间:2015-10-22 09:15:12      阅读:3016      评论:0      收藏:0      [点我收藏+]

标签:

图像处理经常需要提取图片的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

Python提取图片的ROI

标签:

原文地址:http://www.cnblogs.com/cpointer/p/4899800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!