Error Converting PIL B&W images to Numpy Arrays
Posted
by Elliot
on Stack Overflow
See other posts from Stack Overflow
or by Elliot
Published on 2010-05-03T22:30:41Z
Indexed on
2010/05/03
22:38 UTC
Read the original article
Hit count: 319
I am getting weird errors when I try to convert a black and white PIL image to a numpy array. An example of the code I am working with is below.
if image.mode != '1':
image = image.convert('1') #convert to B&W
data = np.array(image) #convert data to a numpy array
n_lines = data.shape[0] #number of raster passes
line_range = range(data.shape[1])
for l in range(n_lines):
# process one horizontal line of the image
line = data[l]
for n in line_range:
if line[n] == 1:
write_line_to(xl, z+scale*n, speed) #conversion to other program code
elif line[n] == 0:
run_to(xl, z+scale*n) #conversion to other program code
I have tried this using both array and asarray for the conversion, and gotten different errors. If I use array, then the data I get out is nothing like what I put in. It looks like several very shrunken partial images side by side, with the remainder of the image space filled in in black. If I use asarray, then the entirety of python crashes during the raster step (on a random line). If I work with a greyscale image ('L'), then neither of these errors occurs for either array or asarray.
Does anyone know what I am doing wrong? Is there something odd about the way PIL encodes B&W images, or something special I need to pass numpy to make it convert properly?
© Stack Overflow or respective owner