TypeError: Invalid dimensions for image data when plotting array with imshow()

2024/11/21 2:36:43

For the following code

# Numerical operation
SN_map_final = (new_SN_map - mean_SN) / sigma_SN  # Plot figure
fig12 = plt.figure(12)
fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')
plt.colorbar()fig12 = plt.savefig(outname12)

with new_SN_map being a 1D array and mean_SN and sigma_SN being constants, I get the following error.

Traceback (most recent call last):File "c:\Users\Valentin\Desktop\Stage M2\density_map_simple.py", line 546, in <module>fig_SN_final = plt.imshow(SN_map_final, interpolation='nearest')File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\pyplot.py", line 3022, in imshow**kwargs)File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\__init__.py", line 1812, in innerreturn func(ax, *args, **kwargs)File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\axes\_axes.py", line 4947, in imshowim.set_data(X)File "c:\users\valentin\appdata\local\enthought\canopy\user\lib\site-packages\matplotlib\image.py", line 453, in set_dataraise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data

What is the source of this error? I thought my numerical operations were allowed.

Answer

There is a (somewhat) related question on StackOverflow:

  • Showing an image with pylab.imshow()

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as npdef valid_imshow_data(data):data = np.asarray(data)if data.ndim == 2:return Trueelif data.ndim == 3:if 3 <= data.shape[2] <= 4:return Trueelse:print('The "data" has 3 dimensions but the last dimension ''must have a length of 3 (RGB) or 4 (RGBA), not "{}".'''.format(data.shape[2]))return Falseelse:print('To visualize an image the data must be 2 dimensional or ''3 dimensional, not "{}".'''.format(data.ndim))return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

https://en.xdnf.cn/q/26249.html

Related Q&A

How to give delay between each requests in scrapy?

I dont want to crawl simultaneously and get blocked. I would like to send one request per second.

preprocess_input() method in keras

I am trying out sample keras code from the below keras documentation page, https://keras.io/applications/What preprocess_input(x) function of keras module does in the below code? Why do we have to do …

How to calculate precision and recall in Keras

I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.

Django set range for integer model field as constraint

I have a django model,class MyModel(models.Model)qty = model.IntegerField()where I want to set constraint for qty something like this, >0 or <0,i.e the qty can be negative or positive but can no…

Increase resolution with word-cloud and remove empty border

I am using word cloud with some txt files. How do I change this example if I wanted to 1) increase resolution and 2) remove empty border. #!/usr/bin/env python2 """ Minimal Example =====…

How can I check if a list index exists?

Seems as thoughif not mylist[1]:return FalseDoesnt work.

Check if space is in a string

in word == TrueIm writing a program that checks whether the string is a single word. Why doesnt this work and is there any better way to check if a string has no spaces/is a single word..

Django F expressions joined field

So I am trying to update my model by running the following: FooBar.objects.filter(something=True).update(foobar=F(foo__bar))but I get the following error: FieldError: Joined field references are not pe…

How do I unit test PySpark programs?

My current Java/Spark Unit Test approach works (detailed here) by instantiating a SparkContext using "local" and running unit tests using JUnit.The code has to be organized to do I/O in one f…

Sorting by arbitrary lambda

How can I sort a list by a key described by an arbitrary function? For example, if I have:mylist = [["quux", 1, "a"], ["bar", 0, "b"]]Id like to sort "myl…