Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert image to value matrix

I have an image which is like a chess board with 4 colors (Black, white, Red, Blue). I have to convert this image to a matrix of numbers: 1 for white, 2 for black, 3 for red so on.

For example the image:

Chessboard

should be converted to the matrix:

[[1,2,1,2,1,2...]
[2,1,2,1,2,1...]
...]

I'd prefer a solution in python.

like image 440
d.putto Avatar asked Oct 19 '25 17:10

d.putto


1 Answers

I am not sure about SVG Images but lets suppose you have an image format readable by PIL (e.g. GIF, TIFF, JPEG, BMP, ...). Then you can read it using PIL like that:

import Image
img = Image.open("Chess_Board.bmp")

Now we want do do quantization, so the image pixels are not RGB anymore but a color index from 0 to 3 (suppose you want 4 different colors):

quantized = img.convert('P', palette=Image.ADAPTIVE, colors=4)

Next I suppose we convert it to numpy for easier access of the individual pixels. Then we do numpy magic to count how many go into one block:

import numpy as np
a = np.array(quantized)
blockLengthX = np.argmin(a[0]==a[0,0])
blockLengthY = np.argmin(a[:,0]==a[0,0])

After that it is easy. We just access the array using stepsize blockLengthX for cols and blockLengthY for rows:

result = a[::blockLengthX, ::blockLengthY]

Of course this assumes all of your blocks are exactly the same size. Here is the complete program for easier copy and paste. I also shortened a bit:

import Image
import numpy as np
img = Image.open("Chess_Board.bmp")
a = np.array(img.convert('P', palette=Image.ADAPTIVE, colors=4))
blockLengthX = np.argmin(a[0]==a[0,0])
blockLengthY = np.argmin(a[:,0]==a[0,0])
result = a[::blockLengthX, ::blockLengthY]
like image 155
Qlaus Avatar answered Oct 22 '25 08:10

Qlaus