Skip to content

Add example: pixel grid overlay on image #30457

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions galleries/examples/images_contours_and_fields/pixel_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
=========================
Image with Pixel Grid Overlay
=========================

This example shows how to overlay a pixel-aligned grid on an image in Matplotlib.
Such grids can be useful for teaching, image analysis, or visual inspection.
"""

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image


def pixel_grid(image, cell_size=50, grid_color="gray", grid_width=0.5):
"""
Display an image with a pixel grid overlay.

Parameters
----------
image : str or ndarray
Path to an image file or a NumPy array representing the image.
cell_size : int, default=50
Spacing between grid lines, in pixels.
grid_color : str, default='gray'
Color of the grid lines.
grid_width : float, default=0.5
Thickness of the grid lines.
"""
# Load image from file or array
if isinstance(image, str):
img = Image.open(image).convert("RGB")
else:
img = Image.fromarray(image)

width, height = img.size

fig, ax = plt.subplots(figsize=(8, 6))
ax.imshow(img)

# Vertical grid lines
for x in range(0, width, cell_size):
ax.axvline(x, color=grid_color, linewidth=grid_width)

# Horizontal grid lines
for y in range(0, height, cell_size):
ax.axhline(y, color=grid_color, linewidth=grid_width)

# Set limits and aspect ratio
ax.set_xlim([0, width])
ax.set_ylim([height, 0]) # flip Y-axis
ax.set_aspect("equal")

ax.set_title("Image with Pixel Grid Overlay")

plt.show()


# Example usage with synthetic image
if __name__ == "__main__":
# Create a synthetic grayscale image (200x300 pixels)
img = np.random.randint(0, 255, (200, 300), dtype=np.uint8)

pixel_grid(img, cell_size=40, grid_color="red", grid_width=1.0)

Check warning on line 64 in galleries/examples/images_contours_and_fields/pixel_grid.py

View workflow job for this annotation

GitHub Actions / ruff

[rdjson] reported by reviewdog 🐶 No newline at end of file Raw Output: message:"No newline at end of file" location:{path:"/home/runner/work/matplotlib/matplotlib/galleries/examples/images_contours_and_fields/pixel_grid.py" range:{start:{line:64 column:68} end:{line:64 column:68}}} severity:WARNING source:{name:"ruff" url:"https://docs.astral.sh/ruff"} code:{value:"W292" url:"https://docs.astral.sh/ruff/rules/missing-newline-at-end-of-file"} suggestions:{range:{start:{line:64 column:68} end:{line:64 column:68}} text:"\n"}
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy