Image processing often needs to extract ROI from images, and this article uses Python to extract ROI from images.
The module used is PIL (Pillow), an image processing library, the function used for the crop method in the class image.
The function prototypes are:
Image.crop (box= None) Returns a rectangular region fromThis image. The box isA 4-tuple defining the left, upper, right, andLower pixel coordinate. this isA lazy operation. Changes to the source image mayorMay notBe reflectedinchThe cropped image. To Breakthe 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.
By knowing the coordinates of the upper-left corner of the rectangle and the coordinates of the lower-right corner, you can construct the box, such as the following code
box = (+, +, +-)= im.crop (box)
When you know how to extract the ROI, the above example is region, and the save ROI to image uses the Save method of class image
Region.save (filename)
Give a demo, use the face database Genki part of the image to do the experiment, the data subset GENKI-SZSL provides the face area coordinates and the size. The extraction code provides the following
fromPILImportImageImportossrc='.'imlist= Open (src +'/genki-szsl_images.txt','R'). ReadLines () RS= [Float (Line.split () [1]) forLineinchOpen (src +'/genki-szsl_labels.txt','R'). ReadLines ()]cs= [Float (line.split () [0]) forLineinchOpen (src +'/genki-szsl_labels.txt','R'). ReadLines ()]ss= [Float (Line.split () [2]) forLineinchOpen (src +'/genki-szsl_labels.txt','R'). ReadLines ()] forIinchRange (0, Len (RS)): Path= src +'/images/'+imlist[i].strip () filename= src +'/output/'+Imlist[i].strip ()Try: Im=image.open (path)except: ContinueR=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)
Code package Download: Http://pan.baidu.com/s/1dD4opKP Password: ygu7
Pillow Project Document Address: http://pillow.readthedocs.org
The ROI of Python extract images