Reputation: 601
I'm trying to do a simple rotation of a sample image, but when I try to display it, the file just shows black pixels. I can tell that it has rotated, because the dimensions are changed properly.
from io import BytesIO
import numpy as np
from PIL import Image
from skimage.transform import rotate
from flask import send_file
image_file = Image.open(file_path).convert("L")
image_array = np.array(image_file)
image_array_rotated = rotate(image_array, angle=90, resize=True)
rotated_image_file = Image.fromarray(image_array_rotated).convert("L")
buffered_image_file = BytesIO()
rotated_image_file.save(buffered_image_file, 'PNG')
buffered_image_file.seek(0)
return send_file(buffered_image_file, mimetype='image/png')
If I remove the rotation code and show the original image, or the converted grayscale ("L") image, they both show up fine. My rotated image is just black.
Upvotes: 0
Views: 455
Reputation: 5768
scikit-image automatically converts images to floating point any time that interpolation or convolution is necessary, to ensure precision in calculations. In converting to float, the range of the image is converted to [0, 1]. You can read more about how it treats data types here:
https://scikit-image.org/docs/dev/user_guide/data_types.html
Here is how you could modify your code to work with PIL data:
from io import BytesIO
import numpy as np
from PIL import Image
from skimage.transform import rotate
from skimage import util
from flask import send_file
image_file = Image.open(file_path).convert("L")
image_array = util.img_as_float(np.array(image_file))
image_array_rotated = rotate(image_array, angle=90, resize=True)
image_array_rotated_bytes = util.img_as_ubyte(image_array_rotated)
rotated_image_file = Image.fromarray(image_array_rotated).convert("L")
buffered_image_file = BytesIO()
rotated_image_file.save(buffered_image_file, 'PNG')
buffered_image_file.seek(0)
return send_file(buffered_image_file, mimetype='image/png')
Alternatively, you could use skimage.io.imsave
, which would do all these conversions for you behind the scenes.
Another option, as pointed out by Mark in the comments, is to use PIL for the rotation also.
Upvotes: 2