如何使用Fastai通过变换直接推断图像?

时间:2019-09-08 23:13:25

标签: python deep-learning fast-ai

我是Fastai的新手,我正在尝试改编以前的model。仅在文件位于磁盘上时,我才能够加载模型并使用推理。由于我正在尝试将文件处理为视频流,因此我将保存每个文件并一次处理一个文件。

import cv2, imageio 
from fastai.vision import *

# ... load the model here

stream = cv2.VideoCapture('Die.Hard.1988.mkv')

while True:
    _, frame = stream.read()

    with tempfile.NamedTemporaryFile(suffix='.jpg') as FOUT:
        imageio.imwrite(FOUT.name, frame)
        FOUT.flush()

        x = open_image(FOUT.name)
        preds_num = learn.predict(x)[2].numpy()

这似乎可行,但将映像保存到磁盘似乎浪费。该库似乎使用了一些转换,这意味着我不能直接将图像推送到“学习者”。加载方式如下:

from fastai.vision import *

f_model = "shot-type-classifier"
path = "shot_type_classifier/"

data = ImageDataBunch.from_folder(
    path,
    "train",
    "valid",
    size=(375, 666),
    ds_tfms=get_tfms(),
    bs=1,
    resize_method=ResizeMethod.SQUISH,
    num_workers=0,
).normalize(imagenet_stats)

learn = cnn_learner(data, models.resnet50, metrics=[accuracy], pretrained=True)
learn = learn.to_fp16()
learn.load(f_model)

似乎在here定义了转换的地方。我真的很想直接将图像传递到预处理器,然后传递给模型,而不必将其保存到磁盘。有没有办法使用fastai做到这一点?

1 个答案:

答案 0 :(得分:1)

尝试将帧转换为枕头图像,然后仅使用pil2tensor:

from PIL import Image as PImage
from fastai.vision import *

frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
pil_im = PImage.fromarray(frame) 
x = pil2tensor(pil_im ,np.float32)
preds_num = learn.predict(Image(x))[2].numpy()