Viewing .npy images - python

How can I view images stored with a .npy extension and save my own files in that format?

.npy is the file extension for numpy arrays - you can read them using numpy.load:
import numpy as np
img_array = np.load('filename.npy')
One of the easiest ways to view them is using matplotlib's imshow function:
from matplotlib import pyplot as plt
plt.imshow(img_array, cmap='gray')
plt.show()
You could also use PIL or pillow:
from PIL import Image
im = Image.fromarray(img_array)
# this might fail if `img_array` contains a data type that is not supported by PIL,
# in which case you could try casting it to a different dtype e.g.:
# im = Image.fromarray(img_array.astype(np.uint8))
im.show()
These functions aren't part of the Python standard library, so you may need to install matplotlib and/or PIL/pillow if you haven't already. I'm also assuming that the files are either 2D [rows, cols] (black and white) or 3D [rows, cols, rgb(a)] (color) arrays of pixel values.

Thanks Ali_m. In my case I inspect the npy file to check how many images was in the file with:
from PIL import Image
import numpy as np
data = np.load('imgs.npy')
data.shape
then I plotted the images in a loop:
from matplotlib import pyplot as plt
for i in range(len(data)):
plt.imshow(data[i], cmap='gray')
plt.show()

Related

how to get an axial image from ct scan images. as i am using sliver07 dataset so it has 100+ images in single .mhd file

i using SLIVER07 dataset for liver segmentation task but i am stuck in reading that images.
import SimpleITK as sitk
import numpy as np
import matplotlib.pyplot as plt
# reading .mhd file from slive07 dataset
itkimage = sitk.ReadImage('liver-orig001.mhd')
ct_scan = sitk.GetArrayFromImage(itkimage)
plt.imshow(ct_scan[1])
You are trying to pass the entire 3D image volume to imshow. You could instead try:
plt.imshow(ct_scan[40,:,:])
Which will show the 40th slice.
Of interest might be the platipy library, available here, or just $ pip install platipy. The built-in image visualiser (based on matplotlib) is perfect for 3D image visualisation in python, and has lots of cool features.
A little demo:
from platipy.imaging import ImageVisualiser
img = sitk.ReadImage("image_filename.mhd")
vis = ImageVisualiser(img)
fig = vis.show()

Saving grayscale image to a directory in python

I have a piece of code that takes in image data as grayscale values, and then converts into an image using matplotlib below
import matplotlib.pyplot as plt
import numpy
image_data = image_result.GetNDArray()
numpy.savetxt('data.cvs', image_data)
# Draws an image on the current figure
image = plt.imshow(image_data, cmap='gray')
I want to be able to export this data to LabView as a .png file. So I need to save these image to a folder where LabView and display them. Is there a function with pillow or os that can do this?
plt.imsave('output.png', image)
Does this work?
If image_data is a Numpy array of shape height x width with dtype=np.uint8 or dtype=np.uint16, you can make a PIL Image and save it as a PNG like this:
from PIL import Image
# Make PIL Image from Numpy array
pImage = Image.fromarray(image_data)
pImage.save('forLabView.png')
You can equally use OpenCV to save a Numpy array as a PNG for LabView like this:
import cv2
# Save Numpy array as PNG
cv2.imwrite('forLabView.png', image_data)
Check what your array is with:
print(image_data.shape, image_data.dtype)

read and display raw image using python

I want to try view the image using spyder python as in:
skydrive share
the image is:
uint16 (10-bit)
width:1376 pixel, height: 960 pixel
no header
bayer pattern blue-green, green-red
What python script is suitable?
Thanks.
Here is one way.
Start with imports
from matplotlib import pyplot as plt
import numpy as np
Now allocate the space
image = np.empty((1376,960), np.uint16)
Read the image into your array:
image.data[:] = open('20_1-20ms.raw').read()
Display it:
plt.imshow(image)

Invert colors when plotting a PNG file using matplotlib

I'm trying to display a PNG file using matplotlib and of course, python. For this test, I've generated the following image:
Now, I load and transform the image into a multidimensional numpy matrix:
import numpy as np
import cv2
from matplotlib import pyplot as plt
cube = cv2.imread('Graphics/Display.png')
plt.imshow(cube)
plt.ion()
When I try to plot that image in matplotlib, the colors are inverted:
If the matrix does not have any modifications, why the colors in the plot are wrong?
Thanks in advance.
It appears that you may somehow have RGB switched with BGR. Notice that your greens are retained but all the blues turned to red. If cube has shape (M,N,3), try swapping cube[:,:,0] with cube[:,:,2]. You can do that with numpy like so:
rgb = numpy.fliplr(cube.reshape(-1,3)).reshape(cube.shape)
From the OpenCV documentation:
Note: In the case of color images, the decoded images will have the
channels stored in B G R order.
Try:
plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))
As others have pointed out, the problem is that numpy arrays are in BGR format, but matplotlib expects the arrays to be ordered in a different way.
You are looking for scipy.misc.toimage:
import scipy.misc
rgb = scipy.misc.toimage(cube)
Alternatively, you can use scipy.misc.imshow().
Color image loaded by OpenCV is in BGR mode. However, Matplotlib displays in RGB mode.
So we need to convert the image from BGR to RGB:
plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))

Scale imread matrix in python

I am looking for a way to rescale the matrix given by reading in a png file using the matplotlib routine imread,
e.g.
from pylab import imread, imshow, gray, mean
from matplotlib.pyplot import show
a = imread('spiral.png')
#generates a RGB image, so do
show()
but actually I want to manually specify the dimension of $a$, say 200x200 entries, so I need some magic command (which I assume exists but cannot be found by myself) to interpolate the matrix.
Thanks for any useful comments : )
Cheers
You could try using the PIL (Image) module instead, together with numpy. Open and resize the image using Image then convert to array using numpy. Then display the image using pylab.
import pylab as pl
import numpy as np
from PIL import Image
path = r'\path\to\image\file.jpg'
img = Image.open(path)
img.resize((200,200))
a = np.asarray(img)
pl.imshow(a)
pl.show()
Hope this helps.

Categories

Resources