python - 需要一个类似字节的对象,而不是 'Image'

标签 python

我想将 Image 对象写入磁盘,但我不断收到错误:

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

首先,我将字符串转换为数组,然后使用该数组创建图像。

    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')

有什么方法可以使用以下方式保存图像:

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)

知道出了什么问题吗?

问候

最佳答案

你使用什么库?

如果你想将 png 图像文件写入磁盘,你需要获取格式化数据,例如使用 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')

根据您使用的库的不同,它会有所不同。

<小时/>

如果要将Python图像对象保存到磁盘,可以使用pickle/序列化。

如果是纯 Python 类,您可以简单地使用 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
<小时/>

看来您使用的是 PIL。将图像另存为 PNG 文件,如下所示:

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

关于python - 需要一个类似字节的对象,而不是 'Image',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51516511/

相关文章:

python - 使用 NumExpr : An analysis 提高 NumPy 代码的运行时间

Python语法/理解

python - 2D数组到3D数组的数量,扩展第三维

python - 如何在 scikit-learn 中使用 SGDRegressor

python - 无法将输入转换为时间戳、bday_range(...) - Pandas/Python

python - 如何在 Python 中使用 os.getcwd() 向 Maya 正确发送命令

python - 如何向 Python 2.x ConfigParser 指定 unicode 和其他转义文字

python - 打印错误类型、错误语句和自身语句

python - 使 difflib 的 SequenceMatcher 忽略 "junk"个字符

python - 值错误: Invalid RGBA argument: 'rgbkymc'