I'm using the code from this question to convert some raw images into png.
import matplotlib.pyplot as plt
import numpy as np
# Parameters.
input_filename = "JPCLN001.IMG"
shape = (2048, 2048) # matrix size
dtype = np.dtype('>u2') # big-endian unsigned integer (16bit)
output_filename = "JPCLN001.PNG"
# Reading.
fid = open(input_filename, 'rb')
data = np.fromfile(fid, dtype)
image = data.reshape(shape)
# Display.
plt.imshow(image, cmap = "gray")
plt.savefig(output_filename)
plt.show()
The thing is, I'm expecting a png size of 2048x2048 but all I'm getting is images under 500x500. Any advice on how to fix this?
If you just want to save the array as a .png without plotting it, you can use matplotlib.image.imsave:
import numpy as np
from matplotlib import pyplot as plt
# some random data
img = np.random.randint(256, size=(2048, 2048))
# creates a 2048 x 2048 .png image
plt.imsave('img.png', img, cmap='gray')
Related
I am using matplotlib to generate matrices I can train on. I need to get to the raw figure data.
Saving and reading the .png works fine, but my code runs 10x longer. Another stack overflow asked a similar question and the solution was to grab the canvas, but that related logic generated a numpy error. Here is my mwe.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import IdentityTransform
px = 1/plt.rcParams['figure.dpi'] # pixel in inches
fig, ax = plt.subplots(figsize=(384*px, 128*px))
i = 756
plt.text(70, 95, "value {:04d}".format(i), color="black", fontsize=30, transform=IdentityTransform())
plt.axis('off')
plt.savefig("xrtv.png") # I dont want to do this ...
rtv = plt.imread("xrtv.png") # or this, but I want access to what imread returns.
gray = lambda rgb: np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
gray = gray(rtv)
Disabling rendering was a good hint. Consider using a memory buffer to I/O rather than playing with strings. Here is a full example:
import numpy as np
import io
import matplotlib.pyplot as plt
from PIL import Image
# disable rendering and dump to buffer
plt.ioff()
fig,ax = plt.subplots()
ax.plot(np.sin(np.arange(100)))
buf = io.BytesIO()
fig.savefig(buf,format='RGBA')
# plot from buffer
shape = (int(fig.bbox.bounds[-1]),int(fig.bbox.bounds[-2]),-1)
img_array = np.frombuffer(buf.getvalue(),dtype=np.uint8).reshape(shape)
Image.fromarray(img_array)
I am trying to get python to read a geoTIFF image but am having trouble trying to get the image to show.
import rasterio as r
import numpy as np
import matplotlib.pyplot as plt
FNF=r'D:\\Iceberg data\\RADARSAT\\RS2_SLC_geotif\\roi20m_RS2_20160415_153940_0004_FQ13_HHVVHVVH_SLC_470697_4660_12996414_Geo.tif\\'
raster = r.open(FNF)
print(raster)
raster.bounds
raster.height
raster.width
raster.transform
raster.get_transform()
raster.tags(1)
xmin=raster.bounds[0]
ymax=raster.bounds[3]
raster.read(1)
fig = plt.figure(1)
plt.title('SLC image') # this defines the title
plt.imshow(raster)
I get the error with imshow. What am I doing incorrectly?
When I do {i: dtype for i, dtype in zip(raster.indexes, raster.dtypes)} I get float32 out.
I load an image and add it to an empty numpy array:
plt.imshow(im)
plt.show()
im = imread('/path_to_image',mode = 'RGB')
array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im
print(array[0].shape)
print(im.shape)
plt.imshow(array[0])
plt.show()
I expect the two images to look the same when displayed. The image seems to change when I assign it to an array with:
array = np.zeros((1, 299, 299,3), dtype = np.int8)
array[0][:,:,:3] = im
im and array should have the same dtype. You can explicitly define the appropriate dtype for the array of zeros (as suggested by #Divakar) or alternatively you can use NumPy's zeros_like and newaxis as follows:
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
im = io.imread('https://i.stack.imgur.com/crpfS.png')
array = np.zeros_like(im[np.newaxis, :])
array[0] = im
fig, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(im)
ax0.set_title('im')
ax1.imshow(array[0])
ax1.set_title('array[0]')
plt.show()
Consider the following code:
import numpy as np
rand_matrix = np.random.rand(10,10)
which generates a 10x10 random matrix.
Following code to display as colour map:
import matplotlib.pyplot as plt
plt.imshow(rand_matrix)
plt.show()
I would like to get the RGB numpy array (no axis) from the object obtained from plt.imshow
In other words, if I save the image generated from plt.show, I would like to get the 3D RGB numpy array obtained from:
import matplotlib.image as mpimg
img=mpimg.imread('rand_matrix.png')
But without the need to save and load the image, which is computationally very expensive.
Thank you.
You can save time by saving to a io.BytesIO instead of to a file:
import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
def ax_to_array(ax, **kwargs):
fig = ax.figure
frameon = ax.get_frame_on()
ax.set_frame_on(False)
with io.BytesIO() as memf:
extent = ax.get_window_extent()
extent = extent.transformed(fig.dpi_scale_trans.inverted())
plt.axis('off')
fig.savefig(memf, format='PNG', bbox_inches=extent, **kwargs)
memf.seek(0)
arr = mpimg.imread(memf)[::-1,...]
ax.set_frame_on(frameon)
return arr.copy()
rand_matrix = np.random.rand(10,10)
fig, ax = plt.subplots()
ax.imshow(rand_matrix)
result = ax_to_array(ax)
# view using matplotlib
plt.show()
# view using PIL
result = (result * 255).astype('uint8')
img = Image.fromarray(result)
img.show()
I have been making slice images of a simulation, now I need to add a shape to the image, the slice has a colour map, I add a circle to the slice, I need help with making the circle colour be adjustable by values, and share the same colormap as the slice.The code I use is:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import csv
def readslice(ndim):
shape = (ndim,ndim,ndim)
fd = open("delta_T_v3_no_halos_z013.40_nf0.898994_useTs0_zetaX-1.0e+00_alphaX-1.0_TvirminX-1.0e+00_aveTb027.03_Pop-1_300_200Mpc", 'rb')
data = np.fromfile(file=fd, dtype= np.dtype('f4')).reshape(shape)
fd.close()
print data
return data
ff = readslice(300)
circle1=plt.Circle((150.0,150.0),50.0)
fig = plt.gcf()
fig.gca().add_artist(circle1)
plt.imshow(ff[0,:,:],cmap = cm.jet)
plt.colorbar()
plt.savefig('picwithcircle.png')
plt.show()