Created
July 30, 2022 03:12
-
-
Save Ending2015a/eab49540cb2f8758d21758b9d517f55f to your computer and use it in GitHub Desktop.
Save Matplotlib as numpy array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import io | |
import numpy as np | |
import cv2 | |
# === some statistics === | |
x1 = np.linspace(0, 10, 100) | |
y1 = np.sin(x1) | |
x2 = np.linspace(-1, 1, 100)[:, None] | |
y2 = np.linspace(-1, 1, 100)[None, :] | |
im = np.sqrt(x2**2 + y2**2) | |
# your plot | |
fig, axs = plt.subplots(ncols=2) | |
axs[0].plot(x1, y1) | |
axs[1].imshow(im, cmap='viridis') | |
plt.tight_layout() | |
# dump to numpy array | |
io_buf = io.BytesIO() | |
fig.savefig(io_buf, format='raw') | |
io_buf.seek(0) | |
canvas = np.reshape( | |
np.frombuffer(io_buf.getvalue(), dtype=np.uint8), | |
(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1) | |
)[...,:3] # ensure only 3 channels RGB | |
io_buf.close() | |
plt.close('all') | |
cv2.imshow('PLOT', canvas[...,::-1]) #RGB2BGR | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment