canvas.html


001| '''Canvas (Image) class.
001| 
001| Replacement for the Img class.
001| 
001| Classes:
001|     Canvas (object)
001| 
001| '''

002| ####################################################################################################
003| from os import path
004| from math import radians
005| from PIL import Image, ImageDraw
006| from colors import ColorBlack, ColorWhite
007| ####################################################################################################
008| 
009| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
010| class Canvas (object):
011|     '''Image base class.
011| 
011| Instance Arguments:
011|     dims        - 2-tuple (px,py) defining image size
011|     view        - 4-tuple ((-x,+x),(-y,+y)) defining virtual canvas size
011|     fg          - foreground color (default: Black)
011|     bg          - background color (default: White)
011|     mode        - image type (default: RGB)
011| 
011| Instance Properties:
011|     dims        - s/a instance argument
011|     view        - s/a instance argument
011|     window      - 2-tuple (canvas width, canvas height)
011|     scale       - 2-tuple (x-scale, y-scale) for virtual x,y to canvas px,py
011|     fg          - s/a instance argument
011|     bg          - s/a instance argument
011|     im          - Image object
011|     draw        - ImageDraw object
011|     size        - Image size
011|     mode        - Image mode
011|     width       - Image width
011|     height      - Image height
011|     info        - Image info
011| 
011| Instance Methods:
011|     show                    - Image show()
011|     save(fn,mode)           - save image to file
011| 
011|     px(vx)                  - convert vx to px (view to point)
011|     py(vy)                  - convert vy to py (view to point)
011|     vx(px)                  - convert px to vx (point to view)
011|     vy(py)                  - convert py to vy (point to view)
011| 
011|     line(p1,p2,c,lw)        - draw line from p1 to p2
011|     box(p1,p2,fg,bg,lw)     - draw box from p1 to p2
011|     circle(p,r,fg,bg,lw)    - draw circle at p, radius r
011|     text(p,txt,font,c,bg)   - draw text txt at p using font
011|     textrect(txt,font)      - get text size rectangle (ulc, lrc)
011| 
011|     point(p,c)              - draw point at p
011|     point4(p,c)             - draw point (4 pixels)
011|     point5(p,c)             - draw point (5 pixels)
011|     point9(p,c)             - draw point (9 pixels)
011|     point13(p,c)            - draw point (13 pixels)
011|     point37(p,c)            - draw point (37 pixels)
011|     point81(p,c)            - draw point (81 pixels)
011| 
011|     border(edges, lw)       - draw border using edges
011|     axis(c,lw)              - draw X-Y axis
011|     grid(xtick,ytick,c,lw)  - draw X-Y grid with xtick and ytick
011|     unit_square(c,lw)       - draw a unit square
011| 
011|     x_axis(c,lw)            - draw X axis
011|     y_axis(c,lw)            - draw Y axis
011|     x_grid(xtick,c,lw)      - draw X grid with xtick
011|     y_grid(ytick,c,lw)      - draw y grid with xtick
011| 
011| '''

