Peter Corke
Peter Corke

Reputation: 584

Display an image with pixel values shown numerically

I'm looking for OpenCV or other Python function that displays a NumPy array as an image like this:

image

Referenced from this tutorial.

MATLAB has a function called showPixelValues().

Upvotes: 4

Views: 4547

Answers (2)

Tony Power
Tony Power

Reputation: 1178

Using matplotlib you could do something like:

image = np.random.randint(low=0, high=255, size=(10, 10))

fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        ax.text(j, i, str(image[i, j]), color='r', ha='center', va='center')

It will produce the following image:

Image with pixel intensities

By the way, if you want to stick to grayscale only, you might want to try something like:

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        c = 1 if image[i, j] < 128 else 0
        ax.text(j, i, str(image[i, j]), color=(c, c, c), ha='center', va='center')
        ax.axis("off")

Resulting in:

enter image description here

Upvotes: 1

Peter Corke
Peter Corke

Reputation: 584

The best way to do this is to search "heat map" or "confusion matrix" rather than image, then there are two good options:

  1. Using matplotlib only, with imshow() and text() as building blocks the solution is actually not that hard, and here are some examples.

  2. Using seaborn which is a data visualisation package and the solution is essentially a one-liner using seaborn.heatmap() as shown in these examples.

My problem was really tunnel vision, coming at it from an image processing mindset, and not thinking about what other communities have a need to display the same thing even if they call it by a different name.

Upvotes: 4

Related Questions