Keep the original shape of the array as the image

Question:

I have some data. I visualize and then save it as image.

import cv2
import numpy as np
import matplotlib.pyplot as plt

data = np.array([
[1,2,0,1],
[0,1,2,1],
[0,0,2,1]])

fig, ax = plt.subplots()
ax.imshow(data)
ax.axis('off')
fig.savefig("test.png", bbox_inches='tight', pad_inches=0)

Next, I load the image and read the shape:

img = cv2.imread('test.png')
print(img.shape)

Output:

(217, 289, 3)

But I want to keep the original resolution and my expected output:

(3, 4, 3)

Any solution?

Upd.:

With dpi=1:

data = np.array([
    [1,2,0,1],
    [0,1,2,1],
    [0,0,2,1],
    [1,0,2,1],
    [4,1,0,2],
])
fig, ax = plt.subplots()
ax.imshow(data)
ax.axis('off')
fig.savefig("test.png", bbox_inches='tight', pad_inches=0, dpi = 1) 

img = cv2.imread('test.png')
img.shape

print(data.shape, img.shape)

Output:

(5, 4) 
(3, 2, 3)
Asked By: voldr

||

Answers:

Since you’re using two different libraries for creating an image and reading the image, it would be difficult to retain the array size as no such information is stored with the image.

The dpi is also specific to your monitor screen and hence is not recommended. Refer to the answer here for more on this.

Also, you’re trying to write the image as a 2D array, but when cv2.imread() reads it, it would also consider the color channel and add the third dimension. To avoid this you need to read the image as a grayscale image.

I would suggest that you use cv2.imwrite() to generate the image (works similar to plt.savefig()) and then read the image using cv2.imshow() as a grayscale image.

import cv2
import numpy as np

data = np.array([
[1,2,0,1],
[0,1,2,1],
[0,0,2,1]])


cv2.imwrite("test.png", data)


img = cv2.imread("test.png", 0) #Using 0 to read in grayscale mode
print(data.shape, img.shape)

Output:

(3, 4) (3, 4)
Answered By: Shivam Roy

The creation of an image using imshow is totally unnecessary, you can simply compute the matrix of RGBA values that you are interested into

import numpy as np
import matplotlib as mp

data = np.array([ [1,2,0,1],[0,1,2,1],[0,0,2,1]])
n = mp.colors.Normalize(data.min(), data.max())
c = mp.cm.viridis(n(data))[:,:,:-1] # [...,:-1] disregards the alpha values
Answered By: gboffi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.