012|     def __init__ (self, dims, view, fg=ColorBlack, bg=ColorWhite, mode='RGB'):
013|         '''Create a new Canvas(dims,view) instance.'''
014|         self.dims = dims
015|         self.view = view
016|         self.fg = fg
017|         self.bg = bg
018|         self.window = (float(view[0][1]-view[0][0]), float(view[1][1]-view[1][0]))
019|         self.scale = (float(dims[0]/self.window[0]), float(dims[1]/self.window[1]))
020|         self.im = Image.new(mode, dims, bg)
021|         self.draw = ImageDraw.Draw(self.im)
022| 
023|     def __getattr__ (self, name):
024|         '''Image Virtual Read-only Properties.'''
025|         if name == 'size': return self.im.size
026|         if name == 'mode': return self.im.mode
027|         if name == 'width': return self.im.width
028|         if name == 'height': return self.im.height
029|         if name == 'info': return self.im.info
030|         raise ReferenceError('No such attribute: "%s"' % name)
031| 
032|     def __str__ (self):
033|         s = '[%d, %d] %s (%.4f, %.4f)'
034|         t = (self.im.size[0],self.im.size[1], self.im.mode, self.scale[0],self.scale[1])
035|         return s % t
036| 
037|     def __repr__ (self):
038|         s = '{Canvas:{mode:"%s", size:%s, view:%s, window:%s, scale:%s, addr:%x}}'
039|         t = (self.mode, self.size, self.view, self.window, self.scale, self.__hash__())
040|         return s % t
041| 
042|     def show (self):
043|         '''Display image in default viewer.'''
044|         self.im.show()
045| 
046|     def save (self, fn, mode='PNG'):
047|         '''Save image as a file.'''
048|         self.im.save(fn, mode)
049| 
050|     def px (self, vx):
051|         '''Point to View: X.'''
052|         return int(self.scale[0] * (float(vx) - self.view[0][0]))
053|     def py (self, vy):
054|         '''Point to View: Y.'''
055|         return self.dims[1] - int(self.scale[1] * (float(vy) - self.view[1][0]))
056| 
057|     def vx (self, px):
058|         '''View to Point: X.'''
059|         return self.view[0][0] + (float(px) / self.scale[0])
060|     def vy (self, py):
061|         '''View to Point: Y.'''
062|         return self.view[1][0] + (float(self.dims[1]-py) / self.scale[1])
063| 
064|     def point (self, p, c=ColorBlack):
065|         '''Draw a point at p.'''
066|         pt = (self.px(p[0]), self.py(p[1]))
067|         self.draw.point(pt, fill=c)
068| 
069|     def line (self, p1, p2, c=ColorBlack, lw=1):
070|         '''Draw a line from p1 to p2.'''
071|         pt1 = (self.px(p1[0]), self.py(p1[1]))
072|         pt2 = (self.px(p2[0]), self.py(p2[1]))
073|         self.draw.line((pt1,pt2), width=lw, fill=c)
074| 
075|     def circle (self, p, radius, fg=ColorBlack, bg=ColorWhite, lw=1):
076|         '''Draw a circle at p with radius.'''
077|         ulc = (self.px(p[0]-radius), self.py(p[1]+radius))
078|         lrc = (self.px(p[0]+radius), self.py(p[1]-radius))
079|         self.draw.ellipse((ulc,lrc), outline=fg, fill=bg, width=lw)
080| 
081|     def box (self, p1, p2, fg=ColorBlack, bg=ColorWhite, lw=1):
082|         '''Draw a box with ulc=p1 and lrc=p2.'''
083|         ulc = (self.px(p1[0]), self.py(p1[1]))
084|         lrc = (self.px(p2[0]), self.py(p2[1]))
085|         self.draw.rectangle((ulc,lrc), outline=fg, fill=bg, width=lw)
086| 
087|     def point4 (self, p, c=ColorBlack):
088|         '''Draw a point at p. (4 pixels)'''
089|         pt = (self.px(p[0]), self.py(p[1]))
090|         self.draw.point((pt[0]  ,pt[1]  ), fill=c) # llc
091|         self.draw.point((pt[0]  ,pt[1]+1), fill=c) # ulc
092|         self.draw.point((pt[0]+1,pt[1]  ), fill=c) # lrc
093|         self.draw.point((pt[0]+1,pt[1]+1), fill=c) # urc
094| 
095|     def point5 (self, p, c=ColorBlack):
096|         '''Draw a point at p. (5 pixels)'''
097|         pt = (self.px(p[0]), self.py(p[1]))
098|         self.draw.point((pt[0]  ,pt[1]  ), fill=c) # center
099|         self.draw.point((pt[0]+1,pt[1]  ), fill=c) # right
100|         self.draw.point((pt[0]  ,pt[1]+1), fill=c) # up
101|         self.draw.point((pt[0]-1,pt[1]  ), fill=c) # left
102|         self.draw.point((pt[0]  ,pt[1]-1), fill=c) # down
103| 
104|     def point9 (self, p, c=ColorBlack):
105|         '''Draw a point at p. (9 pixels)'''
106|         pt = (self.px(p[0]), self.py(p[1]))
107|         for x in [-1, 0, +1]:
108|             for y in [-1, 0, +1]:
109|                 self.draw.point((pt[0]+x,pt[1]+y), fill=c)
110| 
111|     def point13 (self, p, c=ColorBlack):
112|         '''Draw a point at p. (13 pixels)'''
113|         pt = (self.px(p[0]), self.py(p[1]))
114|         for x in [-1, 0, +1]:
115|             for y in [-1, 0, +1]:
116|                 self.draw.point((pt[0]+x,pt[1]+y), fill=c)
117|         self.draw.point((pt[0]+2,pt[1]  ), fill=c) # 2right
118|         self.draw.point((pt[0]  ,pt[1]+2), fill=c) # 2up
119|         self.draw.point((pt[0]-2,pt[1]  ), fill=c) # 2left
120|         self.draw.point((pt[0]  ,pt[1]-2), fill=c) # 2down
121| 
122|     def point37 (self, p, c=ColorBlack):
123|         '''Draw a point at p. (37 pixels)'''
124|         pt = (self.px(p[0]), self.py(p[1]))
125|         for x in [-2, -1, 0, +1, +2]:
126|             for y in [-2, -1, 0, +1, +2]:
127|                 self.draw.point((pt[0]+x,pt[1]+y), fill=c)
128|         for x in [-1, 0, +1]:
129|             self.draw.point((pt[0]+x,pt[1]-3), fill=c)
130|             self.draw.point((pt[0]+x,pt[1]+3), fill=c)
131|         for y in [-1, 0, +1]:
132|             self.draw.point((pt[0]-3,pt[1]+y), fill=c)
133|             self.draw.point((pt[0]+3,pt[1]+y), fill=c)
134| 
135|     def point81 (self, p, c=ColorBlack):
136|         '''Draw a point at p. (81 pixels)'''
137|         pt = (self.px(p[0]), self.py(p[1]))
138|         for x in [-3, -2, -1, 0, +1, +2, +3]:
139|             for y in [-3, -2, -1, 0, +1, +2, +3]:
140|                 self.draw.point((pt[0]+x,pt[1]+y), fill=c)
141|         for x in [-2, -1, 0, +1, +2]:
142|             self.draw.point((pt[0]+x,pt[1]-4), fill=c)
143|             self.draw.point((pt[0]+x,pt[1]+4), fill=c)
144|         for y in [-2, -1, 0, +1, +2]:
145|             self.draw.point((pt[0]-4,pt[1]+y), fill=c)
146|             self.draw.point((pt[0]+4,pt[1]+y), fill=c)
147|         for x in [-1, 0, +1]:
148|             self.draw.point((pt[0]+x,pt[1]-5), fill=c)
149|             self.draw.point((pt[0]+x,pt[1]+5), fill=c)
150|         for y in [-1, 0, +1]:
151|             self.draw.point((pt[0]-5,pt[1]+y), fill=c)
152|             self.draw.point((pt[0]+5,pt[1]+y), fill=c)
153| 
154|     def textrect (self, txt, font, anchor=(0,0)):
155|         return self.draw.textbbox(anchor, txt, font=font)
156| 
157|     def text (self, anchor, txt, font, c=ColorBlack, bg=None):
158|         '''Draw txt at anchor using font.'''
159|         pt = (self.px(anchor[0]), self.py(anchor[1]))
160|         if bg:
161|             bb = self.draw.textbbox((0,0), txt, font=font)
162|             lrc = (pt[0]+bb[2], pt[1]+bb[3]+2)
163|             self.draw.rectangle((pt,lrc), fill=bg)
164|         self.draw.text(pt, txt, font=font, fill=c)
165| 
166|     def border (self, edges=[(0,0,0),(63,63,63),(127,127,127),(191,191,191)], lw=1):
167|         '''Draw a border using colors in edges.'''
168|         ulc = [0, 0]
169|         lrc = [self.dims[0]-1, self.dims[1]-1]
170|         for edge in edges:
171|             for _ in range(lw):
172|                 self.draw.line(((ulc[0],ulc[1]),(lrc[0],ulc[1])), width=1, fill=edge)
173|                 self.draw.line(((ulc[0],lrc[1]),(lrc[0],lrc[1])), width=1, fill=edge)
174|                 self.draw.line(((ulc[0],lrc[1]),(ulc[0],ulc[1])), width=1, fill=edge)
175|                 self.draw.line(((lrc[0],lrc[1]),(lrc[0],ulc[1])), width=1, fill=edge)
176|                 ulc[0] += 1
177|                 lrc[0] -= 1
178|                 ulc[1] += 1
179|                 lrc[1] -= 1
180| 
181|     def axis (self, c=ColorBlack, lw=3):
182|         '''Draw the X-Y axis.'''
183|         self.x_axis(c=c, lw=lw)
184|         self.y_axis(c=c, lw=lw)
185| 
186|     def x_axis (self, c=ColorBlack, lw=3):
187|         '''Draw the X axis.'''
188|         p0 = (self.view[0][0], 0)
189|         p1 = (self.view[0][1], 0)
190|         self.line(p0, p1, c=c, lw=lw)
191| 
192|     def y_axis (self, c=ColorBlack, lw=3):
193|         '''Draw the Y axis.'''
194|         p0 = (0, self.view[1][0])
195|         p1 = (0, self.view[1][1])
196|         self.line(p0, p1, c=c, lw=lw)
197| 
198|     def grid (self, xtick, ytick, c=(191,191,191), lw=1):
199|         '''Draw an X-Y grid using xtick and ytick.'''
200|         self.x_grid(xtick, c=c, lw=lw)
201|         self.y_grid(ytick, c=c, lw=lw)
202| 
203|     def x_grid (self, xtick, c=(191,191,191), lw=1):
204|         '''Draw an X grid using xtick.'''
205|         nn = abs(int(float(self.view[0][0]) / float(xtick)))+1
206|         np = abs(int(float(self.view[0][1]) / float(xtick)))+1
207|         for x in range(np):
208|             p0 = (+x*xtick, self.view[1][0])
209|             p1 = (+x*xtick, self.view[1][1])
210|             self.line(p0, p1, c=c, lw=lw)
211|         for x in range(nn):
212|             p0 = (-x*xtick, self.view[1][0])
213|             p1 = (-x*xtick, self.view[1][1])
214|             self.line(p0, p1, c=c, lw=lw)
215| 
216|     def y_grid (self, ytick, c=(191,191,191), lw=1):
217|         '''Draw a Y grid using ytick.'''
218|         nn = abs(int(float(self.view[1][0]) / float(ytick)))+1
219|         np = abs(int(float(self.view[1][1]) / float(ytick)))+1
220|         for y in range(np):
221|             p0 = (self.view[0][0], +y*ytick)
222|             p1 = (self.view[0][1], +y*ytick)
223|             self.line(p0, p1, c=c, lw=lw)
224|         for y in range(nn):
225|             p0 = (self.view[0][0], -y*ytick)
226|             p1 = (self.view[0][1], -y*ytick)
227|             self.line(p0, p1, c=c, lw=lw)
228| 
229|     def unit_square (self, c=(191,191,191), lw=3):
230|         '''Draw a unit square.'''
231|         self.line((-1,+1), (+1,+1), c=c, lw=lw)
232|         self.line((-1,-1), (+1,-1), c=c, lw=lw)
233|         self.line((-1,+1), (-1,-1), c=c, lw=lw)
234|         self.line((+1,+1), (+1,-1), c=c, lw=lw)
235| 
236| 
237| ####################################################################################################
238| '''eof'''
239|