I am creating a function to "color" matrices given the indices to be colored.
Simplified example: I have a 2x2 matrix made of 0s and I want to "color" the 2nd and 4th element in the matrix with 1s. The output will be:
[[0,1]
[0,1]]
Now, here's the code I have (trying to color in white all odd elements of the matrix):
def createMatrix(w, h, bg, value, seq):
data = np.full((h, w, 3), bg, dtype=uint8)
rows = (seq-1)//w
cols = (seq-1)%w
if rows.size and cols.size:
data[rows,cols] = value
return data
data = createMatrix(w=4, h=4, bg=0, value=255, seq=array([1,3,5,7,9,11,13,15]))
Image.fromarray(data, 'RGB').resize((1024, 1024), Image.BOX).show()
This code works just fine, but it only allows me to use colors where the values for Red, Green and Blue are the same. I was then trying to generalize the function like this:
def createMatrix1(w, h, bg, value, seq):
data = np.tile(bg, (h, w, 1))
rows = (seq-1)//w
cols = (seq-1)%w
if rows.size and cols.size:
data[rows,cols] = value
return data
But for some reason this code returns two very different results:
data = createMatrix(w=4, h=4, bg=0, value=255, seq=array([1,3,5,7,9,11,13,15]))
data1 = createMatrix1(w=4, h=4, bg=(0,0,0), value=(255,255,255), seq=array([1,3,5,7,9,11,13,15]))
if np.array_equal(data, data1): print('The matrices are identical')
Image.fromarray(data, 'RGB').resize((1024, 1024), Image.BOX).show()
Image.fromarray(data1, 'RGB').resize((1024, 1024), Image.BOX).show()
Even though data
and data1
are identical.
What's going on?
CodePudding user response:
They are different data types, even if they evaluate to true.
data.dtype
dtype('unit8')
data1.dtype
dtype('int32')
You can convert it and the image will become a color image.
data = data.astype('int32')
or modify the function to use int32