Example: bankruptcy

Python Imaging Library Overview

|March12,2002|FredrikLundh, ,anefficientinternalrepresentation, ' ,convertbetweenfileformats,printimages, , ,youcanuseJackJansen' ,there' ,includingpointoperations,filteringwitha setofbuilt-inconvolutionkernels, , ' , , ;eitherbyloadingimagesfromfiles,processi ngotherimages, ,usetheopenfunctionintheImagemodule.>>> import Image>>> im = (" ")Ifsuccessful, >>> print , , (512, 512) , (inpixels).Themodeattributedefinesthenum berandnamesofthebandsintheimage, "L"(luminance)forgreyscaleimages,"RGB"fo rtruecolourimages,and"CMYK" , , ,let'sdisplaytheimagewejustloaded: >>> ()(Thestandardversionofshowisnotveryeffi cient, 'thavexvinstalled,itwon' ,itisveryhandyfordebuggingandtests.) , ' , , , :ConvertfilestoJPEG import os, sysimport Imagefor infile in [1:]: outfile = (infile)[0] + ".

Tutorial Using the Image Class The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in ...

Tags:

  Python, Overview, Library, Tutorials, Imaging, Python imaging library overview, Python imaging library

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Python Imaging Library Overview

1 |March12,2002|FredrikLundh, ,anefficientinternalrepresentation, ' ,convertbetweenfileformats,printimages, , ,youcanuseJackJansen' ,there' ,includingpointoperations,filteringwitha setofbuilt-inconvolutionkernels, , ' , , ;eitherbyloadingimagesfromfiles,processi ngotherimages, ,usetheopenfunctionintheImagemodule.>>> import Image>>> im = (" ")Ifsuccessful, >>> print , , (512, 512) , (inpixels).Themodeattributedefinesthenum berandnamesofthebandsintheimage, "L"(luminance)forgreyscaleimages,"RGB"fo rtruecolourimages,and"CMYK" , , ,let'sdisplaytheimagewejustloaded: >>> ()(Thestandardversionofshowisnotveryeffi cient, 'thavexvinstalled,itwon' ,itisveryhandyfordebuggingandtests.) , ' , , , :ConvertfilestoJPEG import os, sysimport Imagefor infile in [1:]: outfile = (infile)[0] + ".

2 Jpg" if infile != outfile: try: (infile).save(outfile) except IOError: print "cannot convert", ,youmustalwaysspecifytheformatthisway:Ex ample:CreateJPEGT humbnailsimport os, sysimport Imagefor infile in [1:]: outfile = (infile)[0] + ".thumbnail" if infile != outfile: try: im = (infile) ((128, 128)) (outfile, "JPEG") except IOError: print "cannot create thumbnail for", infileItisimportanttonoteisthatthelibrar ydoesn' ,thefileheaderisreadtodeterminethefilefo rmatandextractthingslikemode,size,andoth erpropertiesrequiredtodecodethefile, , 'sasimplescripttoquicklyidentifyasetofim agefiles:Example:IdentifyImageFilesimpor t sysimport Imagefor infile in [1:]: try: im = (infile) print infile, , "%dx%d" % , except IOError: passCutting.

3 Copyingasubrectanglefromanimage box = (100, 100, 400, 400) region = (box)Theregionisdefinedbya4-tuple,wherec oordinatesare(left,upper,right,lower).Th ePythonImagingLibraryusesacoordinatesyst emwith(0,0) , :Processingasubrectangle,andpastingitbac k region = ( ) (region, box)Whenpastingregionsback, , , 't,theregionisautomaticallyconvertedbefo rebeingpasted(seethesectiononColourTrans formsbelowfordetails).Here'sanadditional example:Example:Rollinganimagedef roll(image, delta): "Roll an image sideways" xsize, ysize = delta = delta % xsize if delta == 0: return image part1 = ((0, 0, delta, ysize)) part2 = ((delta, 0, xsize, ysize)) (part2, (0, 0, xsize-delta, ysize)) (part1, (xsize-delta, 0, xsize, ysize)) return imageFormoreadvancedtricks, ,thevalue255indicatesthatthepastedimagei sopaqueinthatposition(thatis,thepastedim ageshouldbeusedasis).

