image-dreamer
image-dreamer copied to clipboard
Make dreamify.py more resilient to input image files
Make the input image's numpy array the right format for preprocess() by adding a conversion to RGB in the image read statement:
img = np.float32(PIL.Image.open(sys.argv[1]).convert('RGB'))
Otherwise, it's pretty easy to find JPG or other types of files that crash the script.
It might be less trouble for a user if the image write format were left to PIL to intuit from the output file name's extension, too.
(Hope this is readable. Browser not supported by github.)
Seems legit. I'll add it to #9 when I can test it. I'll also match the output file type to input as you suggested, and think about what to do if the user supplies a filename with a different extension.
I was unclear about the output file type. With PIL you can generally just code the output like this:
pil_image.save(output_file_name)
save() uses output_file_name's extension (e.g. .jpg, .png, .bmp, etc) to figure out the desired image file type. save() recognizes and saves a large variety of image types.
I see what you're saying, but the existing save code looks like...
def savearray(a, filename, fmt='png'):
a = np.uint8(np.clip(a, 0, 255))
with open(filename, 'wb') as f:
PIL.Image.fromarray(a).save(f, fmt)
so, passing a desired file extension in to fmt
, e.g. jpg, bmp, etc., would achieve the same result?
Not exactly. If you tell save() to save the file in a particular format, you could, for instance, end up saving a file named, 'foo.jpg' in PNG form. That would be confusing to humans if not to many programs. And probably not what you wanted to do.
Anyway, it would be pretty rare that someone would want to save the image file in a format not indicated by the file name's extension. Letting PIL handle the output format makes for one less thing to worry about or to get wrong.
To keep the ability to force the format, the code could probably be something like this:
def savearray(a, filename, fmt=None):
a = np.uint8(np.clip(a, 0, 255))
PIL.Image.fromarray(a).save(filename, fmt or None)