4

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

image

Referenced from this tutorial.

  • What function creates this kind of grey-scale image with pixel values display?
  • Is there a color image equivalent?

MATLAB has a function called showPixelValues().

Peter Corke
  • 544
  • 4
  • 16
  • There are a lot of ways to do this. For example, [plot it as a heatmap](https://stackoverflow.com/questions/35572000/how-can-i-plot-a-confusion-matrix) and you will get the same result. – Camilo Martinez M. May 05 '21 at 23:04
  • Thanks for the pointer. Seaborn does it directly at the cost of one more package. "heat map" is a good search term, and here's an example using [matplotlib](https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html) – Peter Corke May 06 '21 at 01:10
  • 1
    so the problem solved ? – Amir Karami May 06 '21 at 06:06

2 Answers2

4

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.

Peter Corke
  • 544
  • 4
  • 16
1

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

Tony Power
  • 1,033
  • 11
  • 23