Example: bachelor of science

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] + ".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] + ".

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

Information

Domain:

Source:

Link to this page:

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

Other abuse

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] + ".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] + ".

2 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, , :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).

3 Here'sanadditionalexample:Example:Rollin ganimagedef 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). , , , :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).

4 :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].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) ( ).

5 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).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:Readingfromastringim port StringIOim = ( (buffer))Notethatthelibraryrewindsthefil e(usingseek(0)) ,seekwillalsobeusedwhentheimagedataisrea d(bytheloadmethod).

6 Iftheimagefileisembeddedinalargerfile,su chasatarfile, :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). , ,with(0,0) ;thecentreofapixeladdressedas(0,0)actual lyliesat( , ):(0, 0)(1, 1)Coordinatesareusuallypassedtothelibrar yas2-tuples(x,y).

7 Rectanglesarerepresentedas4-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).TheBILINEARandBICU BIC filtersuseafixedinputenvironment, ,includingfunctionstoloadimagesfromfiles , :Open,rotate,anddisplayanimageimport Imageim = (" ") (45).show()Example:Createthumbnailsimpor t globfor infile in ("*.)

8 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". (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.

9 "Whentranslatingacolourimagetoblackandwh ite(mode"L"),thelibraryusestheITU-R601-2 lumatransform: 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" ). ()=> ,upper,right, , ()=> ,sothatvaluesforlineonefollowdirectlyaft erthevaluesoflinezero, , ( ),uselist( ()). ()=> , (xy)=> , ()=> , ,thehistogramsforallbandsareconcatenated (forexample,thehistogramforan"RGB"imagec ontains768values).

10 Abilevelimage(mode"1")istreatedasagreysc ale("L") (mask)=> ,andbeeitherabi-levelimage(mode"1")oragr eyscaleimage("L"). ()Allocatesstoragefortheimageandloadsitf romthefile(orfromthesource,forlazyoperat ions).Innormalcases,youdon'tneedtocallth ismethod, (xoffset,yoffset)=>image(Deprecated) , (image,box) ,a4-tupledefiningtheleft,upper,right,and lowerpixelcoordinate,orNone(sameas(0,0)) .Ifa4-tupleisgiven, 'tmatch,thepastedimageisconvertedtothemo deofthisimage(seetheconvertmethodfordeta ils). (colour,box)Sameasabove, , (image,box,mask)Sameasabove, "1","L"or"RGBA"images(inthelattercase,th ealphabandisusedasmask).Wherethemaskis25 5, , "RGBA"image, (colour,box,mask)Sameasabove, (table)=> (function)image=> , , "I"(integer)or"F"(floatingpoint),youmust useafunction,anditmusthavethefollowingfo rmat: argument * scale + offsetExample:Mapfloatingpointimages out = (lambda i: i * + 10) (table,mode)=> (function,mode)=>imageMaptheimagethrough table, ,thiscanonlybeusedtoconvert"L"and"P"imag esto"1"inonestep, (band) "RGBA"image,andthebandmustbeeither"L"or" 1".


Related search queries