Visualize MNIST dataset using OpenCV or Matplotlib/Pyplot
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
The MNIST dataset contains 70,000 grayscale images of handwritten digits (28x28 pixels each). To visualize MNIST images, use matplotlib.pyplot.imshow() with cmap='gray' for quick plots, or cv2.imshow() with OpenCV for interactive windows. Matplotlib is better for grids, annotations, and notebook displays. OpenCV is better for real-time image processing pipelines. Both require the images to be reshaped from flat vectors (784,) to 2D arrays (28, 28) if loaded from certain sources.
Loading MNIST
Visualize a Single Image with Matplotlib
Visualize a Grid of Images
Show One Example Per Digit
Visualize with OpenCV
Visualize Pixel Value Distribution
Handling Flat Vectors
Common Pitfalls
- Forgetting
cmap='gray'in matplotlib: Without it, matplotlib uses a color map (viridis by default) for grayscale images, making digits appear in blue/yellow instead of white/black. Always passcmap='gray'toimshow()for grayscale data. - Not reshaping flat vectors to 28x28: Some sources (scikit-learn's
fetch_openml, CSV files) return MNIST as flat 784-element vectors. Passing a flat vector toimshow()fails with a shape error. Reshape withimg.reshape(28, 28)before displaying. - Pixel values in wrong range for OpenCV: OpenCV
imshowexpects uint8 (0-255) for grayscale display. If your images are normalized to 0.0-1.0 (common after preprocessing), multiply by 255 and cast:(img * 255).astype(np.uint8). Otherwise the display appears all black or all white. - OpenCV window not appearing or freezing:
cv2.imshow()requirescv2.waitKey()to process window events. Without it, the window appears frozen or never renders. Usecv2.waitKey(0)to wait for a keypress orcv2.waitKey(1)in a loop for real-time display. - Mixing up TensorFlow and PyTorch image formats: TensorFlow MNIST returns
(batch, 28, 28)with values 0-255. PyTorch transforms often produce(batch, 1, 28, 28)with values 0.0-1.0. Before visualizing PyTorch tensors, squeeze the channel dimension and convert:img.squeeze().numpy().
Summary
- Use
plt.imshow(img, cmap='gray')for quick MNIST visualization in notebooks and scripts - Use
cv2.imshow()withcv2.resize()for interactive or real-time display - Create grids with
plt.subplots()to compare multiple digits at once - Reshape flat 784-element vectors to (28, 28) before displaying
- Normalize pixel values to the correct range for each library (0-255 for OpenCV, 0-1 or 0-255 for matplotlib)
Related reading
- What algorithm could be used to identify if images are the same or similar, regardless of size?
- What algorithm does Photoshop use to desaturate an image?
- What algorithm to use to segment a sequence of numbers into n subsets, to minimize the standard deviation of the sum of the numbers in each subset
- What are good features for classifying photos of clothing?
- Visualizing attention activation in Tensorflow
- Visualizing branch topology in Git
- What are possible values for data_augmentation_options in the TensorFlow Object Detection pipeline configuration?
- What are the uses of tf.space_to_depth?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.