Function iafig2img

Synopse

Convert a matplotlib figure to an image ready to be displayed by adshow.

  • f = iafig2img(fig)
    • Output
      • f: ndarray, 2D, image ready to be displayed by adshow
    • Input
      • fig: matplotlib figure

Description

The iafig2img function converts a matplotlib figure in a numpy array ready to be displayed by adshow.

Function Code

01. def iafig2img(figure):
02.     import numpy as np
03. 
04.     # draw the renderer
05.     figure.canvas.draw ( )
06. 
07.     # Get the RGB buffer from the figure
08.     w,h = figure.canvas.get_width_height()
09.     buf = np.fromstring ( figure.canvas.tostring_rgb(), dtype=np.uint8 )
10.     buf.shape = ( h, w, 3 )
11. 
12.     return buf.transpose((2,0,1))

Examples

Histogram plotting

01. import ia636 as ia
02. f = adread('cameraman.pgm')
03. adshow(f, 'image')
04. h = ia.iahistogram(f)
05. 
06. import matplotlib.pyplot as plt
07. fig = plt.figure()
08. plt.plot(h)
09. #plt.vlines(arange(len(h)),[0], h)
10. plt.ylabel('number of occurrences')
11. plt.xlabel('gray level')
12. adshow( ia.iafig2img(fig), 'histogram')

image

histogram

Plotting the histogram using bars:

1. fig2 = plt.figure()
2. plt.bar(arange(h.size), h)
3. adshow( ia.iafig2img(fig2), 'histogram')

histogram

Plotting with isolines (contour)

A gaussian image is generated:

1. import numpy as np
2. import ia636 as ia
3. 
4. f = ia.iagaussian((100,150),transpose([[50,75]]),[[50*50,0],[0,30*30]])
5. fn = ia.ianormalize(f)
6. adshow(fn)

We compute the row and col matrices "r" and "c" using indices and apply it to plt.contour

1. import matplotlib.pyplot as plt
2. 
3. fig = plt.figure()
4. r,c = np.indices(fn.shape)
5. plt.contour(c, r, fn)
6. adshow(ia.iafig2img(fig), 'Simple contour')

Simple contour

1. CS = plt.contour(c, r, fn)
2. plt.clabel(CS, inline=1, fontsize=20)
3. adshow(ia.iafig2img(fig), 'Contour with labels')

Contour with labels

1. plt.plot(75,50, 'ro')  # red, marker o
2. adshow(ia.iafig2img(fig), 'With single point')

With single point

See Also

  • iaprofiledemo - Extraction and plotting of a vertical profile of an image
  • iaplot - Simple plotting of list of 1D numpy arrays

Contributions

  • André Luis da Costa, 2012: initial function
  • Roberto Lotufo, 14aug2013: insertion in ia636.