Your SlideShare is downloading. ×
Python & Perl                           Lecture 13                      Vladimir Kulyukin               Department of Comp...
Outline   ●       PIL Basics   ●       OOP in Pythonwww.youtube.com/vkedco   www.vkedco.blogspot.com
PIL Basicswww.youtube.com/vkedco           www.vkedco.blogspot.com
Creating New Images    ●        Image.new(mode, size [, color])    ●        mode is a valid mode represented as a string: ...
Creating and Saving Images      >>> import Image      >>> im1 = Image.new(1, (100, 50))      >>> im1.save("C:Python27CS343...
Getting Pixel Values     ●         im.getpixel(xy)         ## im is an Image object         ## xy is a tuple (x, y)     ● ...
PIL Coordinates      0,0                                       x            Example:            im = Image.new(L, (100, 50...
Setting Pixel Values    ●        im.setpixel(xy, color)        ## im is an Image object        ## xy is a tuple (x, y)    ...
Reading Images from Files      ## 1. Create an image      >>> im1 = Image.new(RGB, (100, 100), (0, 255, 0))      ## 2. Sav...
Colors in PIL    ●        Colors depend on the mode of the image    ●        In RGB mode, colors are returned as 3-tuples ...
Drawing    ●        It is possible to use putpixel() to draw various figures        but this can get tedious and error-pro...
Using ImageDraw    ●        First, create an Image object:             –   Image.new() or Image.open()    ●        Second,...
Installing and Manipulating PIL Fonts    ●        Download pilfonts.zip from        http://effbot.org/downloads/#pilfonts ...
ImageFont    ●        Import ImageFont if you want to manipulate fonts    ●        ImageFont.load(file) is used to load a ...
Example      import Image, ImageDraw, ImageFont      def make_centered_text(imageName, text, size = 300, font = None, colo...
Example      def make_helvetica_centered_text(imageName, text, size = 300, color = (0,0,0)):        my_font = ImageFont.lo...
PIL Reading    ●        Overview        http://www.pythonware.com/library/pil/handbook/overview.htm    ●        Tutorial: ...
OOP in Pythonwww.youtube.com/vkedco            www.vkedco.blogspot.com
Classes vs. Object   ●   A class is a definition (blueprint, description)       of states and behaviors of objects that be...
Older Python: Classes vs. Types   ●       In older versions of Python, there was a       difference between classes and ty...
Older Python: Classes vs. Types   ●       In Python versions prior to Python 3.0, old style       classes are default   ● ...
Class Definition Syntax     __metaclass__ = type     class ClassName:           <statement-1>           …           <state...
Class Definition Evaluation   ●       When a class definition is evaluated, a new       namespace is created and used as t...
class Statement      ●          class statement defines a named class      ●          class statements can be placed insid...
Class Documentation      ●          To document a class, place a docstring immediately after the          class statement ...
Creating Objects      ●          There is no new in Python      ●          Class objects (instances) are created by the cl...
Operations Supported by Class Objects   ●       Class objects support two types of operations: attribute       reference a...
Class Objects        >>> A.x          ## attribute reference        >>> A.g          ## attribute reference        >>> A._...
Defining Class Methods      ●          In C++ terminology, all class members are public and all class          methods are...
Calling Methods on Instances      ●          To call a method on an instance, use the dot          operator      ●        ...
Calling Methods on Instances      ●          What happens to self in sp.println()?      ●          The definition inside t...
Calling Methods on Instances      ●          The statement sp.println() is converted to          SimplePrinter.println(sp)...
Example        class C:            def f(self, x1, x2, x3):                return [x1, x2, x3]        >>> x = C()        >...
Attributes and Attribute References      ●          The term attribute is used for any name that follows a dot      ●     ...
Types of Attribute Names      ●          There are two types of attribute names: data attributes and          method attri...
Data Attributes      ●          Data attributes loosely correspond to data          members in C++      ●          A data ...
Data Attributes      ●          This code illustrates that attributes do not have to be declared and          begin their ...
Method Attributes      ●          Method attributes loosely correspond to data          member functions in C++      ●    ...
Method Attributes      ●          Method attributes loosely correspond to data member functions in          C++          c...
Method Attributes      ●          Data attributes override method attributes          class C:            def f(self):    ...
Method Attributes    ●        Consistent naming conventions help avoid clashes between data        attributes and method a...
Reading & References  ●      www.python.org  ●      Ch 07 M. L. Hetland. Beginning Python From Novice to Pro-             ...
Feedback   Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco            www.vkedco.blogspot.com
Upcoming SlideShare
Loading in...5
×

Python & Perl: Lecture 13

748

Published on

Published in: Technology, Art & Photos
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
748
On Slideshare
0
From Embeds
0
Number of Embeds
20
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Python & Perl: Lecture 13"

  1. 1. Python & Perl Lecture 13 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● PIL Basics ● OOP in Pythonwww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. PIL Basicswww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. Creating New Images ● Image.new(mode, size [, color]) ● mode is a valid mode represented as a string: – 1 – L – RGB ● size is a tuple (width, height) ● color is optional – If missing, the new image is filled with black – If present, the new image is filled with that colorwww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. Creating and Saving Images >>> import Image >>> im1 = Image.new(1, (100, 50)) >>> im1.save("C:Python27CS3430imgfirst.BMP") >>> im2 = Image.new(L, (100, 50), white) >>> im2.save("C:Python27CS3430imgsecond.BMP") >>> im3 = Image.new("RGB", (100, 50), (0, 0, 255)) >>> im3.save("C:Python27CS3430imgthird.BMP")www.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. Getting Pixel Values ● im.getpixel(xy) ## im is an Image object ## xy is a tuple (x, y) ● (0, 0) is the top left corner ● Example: >>> im = Image.new("RGB", (100, 50), (0, 0, 255)) >>> im.getpixel((0, 0))www.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. PIL Coordinates 0,0 x Example: im = Image.new(L, (100, 50), 255) ## ims x ranges from 0 to 99 ## ims y ranges from 0 to 49 ywww.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Setting Pixel Values ● im.setpixel(xy, color) ## im is an Image object ## xy is a tuple (x, y) ● color is a mode-dependent color spec ● Example: def make_green(img): for x in xrange(img.size[0]): for y in xrange(img.size[1]): img.putpixel((x, y), (0, 255, 0))www.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Reading Images from Files ## 1. Create an image >>> im1 = Image.new(RGB, (100, 100), (0, 255, 0)) ## 2. Save an image >>> im1.save(/home/vladimir/Pictures/im1.bmp) ## 3. Open an image from an existing file >>> im2 = Image.open(/home/vladimir/Pictures/im1.bmp) >>> print im2.format, im2.size, im2.mode BMP (100, 100) RGBwww.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Colors in PIL ● Colors depend on the mode of the image ● In RGB mode, colors are returned as 3-tuples (red, green, blue) ● Values range from 0 upto 255 ● Common colors can set with string values, e.g., white, black, redwww.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Drawing ● It is possible to use putpixel() to draw various figures but this can get tedious and error-prone ● ImageDraw is used to draw simple 2D graphics: – Lines – Ellipses – Textwww.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Using ImageDraw ● First, create an Image object: – Image.new() or Image.open() ● Second, create an ImageDraw object from the Image object: – import Image – import ImageDraw – im = Image.new(RGB, (100, 100)) – Draw = ImageDraw.Draw(im) ● Third, use the ImageDraw object to draw various figures in the Image ● Fourth, save the Image in a file if necessarywww.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Installing and Manipulating PIL Fonts ● Download pilfonts.zip from http://effbot.org/downloads/#pilfonts ● Unzip them into an accessible directory, e.g., C:/Python27/pilfonts/ ● Each font has two files: – xxx.pbm – image with all individual letters – xxx.pil – info on how to break up .pbm filewww.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. ImageFont ● Import ImageFont if you want to manipulate fonts ● ImageFont.load(file) is used to load a font file, the file must have .pil extension ● Be ready to handle situations when fonts are not installed ● It is always better to load the default font with ImageFont.load_default()www.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Example import Image, ImageDraw, ImageFont def make_centered_text(imageName, text, size = 300, font = None, color = (0,0,0)): if font == None: font = ImageFont.load_default() im = Image.new(RGB, (size, size), white) draw = ImageDraw.Draw(im) sWidth, sHeight = font.getsize(text) centerX = centerY = (size/2 – 1) x = centerX - sWidth/2 y = centerY – sHeight/2 draw.text((x,y), text, font = font, fill = color) del draw im.save(imageName) del imwww.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Example def make_helvetica_centered_text(imageName, text, size = 300, color = (0,0,0)): my_font = ImageFont.load(C:/Python27/pilfonts/helvR24.pil) make_centered_text(imageName, text, size, my_font, color) print "Creating image with defaultText.png with the default font" make_centered_text(default_text.png, Hello, Python!, color=(255, 0, 0)) print "Creating image with defaultText.png with the Helvetica font" make_helvetica_centered_text(helvetica_text.png, Hello, Python!, color=(0, 0, 255))www.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. PIL Reading ● Overview http://www.pythonware.com/library/pil/handbook/overview.htm ● Tutorial: http://www.pythonware.com/library/pil/handbook/introduction.htm ● Concepts: http://www.pythonware.com/library/pil/handbook/concepts.htmwww.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. OOP in Pythonwww.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Classes vs. Object ● A class is a definition (blueprint, description) of states and behaviors of objects that belong to it ● An object is a member of its class that behaves according to its class blueprint ● Objects of a class are also called instances of that classwww.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Older Python: Classes vs. Types ● In older versions of Python, there was a difference between classes and types ● The programmer could create classes but not types ● In newer versions of Python, the distinction between types and classes is disappearing ● The programmer can now make subclasses of built-in types and the types are behaving like classeswww.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. Older Python: Classes vs. Types ● In Python versions prior to Python 3.0, old style classes are default ● To get the new style classes, place __metaclass__ = type at the beginning of a script or a module ● There is no reason to use old style classes any more (unless there is a serious backward compatibility issue). ● Python 3.0 and higher do not support old style classeswww.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. Class Definition Syntax __metaclass__ = type class ClassName: <statement-1> … <statement-N>www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. Class Definition Evaluation ● When a class definition is evaluated, a new namespace is created and used as the local scope ● All assignments of local variables occur in that new namespace ● Function definitions bind function names in that new namespace ● When a class definition is exited, a class object is createdwww.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. class Statement ● class statement defines a named class ● class statements can be placed inside functions ● Multiple classes can be defined in one .py file ● Class definition must have at least one statement in its body (pass can be used as a placeholder)www.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. Class Documentation ● To document a class, place a docstring immediately after the class statement class <ClassName>: """ Does nothing for the moment """ passwww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Creating Objects ● There is no new in Python ● Class objects (instances) are created by the class name followed by () ● This object creation process is called class instantiation: class SimplePrinter: """ This is class Printer. """ pass >>> x = Printer()www.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. Operations Supported by Class Objects ● Class objects support two types of operations: attribute reference and instantiation __metaclass__ = type class A: this is class A. x = 12 def g(self): return Hello from A!www.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. Class Objects >>> A.x ## attribute reference >>> A.g ## attribute reference >>> A.__doc__ ## attribute reference >>> a = A() ## a is an instance of ## class A (instantiation)www.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. Defining Class Methods ● In C++ terminology, all class members are public and all class methods are virtual ● All class methods are defined with def and must have the parameter self as their first argument ● One can think of self as this in Java and C++ class SimplePrinter: def println(self): print def print_obj(self, obj): print obj,www.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. Calling Methods on Instances ● To call a method on an instance, use the dot operator ● Do not put self as the first argument >>> sp = SimplePrinter() >>> sp.print_obj([1, 2]); sp.println()www.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Calling Methods on Instances ● What happens to self in sp.println()? ● The definition inside the SimplePrinter class is def println(self): print ● How come self is not the first argument?www.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Calling Methods on Instances ● The statement sp.println() is converted to SimplePrinter.println(sp) so self is bound to sp ● In general, suppose there is a class C with a method f(self, x1, ..., xn) ● Suppose we do: >>> x = C() >>> x.f(v1, ..., vn) ● Then x.f(v1, ..., vn) is converted to C.f(x, v1, ..., vn)www.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. Example class C: def f(self, x1, x2, x3): return [x1, x2, x3] >>> x = C() >>> x.f(1, 2, 3) [1, 2, 3] >>> C.f(x, 1, 2, 3) ## equivalent to x.f(1, 2, 3) [1, 2, 3]www.youtube.com/vkedco www.vkedco.blogspot.com
  34. 34. Attributes and Attribute References ● The term attribute is used for any name that follows a dot ● For example, in the expression “a.x”, x is an attribute class A: """ This is class A. """ def printX(self): print self._x, ● A.__doc__, A._x, A.printX, A._list are valid attribute referenceswww.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. Types of Attribute Names ● There are two types of attribute names: data attributes and method attributes class A: """ This is class A. """ _x = 0 ## data attribute _x _list = [] ## data attribute _list def printX(self): ## method attribute print self._x, ● A.__doc__, A._x, A._list are data attributes ● A.printX is a method attributewww.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Data Attributes ● Data attributes loosely correspond to data members in C++ ● A data attribute does not have to be explicitly declared in the class definition ● A data attribute begins to exist when it is first assigned to ● Of course, integrating data attributes into the class definition makes the code easier to read and debugwww.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. Data Attributes ● This code illustrates that attributes do not have to be declared and begin their existence when they are first assigned to class B: """ This is class B. """ def __init__(self): self._number = 10 self._list = [1, 2, 3] >>> b = B() >>> b._number 10 >>> b._list [1, 2, 3]www.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. Method Attributes ● Method attributes loosely correspond to data member functions in C++ ● A method is a function that belongs to a class ● If a is an object of class A, then a.printX is a method object ● Like function objects, method objects can be used outside of their classes, e.g. assigned to variables and called at some later pointwww.youtube.com/vkedco www.vkedco.blogspot.com
  39. 39. Method Attributes ● Method attributes loosely correspond to data member functions in C++ class A: _x = 0 def printX(self): print self._x, >>> a = A() >>> m = a.printX >>> m() 0 >>> a._x = 20 >>> m() 20www.youtube.com/vkedco www.vkedco.blogspot.com
  40. 40. Method Attributes ● Data attributes override method attributes class C: def f(self): print "I am a C object." >>> c = C() >>> c.f() I am a C object. >>> c.f = 10 >>> c.f 10 >>> c.f() ### errorwww.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. Method Attributes ● Consistent naming conventions help avoid clashes between data attributes and method attributes ● Choosing a naming convention and using it consistently makes reading and debugging code much easier ● Some naming conventions: – First letter in data attributes is lower case; first letter in method attributes is upper case – First letter in data attributes is underscore; first letter in method attributes is not underscore – Nouns are used for data attributes; verbs are used for methodswww.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. Reading & References ● www.python.org ● Ch 07 M. L. Hetland. Beginning Python From Novice to Pro- nd fessional, 2 Ed., APRESSwww.youtube.com/vkedco www.vkedco.blogspot.com
  43. 43. Feedback Bugs, comments to vladimir dot kulyukin at usu dot eduwww.youtube.com/vkedco www.vkedco.blogspot.com

×