问题描述
我正在尝试优化代码.
I'm trying to optimize my code.
首先,我得到一张图像,其类型为字节
First, I get an image, which type is bytes
然后我必须将该映像写入文件系统.
Then I have to write that image to file system.
with open('test2.jpg', 'wb') as f:
f.write(content)
最后我用
from scipy import misc
misc.imread('test2.jpg')
将图像转换为np.array.
which convert image to np.array.
我想跳过将图像写入文件系统的部分,并获取np.array.
I want to skip part where I write image to file system, and get np.array.
PS :我尝试使用np.frombuffer().它对我不起作用,因为两个np.arrays不同.将str转换为numpy.ndarray
P.S.: I tried to use np.frombuffer(). It doesn't work for me, cause two np.arrays are not the same.Convert str to numpy.ndarray
要进行测试,您可以尝试一下自己:
For test you can try yourself:
file = open('test1.jpg', 'rb')
content = file.read()
推荐答案
我在说唱中的第一个答案...
My first answer in rap...
远走高飞
因此,要生成一些类似于您从API获得的合成数据:
So, to generate some synthetic data similar to what you get from the API:
file = open('image.jpg','rb')
content = file.read()
看起来像这样,具有JPEG的所有特征:
That looks like this which has all the hallmarks of a JPEG:
content = b'\xff\xd8\xff\xe0\x00\x10JFIF...
现在为解决方案:
from io import BytesIO
from scipy import misc
numpyArray = misc.imread(BytesIO(content))
这篇关于如何将字节类型的图像转换为numpy.ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!