4 , , , :Example:Splittingandmergingbandsr, g, b = ()im = ("RGB", (b, g, r)) , :Simplegeometrytransformsout = ((128, 128))out = (45) # degrees counter-clockwiseTorotatetheimagein90deg reesteps, :Transposinganimageout = ( )out = ( )out = ( )out = ( )out = ( )There'snodifferenceinperformanceorresul tbetweentranspose(ROTATE) :Convertingbetweenmodes im = (" ").convert("L")Thelibrarysupportstransfo rmationsbetweeneachsupportedmodeandthe"L "and"RGB" ,youmayhavetouseanintermediateimage(typi callyan"RGB"image). :Applyingfiltersimport ImageFilterout = ( )PointOperationsThepointmethodcanbeusedt otranslatethepixelvaluesofanimage( ).Inmostcases, :Example:Applyingpointtransforms# multiply each pixel by = (lambda i: i * )Usingtheabovetechnique, :Example:Processingindividualbands# split the image into individual bandssource = ()R, G, B = 0, 1, 2# select regions where red is less than 100mask = source[R].

5 Point(lambda i: i 100 and 255)# process the green bandout = source[G].point(lambda i: i * )# paste the processed band back, but only where red was 100source[G].paste(out, None, mask)# build a new multiband imageim = ( , source)Notethesyntaxusedtocreatethemask: imout = (lambda i: expression and 255)Pythononlyevaluatestheportionofalogi calexpressionasisnecessarytodeterminethe outcome, (0),Pythondoesnotlookatthesecondoperand, , , , ,brightness, :Enhancingimagesimport ImageEnhanceenh = (im) ( ).show("30% more contrast")ImageSequencesThePythonImaging Librarycontainssomebasicsupportforimages equences(alsocalledanimationformats).Sup portedsequenceformatsincludeFLI/FLC,GIF, , :Example:Readingsequencesimport Imageim = (" ") (1) # skip to the second frametry: while 1: ( ()+1) # do something to imexcept EOFE rror: pass # end of sequenceAsseeninthisexample,you' (asintheaboveexample).

6 Torewindthefile, :Example:Asequenceiteratorclassclass ImageSequence: def __init__(self, im): = im def __getitem__(self, ix): try: if ix: (ix) return except EOFE rror: raise IndexError # end of sequencefor frame in ImageSequence(im): # ..do something to , 'sasimpleexample:Example:DrawingPostscri ptimport Imageimport PSDrawim = (" ")title = "lena"box = (1*72, 2*72, 7*72, 10*72) # in pointsps = () # default is (title) # draw the image (75 dpi) (box, im, 75) (box) # draw centered ("HelveticaNarrow-Bold", 36)w, h, b = (title) ((4*72-w/2, 1*72-h), title) ()MoreonReadingImagesAsdescribedearlier, ,yousimplypassitthefilenameasanargument: im = (" ")Ifeverythinggoeswell, , ,seekandtellmethods, :Readingfromanopenfilefp = open(" ", "rb")im = (fp)Toreadanimagefromstringdata,usetheSt ringIOclass:Example.

7 Readingfromastringimport StringIOim = ( (buffer))Notethatthelibraryrewindsthefil e(usingseek(0)) ,seekwillalsobeusedwhentheimagedataisrea d(bytheloadmethod).Iftheimagefileisembed dedinalargerfile,suchasatarfile, :Readingfromatararchiveimport TarIOfp = (" ", " Imaging / ")im = (fp) (whenspeedisusuallymoreimportantthanqual ity)andprintingtoamonochromelaserprinter (whenonlyagreyscaleversionoftheimageisne eded). :Readingindraftmodeim = (file)print "original =", , ("L", (100, 100))print "draft =", , :original = RGB (512, 512)draft = L (128, 128) , ,thatis, , , :1(1-bitpixels,blackandwhite,storedas8-b itpixels) L(8-bitpixels,blackandwhite) P(8-bitpixels,mappedtoanyothermodeusinga colourpalette) RGB(3x8-bitpixels,truecolour) RGBA(4x8-bitpixels,truecolourwithtranspa rencymask) CMYK(4x8-bitpixels,colourseparation) YCbCr(3x8-bitpixels,colourvideoformat) I(32-bitintegerpixels) F(32-bitfloatingpointpixels) PILalsosupportsafewspecialmodes,includin gRGBX(truecolourwithpadding)andRGBa(true colourwithpremultipliedalpha).

