Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting An Array to Image

Tags:

python

image

I am having an array of 64*64 consists of 0 and 1. How do i convert this array to image and save it ?

from PIL import Image
img = Image.fromarray(data , 'RGB') // 
img.save('my.png')
img.show()

'Removing RGB is not giving me expected result All 1's array is also giving me black'

The above code is giving me error , i can not convert it, how to convert it if i want to lower resolution image i.e 16*16

like image 944
Narendra Modi Avatar asked Aug 26 '26 01:08

Narendra Modi


2 Answers

from PIL import Image

import random
data = [random.randint(0, 1) for i in range(64 * 64)]

img = Image.new('1', (64, 64))
img.putdata(data)
img.save('my.png')
img.show()
like image 166
Simon J. Liu Avatar answered Aug 27 '26 15:08

Simon J. Liu


from PIL import Image
import numpy as np
from random import randint


# create random array
def create_arr(width, height):
    bin_array = np.zeros((width, height), 'uint8')
    for x in xrange(0, width):
        for y in xrange(0, height):
            bin_array[x, y] = randint(0, 1)
    return bin_array

# write array to img
def create_img(width, height, bin_array):
    rgb_array = np.zeros((width, height, 3), 'uint8')
    for x in xrange(0, width):
        for y in xrange(0, height):
            rgb_array[x, y, 0] = bin_array[x, y] * 255 #R
            rgb_array[x, y, 1] = bin_array[x, y] * 255 #G
            rgb_array[x, y, 2] = bin_array[x, y] * 255 #B

    img = Image.fromarray(rgb_array)
    img.save('img.jpeg')

# create array
bin_array = create_arr(64, 64)
# write bin_array to img
create_img(64, 64, bin_array)
like image 27
IvanB Avatar answered Aug 27 '26 14:08

IvanB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!