I am getting error with im.show() - python

I am trying to save a gray scale image (256,256,1) and show it in the output.
im = data.astype(np.uint8)
print im.shape
im = np.transpose(im, (2,1,0))
print im.shape
im.show()
However, I am getting the following error:
(256, 256, 1)
Traceback (most recent call last):
File "lmdb_reader.py", line 37, in <module>
plt.imshow(im)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3029, in imshow
**kwargs)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/__init__.py", line 1819, in inner
return func(ax, *args, **kwargs)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 4922, in imshow
im.set_data(X)
File "/home/se/anaconda2/envs/caffeenv/lib/python2.7/site-packages/matplotlib/image.py", line 453, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

Note that im.show() does not exist, but it might just be a typo in the question.
The real problem is the following:
Matplotlib's pyplot.imshow can plot images of dimension (N,M) (grayscale) or (N,M,3) (rgb color). Your image is (N,M,1); we therefore need to get rid of the last dimension.
import matplotlib.pyplot as plt
import numpy as np
#create data of shape (256,256,1)
data = np.random.rand(256,256,1)*255
im = data.astype(np.uint8)
print im.shape # prints (256L, 256L, 1L)
# (256,256,1) cannot be plotted, therefore
# we need to get rid of the last dimension:
im = im[:,:,0]
print im.shape # (256L, 256L)
# now the image can be plotted
plt.imshow(im, cmap="gray")
plt.show()

You need to specify the colormap before calling matplotlib.pyplot.show().
By default the function expects RGB images when you pass a 3D array.
Example:
im = np.squeeze(im)
plt.imshow(im,cmap='gray')
plt.show()

Related

i want to resize an image but it shows an error

I am trying to program a code that accepts an image,rescales it to a smaller values,uses border detection and gives out an ASCII art.
But the problem arises with the part where im unable to retrieve the rescaled imagge.
here is the code:
from matplotlib import image
from matplotlib import pyplot
# load image as pixel array
image = image.imread(r'C:\Users\lavni\OneDrive\Desktop\asci.png')
# summarize shape of the pixel array
print(image.dtype)
print(image.shape)
image=image.resize((52,int((image.shape[1]*52)/image.shape[0])))
# display the array of pixels as an image
pyplot.imshow(image)
pyplot.show()
and i get the error:
(648, 1152, 3)
Traceback (most recent call last):
File "C:/Users/lavni/AppData/Local/Programs/Python/Python38-32/ASCII.py", line 11, in <module>
pyplot.imshow(image)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\pyplot.py", line 2645, in imshow
__ret = gca().imshow(
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\__init__.py", line 1565, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\cbook\deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\cbook\deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_axes.py", line 5626, in imshow
im.set_data(X)
File "C:\Users\lavni\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\image.py", line 693, in set_data
raise TypeError("Image data of dtype {} cannot be converted to "
TypeError: Image data of dtype object cannot be converted to float
Use openCV library
pip install opencv-python
Code:
import cv2
img2 = cv2.imread(filename)
resized = cv2.resize(img2, dsize=(28,28), interpolation=cv2.INTER_CUBIC)

Python PIL image from array datatype error

I've been playing around with PIL to get a hang of it and wanted to split up an image into its rgb channels, put it together again and show it.
import PIL.Image as Img
import numpy as np
img = Img.new('RGB', (10,10), color = 'cyan')
r,g,b = img.split()
pixels = np.array([np.asarray(r),np.asarray(g),np.asarray(b)])
new_img = Img.fromarray(pixels.astype(np.uint8))
new_img.show()
when I run the file it returns an Error:
File "C:\Program Files (x86)\Python38-32\lib\site-packages\PIL\Image.py", line 2716, in fromarray
raise TypeError("Cannot handle this data type: %s, %s" % typekey)
TypeError: Cannot handle this data type: (1, 1, 10), |u1
I've also tried it like this:
import PIL.Image as Img
import numpy as np
img = Img.new('RGB', (10,10), color = 'cyan')
r,g,b = img.split()
pixels = [np.asarray(r),np.asarray(g),np.asarray(b)]
new_img = Img.fromarray(pixels)
new_img.show()
Where I got this error:
File "C:\Program Files (x86)\Python38-32\lib\site-packages\PIL\Image.py", line 2704, in fromarray
arr = obj.__array_interface__
AttributeError: 'list' object has no attribute '__array_interface__'
So how do I have to put the r, g and b arrays back together correctly?
RGB image is made by stacking 3 colored channels one over the other on the z-axis. See this image for analogy,
pixels = np.array([np.asarray(r),np.asarray(g),np.asarray(b)])
This command places those 3 colored channels side by side, you can check shape using
print(pixels.shape)
(3, 10, 10)
This makes no sense to the interpreter thus the error message.
Each pixel in an RBG image is a tuple of red, green and blue color values.
thus shape take the form rows x cols x channels. You can achieve this by using np.stack
pixels = np.stack([np.asarray(r),np.asarray(g),np.asarray(b)], axis = 2)

Plot a Numpy Array with (1, 2208, 2752, 3) Dimensions

I have a microscopy array and I want to plot them.
The shape is:
(1, 2208, 2752, 3)
And Im triying it to plot with the following code:
from PIL import Image
im = Image.fromarray(image_array)
im.show()
And get this error:
Traceback (most recent call last):
File "/Users/x/anaconda3/envs/x/lib/python3.6/site-packages/PIL/Image.py", line 2515, in fromarray
mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 2752, 3), '|u1')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/x/Desktop/x/x/test.py", line 21, in <module>
im = Image.fromarray(image_arrays)
File "/Users/x/x/x/x/lib/python3.6/site-packages/PIL/Image.py", line 2517, in fromarray
raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type
If I resize the array to (2000,2000,3) this working, but with the 1 in the first dimension I have no Idea how can this work. The filetype is .czi and its a normal image.
You need a x by y by (r,g,b) matrix to display an image. You seem to have a fourth dimension on your matrix, so I'm guessing whatever routine you are using to create the array is actually creating an array of images.
Since you only have one image, you can just remove the first axis using image_array = numpy.squeeze(image_array, axis=0) This returns just the one image array in shape (2208, 2752, 3). Alternately, you can do: im = Image.fromarray(image_array[0])
from PIL import Image
image_array = numpy.squeeze(image_array, axis=0)
im = Image.fromarray(image_array)
im.show()

How to read raw image in Python and plot as an image

I am trying to read a raw image file, but the stored image array seems to be one dimensional. Not sure how to read a raw file and plot it. Any help would be appreciated
Link to image TestImage1c.raw
from scipy import misc
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import math
A = np.fromfile("TestImage1c.raw", dtype='int16', sep="")
print("A.shape: %d", A.shape)
print("A: ", A)
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
print("img_gray :", img_gray)
print("img_gray shape: ", img_gray.shape)
print("img_gray size: ", img_gray.size)
plt.imshow(img_gray, cmap="gray")
plt.show()
OUTPUT:
D:\Python36\python.exe D:/PycharmProjects/First/readrawimage.py
A.shape: %d (1143072,)
A: [-27746 -24987 26514 ..., 28808 -31403 18031]
img_gray : -20149.59
img_gray shape: ()
img_gray size: 1
Traceback (most recent call last):
File "D:/PycharmProjects/First/readrawimage.py", line 33, in <module>
plt.imshow(img_gray, cmap="gray")
File "D:\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in
imshow
**kwargs)
File "D:\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in
inner
return func(ax, *args, **kwargs)
File "D:\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194,
in imshow
im.set_data(X)
File "D:\Python36\lib\site-packages\matplotlib\image.py", line 604, in
set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
Process finished with exit code 1
I found that RAW file is interleaved with RGB value an is one dimensional array
R(0,0) G(0,0) B(0,0)
R(0,1) G(0,1) B(0,1)
.......
A = np.fromfile("TestImage2c.raw", dtype='int8', sep="")
A = np.reshape(A, (756, 1008, 3))
img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11])
plt.imshow(img_gray, cmap="gray")
plt.show()
I started getting the image now.
Thank you all for response.

Zoom in an Image using python-numpy

I'm trying to zoom in an image.
import numpy as np
from scipy.ndimage.interpolation import zoom
import Image
zoom_factor = 0.05 # 5% of the original image
img = Image.open(filename)
image_array = misc.fromimage(img)
zoomed_img = clipped_zoom(image_array, zoom_factor)
misc.imsave('output.png', zoomed_img)
Clipped Zoom Reference:
Scipy rotate and zoom an image without changing its dimensions
This doesn't works and throws this error:
ValueError: could not broadcast input array from shape
Any Help or Suggestions on this
Is there a way to zoom an image given a zoom factor. And what's the problem ?
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1443, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "title_apis_proxy.py", line 798, in get
image, msg = resize_image(image_local_file, aspect_ratio, image_url, scheme, radius, sigma)
File "title_apis_proxy.py", line 722, in resize_image
z = clipped_zoom(face, 0.5, order=0)
File "title_apis_proxy.py", line 745, in clipped_zoom
out[top:top+zh, left:left+zw] = zoom(img, zoom_factor, **kwargs)
ValueError: could not broadcast input array from shape (963,1291,2) into shape (963,1291,3)
The clipped_zoom function you're using from my previous answer was written for single-channel images only.
At the moment it's applying the same zoom factor to the "color" dimension as well as the width and height dimensions of your input array. The ValueError occurs because the the out array is initialized to the same number of channels as the input, but the result of zoom has fewer channels because of the zoom factor.
To make it work for multichannel images you could either pass each color channel separately to clipped_zoom and concatenate the results, or you could pass a tuple rather than a scalar as the zoom_factor argument to scipy.ndimage.zoom.
I've updated my previous answer using the latter approach, so that it will now work for multichannel images as well as monochrome.

Categories