Home > Net >  Printing Images With Python
Printing Images With Python

Time:11-14

I want to plot a 37x37 black&white image, so far I have created a matrix and was hoping to get black pixels for 1's and white pixels for 0's. I dont know what went wrong.

import numpy as np
from PIL import Image
cols37 = [1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1]
rows = []

for i in range (37):
    rows.append(cols37)

mura = np.array(rows, dtype = np.bool)
temp = Image.fromarray(mura, '1')
temp.save('my1.png')
temp.open('my1.png')

I am currently getting this image:

current output

Instead, I am supposed to get something like this:

desired output

CodePudding user response:

It is caused by two issues

  • Option mode specified with '1' will get rawmode '1;8', then it will decode wrong raw data from numpy array, remove option '1' will get rawmode '1', also result image with mode '1'.
  • Same row data in rows, so you won't get right image as requested, or ten vertical black lines in your images.
import numpy as np
from PIL import Image

cols37 = [1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,0]
rows = []

for i in range (37):
    rows.append(cols37)

mura = np.array(rows, dtype = np.bool)
temp = Image.fromarray(mura)        # temp.mode will be `'1'`

or

import numpy as np
from PIL import Image

cols37 = [1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,0]
row_data = [255 if item else 0 for item in cols37]
rows = [row_data for i in range(37)]

mura = np.array(rows, dtype=np.uint8)
temp = Image.fromarray(mura, mode='L')
temp.convert('1')

Both scripts will get same image

enter image description here

Update: Actually, there's only 36 data in cols37, here I convert your data from 1D to 2D with NOT XOR operation , then get picture like yours.

import numpy as np
from PIL import Image

cols36 = [1,0,1,1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1]
row = cols36   cols36[::-1]

rows = []
for y in range(72):
    line = []
    for x in range(72):
        line.append(not(row[x] != row[y]))
    rows.append(line)
    line = []

mura = np.array(rows, dtype = np.bool)
im = Image.fromarray(mura)        # temp.mode will be `'1'`
im.show()

enter image description here

  • Related