【问题标题】:Python - byte image to NumPy array using OpenCVPython - 使用 OpenCV 将字节图像转换为 NumPy 数组
【发布时间】:2018-09-05 19:05:48
【问题描述】:

我有一个以字节为单位的图像:

print(image_bytes)

b'\xff\xd8\xff\xfe\x00\x10Lavc57.64.101\x00\xff\xdb\x00C\x00\x08\x04\x04\x04\x04\x04\x05\x05\x05\x05\x05\x05\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x07\x07\x07\x08\x08\x08\x07\x07\x07\x06\x06\x07\x07\x08\x08\x08\x08\t\t\t\x08\x08\x08\x08\t\t\n\n\n\x0c\x0c\x0b\x0b\x0e\x0e\x0e\x11\x11\x14\xff\xc4\x01\xa2\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\ ... some other stuff

我可以使用 Pillow 将其转换为 NumPy 数组:

image = numpy.array(Image.open(io.BytesIO(image_bytes))) 

但我不太喜欢使用 Pillow。有没有办法使用清晰的OpenCV,或者直接使用更好的NumPy,或者其他更快的库?

【问题讨论】:

标签: python python-3.x numpy opencv


【解决方案1】:

我创建了一个2x2 JPEG image 来测试它。图像具有白色、红色、绿色和紫色像素。我用cv2.imdecodenumpy.frombuffer

import cv2
import numpy as np

f = open('image.jpg', 'rb')
image_bytes = f.read()  # b'\xff\xd8\xff\xe0\x00\x10...'

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]]]

【讨论】:

  • 在 Keras 中有没有 cv2.imdecode 的替代品?
【解决方案2】:

我在网上搜索了最后我解决了:

NumPy 数组(cv2 图像)- 转换

NumPy 到字节

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'\xff\xd8\xff\xe0\x00\x10...';
img = decodeImage(img_code) #Output: normal array
cv2.imshow('image_deirvlon',img);
print(decoded.shape)

您可以从here获取完整代码

【讨论】:

    猜你喜欢
    • 2016-03-17
    • 2014-12-28
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2013-07-31
    • 2012-08-20
    • 2020-01-24
    • 2018-09-28
    相关资源
    最近更新 更多