gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:44:38 25 4
gpt4 key购买 nike

我想将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com