简体   繁体   中英

Python: Greyscale image: Make everything white, except for black pixels

I tried to open (already greyscale) images and change all non-black pixels to white pixels. I implemented the following code:

from scipy.misc import fromimage, toimage
from PIL import Image
import numpy as np

in_path = 'E:\\in.png'
out_path = 'E:\\out.png'

# Open gray-scale image
img = Image.open(in_path).convert('L')

# Just for testing: The image is saved correct
#img.save(out_path)

# Make all non-black colors white
imp_arr = fromimage(img)
imp_arr = (np.ceil(imp_arr / 255.0) * 255.0).astype(int)

# Save the image
img = toimage(imp_arr, mode='L')
img.save(out_path)

The calculation to make all pixels white, except for the black ones is quite simple and also very fast. For my use-case it is especially important that it works very fast, for this reason i used numpy. For some reason this code does not work with all images?

An example: The following image is the input.

在此处输入图片说明

It contains a grey rectangle and also a white border. The output should be a complete white image, but for some reason the output is a black image:

在此处输入图片说明

With some other images it works quite well. What do i do wrong? I think floating point shouldn't be a big issue here, because this code does not require a high calculation accuracy to work.

Thank you very much

toimage expects a byte array, so convert to uint8 not int:

imp_arr = (np.ceil(imp_arr / 255.0) * 255.0).astype('uint8')

I seems to work for int if there is a mix of black and white pixels in the output, but not if they are all white. I can't find any explanation for this in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM