I am using mnist dataset for training a capsule network in keras background.
After training, I want to display an image from mnist dataset. For loading images, mnist.load_data() is used. The data is stored as (x_train, y_train),(x_test, y_test).
Now, for visualizing image, my code is as follows:
img_path = x_test[1]
print(img_path.shape)
plt.imshow(img_path)
plt.show()
The code gives output as follows:
(28, 28, 1)
and the error on plt.imshow(img_path) as follows:
TypeError: Invalid dimensions for image data
How to show image in png format. Help!
Accepted answer
You can use tf.squeeze
for removing dimensions of size 1 from the shape of a tensor.
plt.imshow( tf.shape( tf.squeeze(x_train) ) )
Check out TF2.0 example
Invalid dimension for image data in plt.imshow()
Python matplotlib, invalid shape for image data
TypeError: Invalid shape (100, 100, 1) for image data When plot image
Retrieve data from db & set to textinput fields and image widget in Kivy for a multiscreen app! AttributeError
zip does not work for imshow: TypeError: Image data cannot be converted to float
problem after read data from database ValueError: invalid literal for int() with base 10: '\r'
'TypeError: Invalid shape (10000, 28, 28) for image data' in tensor flow Fashion MNIST image prediction
Python: Error Importing data from CSV to Postgres (ERROR: invalid input syntax for integer:)
Image library for Python 3
ValueError: invalid literal for int () with base 10
score:0
matplotlib.pyplot.imshow()
does not support images of shape (h, w, 1)
. Just remove the last dimension of the image by reshaping the image to (h, w)
: newimage = reshape(img,(h,w))
.
As per the comment of @sdcbr using np.sqeeze reduces unnecessary dimension. If image is 2 dimensions then imshow function works fine. If image has 3 dimensions then you have to reduce extra 1 dimension. But, for higher dim data you will have to reduce it to 2 dims, so np.sqeeze may be applied multiple times. (Or you may use some other dim reduction functions for higher dim data)
import numpy as np
import matplotlib.pyplot as plt
img_path = x_test[1]
print(img_path.shape)
if(len(img_path.shape) == 3):
plt.imshow(np.squeeze(img_path))
elif(len(img_path.shape) == 2):
plt.imshow(img_path)
else:
print("Higher dimensional data")
Upload Image using POST form data in Python-requests
TypeError: 'encoding' is an invalid keyword argument for this function
Tensorboard Error: No dashboards are active for current data set
Is there a Google Data API (gdata) for Python 3.x?
Tkinter error: Couldn't recognize data in image file
Oversampling: SMOTE for binary and categorical data in Python
Cross-validation for grouped time-series (panel) data
TypeError: 'newline' is an invalid keyword argument for this function
TypeError: 'cmp' is an invalid keyword argument for this function
How do I load custom image based datasets into Pytorch for use with a CNN?
Are there image processing modules for Python 3?
Displaying an image with Pygobject and Python 3 from in-memory data
Check for invalid path in Python
Clean invalid characters from data held in a Spark RDD
ValueError: Negative dimension size caused by subtracting 3 from 1 for 'conv1d_1/convolution/Conv2D
AxisError: axis 1 is out of bounds for array of dimension 1 when calculating AUC
Plotly: How to show all the stacked y axis data values while hovering for three y layout and one x axis shared graph?
Proper Usage of PyTorch's non_blocking=True for Data Prefetching
UserWarning: Implicit dimension choice for log_softmax has been deprecated
What is the state of the art way to handle what makefiles do for python data analysis?
openpyxl cannot read Strict Open XML Spreadsheet format: UserWarning: File contains an invalid specification for Sheet1. This will be removed
Data Structure for fast insertion and random access in already sorted data
for Imbalanced data dealing with cat boost
insert data from two lists to dict with for loop
How do I compare two nested data structures for unittesting?
Get Binary Image Data From a MatPlotLib Canvas?
using sklearn.train_test_split for Imbalanced data
How to search for a substring, find the beginning and ending, and then check if that data is a weekday?
Opening Image file from url with PIL for text recognition with pytesseract
Is there a way to achieve drag and drop for Magento image upload using Selenium?
How to add/get image data in the OS clipboard using Python?
Python3 csv writer failing, exiting on error "TypeError: 'newline' is an invalid keyword argument for this function
PyAutoGUI locate command returning incorrect coordinates for image recognition
Simple python library for recognition text from image
Where does Keras store downloaded data for MNIST?
Mask data in an xarray and changing values for both True and False responses
Programming Python for absolute beginners: Chapter 7 Storing Complex Data
asyncio doesn't send the entire image data over tcp
'Shuffle' is claimed to be an invalid parameter for model_selection.train_test_split
XGboost: cannot pass validation data for eval_set in pipeline
More Query from same tag
How to get pathlib’s unix path handling goodies without the system specific ones, eg Path.resolve() changes /tmp to /private/tmp
ModuleNotFoundError: No module named 'Src' - When I run a Pytest
Pygame problem: how to execute conditional on collision?
why can't I change the variables using kwargs inside a function?
How to specify the loss function when finetuning a model using the Huggingface TFTrainer Class?
python3.4 tkinter.scrolledtext not callable
Better way to write recursive random variables
BeautifulSoup.find() is returning None, unable to access table on wiki page
Should I use raw string by default?
Getting a different value when adding a float value in an integer (PYTHON)
Write key to separate csv based on value in dictionary
Python - Itemgetter on Dates
How do I run "pandas.read_csv" with the ''delimeter" inside the definition of a generator function?
Can I update python 3.6.3 to 3.6.5, which is the latest, on windows 10?
Install gobject module?
How to query an input in Python without outputting a new line (cont.)
Need help for relative paths imports
Can a function feed two values into another function?
Executing a kmedoids python module
Python: Trouble with encoding on Windows (Bokeh plotting library)
AttributeError: cffi library '(pyModulesPath)\_soundfile_data\libsndfile64bit.dll' has no function, constant or global variable named 'sf_wchar_open'
How to rotate an object from the center in pycharm?
Solving Python Riddle
Nested function in Python class
Why can't I place this class using the tkinter grid method?
Changing table column width using Google-Slide-API and python
Is there a way to assign a descriptor to an instance attribute at runtime?
How to write to an open Excel file using Python?
How to upgrade to python 3.6.4 on macos?
Is it possible to input Chinese text into tk Text and Entry widgets with tkinter?
Need help to understand a peice of while loop code?
Python - Merge PDF files with same prefix using PyPDF2
Python recursive function counting the user
Faulty string representation
Read nested data from json using .proto in python
Different results while training with CudnnLSTM compared to regular LSTMCell in Tensorflow
cast tensorflow 2.0 BatchDataset to numpy array
Tensorflow restore while ignoring scope name or into new scope name
Object detection Classfication /A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights)
"unsupported/Eigen/CXX11/Tensor: No such file or directory" while working with TensorFlow
Translation Model Predictions: TypeError: Object of type 'EagerTensor' is not JSON serializable
Is it possible to get OpenCL on Windows Linux Subsystem?
How to do parallel GPU inferencing in Tensorflow 2.0 + Keras?
How to create a NoneType Error workaround occurring within a functional input with occasional nonetype set
How do I write a parameter of a function if its a string in a statement?
BeautifulSoup adding extra whitespace before and after each opening and closing tag
Python Error: TypeError: 'NoneType' object is not callable
How to merge/collapse child DOM node into parent with BeautifulSoup / lxml?
Using BeautifulSoup where authentication is required
chrome fails to load SOME scripts & stylesheets with ERR_INVALID_HTTP_RESPONSE (for a flask app on linux (debian))
Change model representation in Flask-Admin without modifying model
Configure module logger to flask app logger
Disabling logger in Flask Socket.io
Get Data JSON in Flask
Ensure the POST data is valid JSON
Python Flask "send_file()" method TypeError
How to set a conda env with uwsgi and supervisor?
How to redirect from helper function in Flask?