[英]Python conversion of PIL image to numpy array very slow
我正在評估開放 cv 視頻幀上的 Tensorflow 模型。 我需要將傳入的 PIL 圖像重塑為重塑的 numpy 數組,以便我可以對其進行推理。 但是我看到在我的筆記本電腦上將 PIL 圖像轉換為 numpy 數組大約需要 900 多毫秒,內存為 16 GiB 和 2.6 GHz Intel Core i7 處理器。 我需要將其縮短到幾毫秒,以便我可以在我的相機上每秒處理多個幀。
誰能建議如何使以下方法運行得更快?
def load_image_into_numpy_array(pil_image):
(im_width, im_height) = pil_image.size
data = pil_image.getdata()
data_array = np.array(data)
return data_array.reshape((im_height, im_width, 3)).astype(np.uint8)
在進一步的檢測中,我意識到np.array(data)
占用了大部分時間......接近 900+ 毫秒。 所以將圖像數據轉換為 numpy 數組才是真正的罪魁禍首。
您可以讓 numpy 處理轉換而不是重塑自己。
def pil_image_to_numpy_array(pil_image):
return np.asarray(pil_image)
您正在將圖像轉換為(高度、寬度、通道)格式。 這是對 PIL 圖像執行的默認轉換 numpy.asarray 函數,因此不需要顯式整形。
非常感謝!! 它的工作速度非常快!
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: a file path (this can be local or on colossus)
Returns:
uint8 numpy array with shape (img_height, img_width, 3)
"""
img_data = tf.io.gfile.GFile(path, 'rb').read()
image = Image.open(BytesIO(img_data))
return np.array(image)
帶有 (3684, 4912, 3) 的圖像需要 0.3~0.4 秒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.