petem
petem

Reputation: 820

How to convert a Julia plot (via Plots.jl) into a Matrix{RGB{N0f8}}

Matplotlib can convert a plot/figure into a RGB array as follows:

import matplotlib.pyplot as plt 
import numpy as np
import io

fig, ax = plt.subplots()
n=256
I, J = np.indices((n, n))

im = ax.imshow((I | J) % 19, interpolation='none')
fig.colorbar(im, ax=ax)
#Convert fig to a RGB array
io_buf = io.BytesIO()
fig.savefig(io_buf, format='raw')
io_buf.seek(0)
fig_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                     newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1))
print(f"The shape of the rgb array: {fig_arr.shape}")
plt.show()

It displays:

The shape of the rgb array: (480, 640, 4)

Is it possible to convert similarly a Plots plot into a Matrix{RGB{N0f8}}?

The first part:

using Plots
n = 255
I = [i for i in 0:n, j in 0:n]
h = heatmap(mod.((I .| I'), 19), c= :deep, yflip=true, size=(400, 400), aspect_ratio=:equal)

I searched for Julia equivalent of numpy.frombuffer, but no result has been returned

Upvotes: 2

Views: 189

Answers (1)

Dan Getz
Dan Getz

Reputation: 18217

With h holding the plot, as the code in the OP has described. The following:

using FileIO

io = IOBuffer()
show(io, MIME("image/png"), h);
strm = Stream(format"PNG", io)
img = load(strm)

leaves img with the Matrix{RGB{...}}.

Upvotes: 2

Related Questions