vftw
vftw

Reputation: 1677

a bytes-like object is required, not 'Image'

I want to write an Image object to disk but I keep getting the error:

 a bytes-like object is required, not 'Image'

First I convert a String to an array and then I create an Image using that array.

    class Item(object):

def __init__(self, patch, coords, label):

    self.channels = patch.shape[2]
    # Assuming only square images.
    self.size = patch.shape[0]
    self.data = patch.tobytes()
    self.label = label # Integer label ie, 2 = Carcinoma in situ
    self.coords = coords

def get_label_array(self, num_classes):
    l = np.zeros((num_classes))
    l[self.label] = 1
    return l

def get_patch(self):
    return np.fromstring(self.data, dtype=np.uint8).reshape(self.size, self.size, self.channels)

def get_patch_as_image(self):
    return Image.fromarray(self.get_patch(), 'RGB')

Is there any way that I can save the image using:

def save_in_disk(patches, coords, file_name, labels=[]):
    use_label = False
    if len(labels) > 0:
        use_label = True

    # txn is a Transaction object
    for i in range(len(patches)):
        if use_label:
            item = Item(patches[i], coords[i], labels[i])
        else:
            item = Item(patches[i], coords[i], 0)

        p = item.get_patch_as_image()

        str_id = file_name + '-' + str(coords[i][0]) + '-' + str(coords[i][1]) + '.png'
        print(str_id)
        with open(str_id, 'wb+') as f:
            f.write(p)

Any idea what is going wrong?

Regards

Upvotes: 3

Views: 19638

Answers (1)

NanoPish
NanoPish

Reputation: 1501

What library do you use?

If you want to write a png image file to disk you need to get the formatted data, e.g. with BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

It will be different depending on the library you use.


If you want to save a python image object to disk, you can use pickle / serialization.

In case of pure Python classes you can simply use pickle:

import pickle
with open('Storage', 'wb') as f:
    pickle.dump(instance001, f)

and load it:

with open('Storage', 'rb') as f:
    instance002 = pickle.load(f)

print(instance002.a)   # 2
print(instance002.b)   # 200

It looks like you use PIL. You save Image as a PNG file like this:

newImg1.save("img1.png","PNG")

Upvotes: 2

Related Questions