DuttaA
DuttaA

Reputation: 923

Matrix values for an image

So, I am trying to convert a b/w image into its corresponding matrix. I have used the suggestion to convert into the matrix representation given in this answer.

How to see the whole matrix of an image in python?

The image is: enter image description here

And the corresponding json file I got consisted mostly of [1.0, 1.0, 1.0]. Since the majority of the paper is white I am assuming [1.0, 1.0, 1.0] stands for white.But how so? White is represented by [255, 255, 255]. So what exactly is happening here?

Upvotes: 0

Views: 239

Answers (2)

Arne
Arne

Reputation: 20137

From what the docu implies, a result with MxNx3 dimensions implies RGB encoding. The only thing left to do then is to turn their representation (float[0..1]) into the one you want (int[0..255]):

with open('your_image.png', 'r') as img:
    image_as_floats = json.load(img)
image_as_ints = [[int(r*255), int(g*255), int(b*255)] for r, g, b, in image_as_floats]

with open('your_image_2.png', 'w') as img:
    img.write(json.dumps(img))       

Upvotes: 1

Matan Hugi
Matan Hugi

Reputation: 1130

This is an RGB image. the easiest thing would be to use PIL.Image module and numpy

from PIL import Image
import numpy as np
img = Image.open(PATH_TO_IMAGE)
img_as_matrix = np.array(img)
np.savetxt('imagematrix.txt', img_as_mtrix, delimiter=" ", fmt="%s") 

Upvotes: 1

Related Questions