我想将Image对象写入磁盘,但我不断收到错误消息:
a bytes-like object is required, not 'Image'
首先,我将一个String转换为一个数组,然后使用该数组创建一个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)
有什么想法吗?
致谢
答案 0 :(得分:1)
您使用什么图书馆?
如果要将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")