4

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.

Chris
  • 8,030
  • 4
  • 37
  • 56
d.putto
  • 7,185
  • 11
  • 39
  • 45
  • Assuming that the spaces have to be congruent, a decent approach would be to count all of the pixels in the top left "rectangle" until you reach a different color on both the x and y axis. You can then simply add the width/height of this rectangle to its top left pixel to get the color of the top left pixel of other rectangles. – cabbagebot Jun 26 '12 at 16:55
  • What are the knowns, and unknowns? Do you know how many coloured squares there are? If you know the order and size, there is no need to do the conversion. just create the new array. – fraxel Jun 26 '12 at 17:23
  • Did my answer solve your problem? – Qlaus Jul 01 '12 at 20:15

1 Answers1

5

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]
Community
  • 1
  • 1
Qlaus
  • 885
  • 5
  • 15
  • 1
    for the picture is question code gives error >>>result =a[::blockLengthX, ::blockLengthY] ValueError: slice step cannot be zero – d.putto Jul 03 '12 at 12:16