I want to convert a plot generated with matplotlib to an rgb array. In my case, I want to draw two circles using matplotlib. Currently, there are two problems:
- You can still see the space taken by the axes
- The circles aren't circles anymore in the resulting rgb array
Here is the code so far:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
Generate the plot:
def drawImage(color, posx, posy, radius):
posx_left, posx_right = posx
posy_left, posy_right = posy
radius_left, radius_right = radius
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax.axis('off')
ax.set_axis_off()
ax = fig.add_subplot(1, 1, 1)
circle_left = plt.Circle((posx_left, posy_left), radius=radius_left,color=color)
ax.add_patch(circle_left)
circle_right = plt.Circle((posx_right, posy_right), radius=radius_right,color=color)
ax.add_patch(circle_right)
fig.tight_layout(pad=0)
fig.canvas.draw()
width, height = fig.get_size_inches() * fig.get_dpi()
img = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)
return img
Generate plot and save as array:
color = "blue"
radius = 0.2, 0.12
posx = 0.0,0.8
posy = 0.3,0.7
img = drawImage(color,posx,posy,radius)
plt.imshow(img)