I have a piece of code which is inputting a total of 448 thumbnail images and i need to display them in with 64 rows and 7 columns. The code I have does this but the images are so small they are completely useless. I've attached the image and the code i currently have. Any suggestions as to how i can get them to display large enough to see?
import numpy as np
import pylab as plt
import csv
import os
import matplotlib.image as img
plt.close('all')
ID=np.array([])
cata=csv.reader(open('final_final_list.csv',"rU"))
for x in cata:
ID=np.append(ID,x[0])
plots_acc=np.array([])
for i in range(0,len(ID)):
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'ugr.png') #appending the file location for each of the object filter images
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'i1.png')
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'z.png')
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'Y.png')
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'J.png')
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'H.png')
plots_acc=np.append(plots_acc,'filt_image/'+ID[i]+'/'+'Ks.png')
text=(['ugr','i1','z','Y','J','H','Ks'])
print plots_acc
plt.figure()
for x in range(0,len(plots_acc)): #creating subplot of filter images
plt.subplot(64,7,x)
plots=img.imread(plots_acc[x])
plt.imshow(plots)
plt.axis('off')
#plt.suptitle(ID[i])
plt.subplots_adjust(hspace=0.0, wspace=0.0, bottom=0.63)
#plt.savefig('accepted object images/'+str(ID[i])+'.png')
plt.show()
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 downloaded a VLASS fits file and i'm trying to plot it without success.
The problem is, i think, the shape
print(image_data.shape)
which gives me (1, 1, 3722, 3722).
My code is:
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
hdulist = fits.open("vla_test.fits")
hdu = hdulist[0]
plt.figure()
plt.imshow(hdu.data[0,0,:,:], cmap='Greys')
plt.colorbar()
I don't get any error but image doesn't show off and i get white (void) image.
I tried to download other files from the survey but i get same result.
I have a simple program to grab an image and plot its blue and green pixel histogram. I get the plot but I want to do some data science on the plots. Is there an easy way to convert the plot into a table either that I can copy and paste from or straight to a .csv?
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread(file_path)
color = ('b','g')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
cv2.imread() returns a numpy array which you can save to a file, by default in binary format. To get a CSV formatted text file, use the sep parameter:
img.tofile('image.csv', sep=',')
See the official documentation for more information.
I have an MHA file and when I write
from medpy.io import load
image_data, image_header = load("HG/0001/VSD.Brain.XX.O.MR_Flair/VSD.Brain.XX.O.MR_Flair.684.mha")
print(image_data.shape)
I get a tuple (160, 216, 176). What do these dimensions represent (for reference these are brain tumor images from BRATS 2013)? Your help is appreciated.
Edit: on Jupyter for the slider to work I did
import matplotlib.pyplot as plt
from ipywidgets import interact
import numpy as np
%matplotlib inline
#interact(x=(0, image_data.shape[2]))
def update(x):
plt.imshow(np.flip(image_data[x].T, 0))
but of course your code probably works on other editors
According to the documentation, load(image) "Loads the image and returns a ndarray with the image’s pixel content as well as a header object."
Further down in medpy.io.load it says that image_data is "The image data as numpy array with order x,y,z,c.".
Edit: Because I was kind of curious to see what is actually in this file, I put together a quick script (heavily based on the slider demo) to take a look. I'll leave it here just in case it may be useful to someone. (Click on the "Layer" slider to select the z-coordinate to be drawn.)
from medpy.io import load
image_data, image_header = load("/tmp/VSD.Brain.XX.O.MR_Flair.684.mha")
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
axlayer = plt.axes([0.25, 0.1, 0.65, 0.03])
slider_layer = Slider(axlayer, 'Layer', 1, image_data.shape[2], valinit=1, valstep=1)
def update(val):
layer = slider_layer.val
ax.imshow(image_data[:,:,layer])
fig.canvas.draw_idle()
slider_layer.on_changed(update)
ax.imshow(image_data[:,:,0])
plt.show()
(This indirectly confirms that image_data holds a 3-D voxel image.)
Just to add on top the accepted answer, we can visualize the slices with subplots and animation too:
from medpy.io import load
image_data, image_header = load("VSD.Brain.XX.O.MR_Flair.684.mha")
image_data = image_data / image_data.max()
plt.figure(figsize=(20,32))
plt.gray()
plt.subplots_adjust(0,0,1,0.95,0.01,0.01)
for i in range(ct.shape[0]):
plt.subplot(16,10,i+1), plt.imshow(image_data[i]), plt.axis('off')
plt.suptitle('Brain-Tumor CT-scan mha (raw) files', size=15)
plt.show()
I am posting this question after three days searching the net but no success. Hope can get the answer here. Please do NOT delete the post as I did not find an answer for it here also. Thanks.
I have 2 files:
A raster image file (i.e., Air temperature 2020-01-01.tif)
World countries boundary shapefile ((i.e., World_Countries_base_map.shp)
Goal: I want to plot the shapefile on top of raster file, and then save the plot in a Jpeg file format to get something like this eventually:
I am quite new in Python, and used Spyder to prepare this simple code to do so:
# Import needed packages
import os
import rasterio
import matplotlib.pyplot as plt
import geopandas as gpd
import earthpy as et
from matplotlib import pyplot
## list all raster images in tiff format in the folder:
list_files = [f for f in
os.listdir('C:/Users/Desktop/Question/Raster_Air_temp')
if '.tif' in f]
print(list_files[1]) # checking the 1st file in the list
## reading the first tiff file:
raster_image = rasterio.open(list_files[1])
## plot it
draft_output = pyplot.imshow(raster_image.read(1), cmap='jet')
## importing world shapefile
World_map = gpd.read_file('C:/Users/Desktop/Question/World_shapefile/World_Countries_base_map.shp')
# plot World shapefile
fig, ax = plt.subplots(figsize = (30,30)) # image size and quality can be controled by figsize
ax.set_title('The Glob Map', fontsize=50);
World_map.plot(ax=ax, color='white', edgecolor='black') # colors note at https://matplotlib.org/tutorials/colors/colormaps.html
plt.show()
## Plot both World shapefile and raster image in one graph:
????
However, this code just produces 2 separated plots in the console for me as can be seen above.
Question: How can I type a proper code in ???? section of the code to get to my Goal (mentioned above)?
Thanks to all comments and helps.
Here, I share the two files in order to make it easier for those who want help.
Download the files from my Dropbox
.
since i have no access to your data I am showing the principle with some sample data from geopandas and a random numpy ndarray as a tiff surrogate.
the key point is to show the tiff with rasterios rasterplot and don't forget to set the extent of your DEM!
import rasterio
import numpy as np
from rasterio import plot as rasterplot
import geopandas as gpd
from matplotlib import pyplot as plt
# this is how you'd open the raster dataset if you have one
#tiff = rasterio.open('example.tif')
#tiff_extent = [tiff.bounds[0], tiff.bounds[2], tiff.bounds[1], tiff.bounds[3]]
# i am making this array up
tiff_band_1 = np.random.randint(0, 10, size=(65, 64))
tiff_extent = [4159200.0, 4808100.0, 2828000.0, 3482600.0]
shapefile = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
shapefile = shapefile.to_crs('epsg:3035')
shapefile = shapefile[shapefile.name == 'Germany']
f, ax = plt.subplots()
# plot DEM
rasterplot.show(
tiff_band_1, # use tiff.read(1) with your data
extent=tiff_extent,
ax=ax,
)
# plot shapefiles
shapefile.plot(ax=ax, facecolor='w', edgecolor='k')
plt.savefig('test.jpg')
plt.show()