8 , ,with(0,0) ;thecentreofapixeladdressedas(0,0)actual lyliesat( , ):(0, 0)(1, 1)Coordinatesareusuallypassedtothelibrar yas2-tuples(x,y).Rectanglesarerepresente das4-tuples, ,arectanglecoveringallofan800x600pixelim ageiswrittenas(0,0,800,600).PaletteThepa lettemode("P") (seethechapteronImageFileFormats).Filter sForgeometryoperationsthatmaymapmultiple inputpixelstoasingleoutputpixel, ,thisfilterusesafixedinputenvironmentwhe ndownsampling. ,thisfilterusesafixedinputenvironmentwhe ndownsampling. ANTIALIAS.( ).Calculatetheoutputpixelvalueusingahigh -qualityresamplingfilter(atruncatedsinc) ,thisfiltercanonlybeusedwiththeresizeand thumbnailmethods. NotethatinthecurrentversionofPIL,theANTI ALIAS filteristheonlyfilterthatbehavesproperly whendownsampling(thatis,whenconvertingal argeimagetoasmallone).

9 TheBILINEARandBICUBIC filtersuseafixedinputenvironment, ,includingfunctionstoloadimagesfromfiles , :Open,rotate,anddisplayanimageimport Imageim = (" ") (45).show()Example:Createthumbnailsimpor t globfor infile in ("*.jpg"): file, ext = (infile) im = (infile) ((128, 128), ) (file + ".thumbnail", "JPEG") (mode,size)=> (mode,size,color)=> ,andatupleformulti-bandimages(withoneval ueforeachband).Ifthecolourargumentisomit ted, , (infile)=> (infile,mode)=> ;theactualimagedataisnotreadfromthefileu ntilyoutrytoprocessthedata(orcalltheload method).Ifthemodeargumentisgiven,itmustb e"r".Youcanuseeitherastring(representing thefilename) ,thefileobjectmustimplementread,seek,and tellmethods, (image1,image2,alpha)=>imageCreatesanewi magebyinterpolatingbetweenthegivenimages , out = image1 * ( - alpha) + image2 * , , , (image1,image2,mask)=>imageCreatesanewim agebyinterpolatingbetweenthegivenimages, "1","L",or"RGBA".

10 (function,image)=>imageAppliesthefunctio n(whichshouldtakeoneargument) , , (mode,size,data)=>imageCreatesanimagemem oryfrompixeldatainastring,usingthestanda rd"raw" (mode,size,data,decoder,parameters)=>ima geSame, , , ,wrapitinaStringIOobject, (mode,bands)=> , ,allmethodsreturnanewinstanceoftheImagec lass, (mode)=> "P"mode, , "L","RGB"and"CMYK."Whentranslatingacolou rimagetoblackandwhite(mode"L"),thelibrar yusestheITU-R601-2lumatransform: L = R * 299/1000 + G * 587/1000 + B * 114/1000 Whentranslatingagreyscaleimageintoabilev elimage(mode"1"),allnon-zerovaluesareset to255(white).Touseotherthresholds, (mode,matrix)=>imageConvertsan"RGB"image to"L"or"RGB" (linearlycalibratedaccordingtoITU-R709,u singtheD65luminant)totheCIEXYZ colourspace:Example:ConvertRGBtoXYZ rgb2xyz = ( , , , 0, , , , 0, , , , 0 ) out = ("RGB", rgb2xyz) ()=> , (box)=> ,upper,right, , (mode,size) ,youcanusethismethodtoconvertacolourJPEG togreyscalewhileloadingit, , (filter)=> , (data) (data,decoder,parameters)Sameasthefromst ringfunction, ()=> ,getbandsonanRGBimagereturns("R","G","B" ).