Send
Close Add comments:
(status displays here)
Got it! This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website. Note: This appears on each machine/browser from which this site is accessed.
Python: Canvas drawing and rsCanvas module
1. Python: Canvas drawing and rsCanvas module
It is sometimes useful to create custom images in Python. The
ImageDraw class in the
PIL (Python Imaging Library) can be useful for this.
One can create new images or read and annotate existing images.
It as always useful to create a custom class. In this case, aggregation is used rather than inheritance.
2. Object-oriented
In object-oriented terms, the approach of inheritance derives a class (i.e., subclasses) from an ancestor or parent class.
In object-oriented terms, the approach of aggregation make another class and instance variable and then controls access to that instance variable via it's own methods, properties, etc.
3. Modules
4. rsCanvas module
A custom canvas class in the rsCanvas module will now be created.
5. Imports
Some imports are needed.
6. Module variables
Some module variables are needed.
The variable imagePos1 allows a series of images to be created in order.
The variable basePs1 allows the base path of the saved images to be changed.
7. The canvas class
Some methods of the
canvas class are now discussed.
The
ImageDraw class uses colors are represented as a tuple of the integer values for red, green, and blue.
I find it easier to work with the hex forms of red, green and blue.
color of "FF0000" returns (255,0,0)
color of "00FF00" returns (0,255,0)
color of "0000FF" returns (0,0,255)
The
color method converts from hex to tuple representation.
8. Initializer
The initializer sets various instance variables which can then be changed by the calling routines as needed.
Important parts:
The width and height are set.
The default colors are set, as is the default thickness.
An image image1 is created as the canvas (width, height, and back are required).
A drawing object draw1 is created.
The position is set to the center of the image.
Note: Some defaults are set, where possible, using an existing instance method.
9. Moveto
10. Lineto
11. Fonts
An ImageFont object is required to draw text. This is saved in the font1 instance variable.
12. Drawing text
13. Save the canvas
A method similar to the one used in the rsPlot module is used here to save the canvas
as an image.
Here is a code module in Lua [module rsCanvas in rsCanvas.py].
Here is the Python code [#11]
14. Output
Here is the output of the Python code.
15. Image
16. Other capabilities
Some capabilities not shown here include the following.
Blurring an image
Cropping an image
Putting an existing image in part of another image
Copying (and saving) part of an image
Rotating an image
17. End of page