簡體   English   中英

Python - 使用 OpenCV 將字節圖像轉換為 NumPy 數組

[英]Python - byte image to NumPy array using OpenCV

我有一個以字節為單位的圖像:

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 甚至更好,或者其他一些更快的庫?

我創建了一個2x2 JPEG 圖像來測試這個。 圖像具有白色、紅色、綠色和紫色像素。 我使用了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]]]

我在互聯網上搜索了最后我解決了:

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)

你可以從這里獲得完整的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM