6/26/2021

matplotlib plt to cv2

This example code is based on plt.pie drawing.

But you can apply any drawing way, just refer to how to be converted plt.fig 2 Numpy(cv2).


..

    import matplotlib.pyplot as plt
fig = plt.figure()
plt.pie(ratio, labels = mylabels, colors = mycolors) #, radius=180)
def get_img_from_fig(fig, dpi=180):
import io
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=dpi)
buf.seek(0)
img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
buf.close()
img = cv2.imdecode(img_arr, 1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

return img

plot_img_np = get_img_from_fig(fig)

cv2.namedWindow('palette')
cv2.imshow('palette', plot_img_np)
cv2.waitKey(0)

..



Thank you.

πŸ™‡πŸ»‍♂️