Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a white image in Python?

Upon doing my homework, I stumbled across a problem concerning Python and image manipulation. I must say, using the Image lib is not an option. So here it is

from scipy.misc import imread,imsave
from numpy import zeros

imga = zeros([100,100,3])
h = len(imga)
w = len(imga[0])

for y in range(h):
    for x in range(w):
        imga[y,x] = [255,255,255]

imsave("Result.jpg",imga)

I would assume it makes my picture white, but it turns it black, and I have no idea why It's not about the code (and I know it looks very ugly). Its just about the fact, that it is a black image.

like image 569
Lefix Avatar asked May 05 '12 20:05

Lefix


People also ask

How do you create a image in Python?

new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names.

Can you code images in Python?

PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors.


3 Answers

Every color in an image is represented by one byte. So to create an image array, you should set it's dtype to uint8.

And, you don't need for-loop to set every elements to 255, you can use fill() method or slice index:

import numpy as np
img = np.zeros([100,100,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255
like image 56
HYRY Avatar answered Oct 08 '22 09:10

HYRY


Easy! Check the below Code:

whiteFrame = 255 * np.ones((1000,1000,3), np.uint8)

255 is the color for filling the bytes.

1000, 1000 is the size of the image.

3 is the color channel for the image.

And unit8 is the type

Goodluck

like image 9
Etezadi Avatar answered Oct 08 '22 09:10

Etezadi


When creating imga, you need to set the unit type. Specifically, change the following line of code:

imga = zeros([100,100,3], dtype=np.uint8)

And, add the following to your imports:

import numpy as np

That gives a white image on my machine.

like image 2
Sam Cantrell Avatar answered Oct 08 '22 09:10

Sam Cantrell