Nicolai Iversen
Nicolai Iversen

Reputation: 369

Upload numpy array as grayscale image to S3 bucket

I have made some mathematical operations on some grayscaled images in python using numpy.

Now I want to upload the resulting numpy arrays as png images to my S3 bucket. I have tried to upload them as base64 formats, but in that way I cannot open them as images from S3. My code looks as follows:

dec=base64.b64decode(numpy_image)
s3.Bucket('bucketname').put_object(Key='image.png',Body=dec, ContentType='image/png',ACL='public-read')

When I try to open the file from S3 it says that the file contains an error

Upvotes: 1

Views: 4457

Answers (2)

Leo Quiroa
Leo Quiroa

Reputation: 55

This works using the CV2 library

data_serial = cv2.imencode('.png', frame)[1].tostring()
s3.Object(bucket_name, key_path).put(Body=data_serial,ContentType='image/PNG')

Upvotes: 2

Nicolai Iversen
Nicolai Iversen

Reputation: 369

So I needed to convert the numpy array into an image first. The following code turned out to work:

from PIL import Image
import io
img = Image.fromarray(numpy_image).convert('RGB')
out_img = BytesIO()
img.save(out_img, format='png')
out_img.seek(0)  
s3.Bucket('my-pocket').put_object(Key='cluster.png',Body=out_img,ContentType='image/png',ACL='public-read')

Upvotes: 8

Related Questions