Search code examples
pythonnumpyscipy

How to create a white image in Python?


The following code creates a black picture:

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

img = zeros([100,100,3])
for y in range(len(img)):
    for x in range(len(img[0])):
        img[y,x] = [255,255,255]
imsave("Result.jpg",img)

I would have assumed it to be white.

Edit in 2024: The code block is deprecated and won't run anymore.


Solution

  • 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