我正在使用 Microsoft 的人脸认知服务,我的工作流程将图像作为一个 numpy 数组MS 允许图像作为 url 或作为标题中的数据传入如果数据在标头中传递,则可以使用二进制读取创建它,如下所示:# cropped is the image as a numpy array# the three attempts below do not work# as microsoft does not recognise the result# as an imageimage_data = cropped.tobytes()image_data = cropped.tobytes("F")image_data = cropped.tobytes("C")# the following method does work but seems # a bit ridiculouscv2.imwrite("temp.png", cropped)with open(path_to_image, 'rb') as f: image_data = f.read()我可以通过使用 opencv imwrite 保存到磁盘,然后像上面一样读取它来以正确的格式获取我的 numpy 数组,但这似乎不是一件明智的事情。我尝试使用 numpy 函数 tobytes("F") 和 tobytes("C") 但 MS 无法将结果识别为有效图像如何使用 numpy 将图像数组转换为与从磁盘读取图像相同的格式?
1 回答

慕后森
TA贡献1802条经验 获得超5个赞
标准图像格式由带有有关图像的元数据和编码以匹配该格式规范的图像数据的标头组成。当您调用tobytes数组时,numpy 只是将图像数据展平并将其编码为未压缩的字节。您使用的软件无法使用此数据,因为没有描述图像编码方式的标题。它是压缩的还是未压缩的?图像是黑白还是彩色?像素是使用 RGB 还是 HUV 编码的?
听起来最好的选择是在将图像数据传递给 Microsoft 之前以标准图像格式写入图像数据。您可以通过使用 BytesIO 来避免使用文件,但基本思想是您已经拥有的。
from io import BytesIO
import PIL
image = PIL.Image.fromarray(cropped, mode="RGB")
with BytesIO() as temp_buffer:
image.save(temp_buffer, format='png')
image_data = temp_buffer.getvalue()
添加回答
举报
0/150
提交
取消