我在字节中具有图像:
print(image_bytes)
b'xffxd8xffxfex00x10Lavc57.64.101x00xffxdbx00Cx00x08x04x04x04x04x04x05x05x05x05x05x05x06x06x06x06x06x06x06x06x06x06x06x06x06x07x07x07x08x08x08x07x07x07x06x06x07x07x08x08x08x08tttx08x08x08x08ttnnnx0cx0cx0bx0bx0ex0ex0ex11x11x14xffxc4x01xa2x00x00x01x05x01x01x01x01x01x01x00x00x00x00x00x00x00x00x01x02x03x04x05x06x07x08tnx0bx01x00x03x01x01x01x01x01x01x01x01x01x00x00 ... some other stuff
我能够使用Pillow
转换为Numpy阵列:
image = numpy.array(Image.open(io.BytesIO(image_bytes)))
,但我真的不喜欢使用枕头。有没有一种方法可以使用清晰的openCV,或者直接直接使用numpy,或者其他一些更快的库?
我创建了一个2x2 jpeg映像来测试。该图像具有白色,红色,绿色和紫色像素。我使用了cv2.imdecode
和numpy.frombuffer
import cv2
import numpy as np
f = open('image.jpg', 'rb')
image_bytes = f.read() # b'xffxd8xffxe0x00x10...'
decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
print('OpenCV:n', decoded)
# your Pillow code
import io
from PIL import Image
image = np.array(Image.open(io.BytesIO(image_bytes)))
print('PIL:n', image)
这似乎有效,尽管频道顺序为BGR,而不是PIL.Image
中的RGB。您可能会使用一些标志来调整此标志。测试结果:
OpenCV:
[[[255 254 255]
[ 0 0 254]]
[[ 1 255 0]
[254 0 255]]]
PIL:
[[[255 254 255]
[254 0 0]]
[[ 0 255 1]
[255 0 254]]]
我在互联网上进行了搜索,我最终解决了:
numpy阵列(CV2图像( - 转换
numpy to byte
和
bytes to numpy
:。
#data = cv2 image array
def encodeImage(data):
#resize inserted image
data= cv2.resize(data, (480,270))
# run a color convert:
data= cv2.cvtColor(data, cv2.COLOR_BGR2RGB)
return bytes(data) #encode Numpay to Bytes string
def decodeImage(data):
#Gives us 1d array
decoded = np.fromstring(data, dtype=np.uint8)
#We have to convert it into (270, 480,3) in order to see as an image
decoded = decoded.reshape((270, 480,3))
return decoded;
# Load an color image
image= cv2.imread('messi5.jpg',1)
img_code = encodeImage(image) #Output: b'xffxd8xffxe0x00x10...';
img = decodeImage(img_code) #Output: normal array
cv2.imshow('image_deirvlon',img);
print(decoded.shape)
您可以从这里获得完整的代码