如何在Android中将图像传递给tflite模型

时间:2020-08-03 14:39:49

标签: android computer-vision tensorflow-lite tf-lite

我已经将Yolo模型转换为.tflite以便在android中使用。这就是它在python中的用法-

net = cv2.dnn.readNet("yolov2.weights", "yolov2.cfg")
classes = []
with open("yolov3.txt", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))

cap= cv2.VideoCapture(0)


while True:
    _,frame= cap.read()
    height,width,channel= frame.shape
    blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True, crop=False)
    net.setInput(blob)
    outs = net.forward(output_layers)
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.2:
            # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)
                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

我用netron https://github.com/lutzroeder/netron来可视化模型。输入被描述为名称:输入, 类型:float32 [1,416,416,3], 量化:0≤q≤255, 位置:399 和输出为 名称:output_boxes, 类型:float32 [1,10647,8], 位置:400。

我的问题是关于在an​​droid中使用此模型。我已经在“ Interpreter tflite”中加载了模型,我正在以byte []格式从摄像机获取输入帧。如何将其转换为tflite.run(输入,输出)所需的输入?

1 个答案:

答案 0 :(得分:1)

您需要调整输入图像的大小以与TensorFlow-Lite模型的输入大小相匹配,然后将其转换为RGB格式以提供给模型。

通过使用ImageProcessor支持库中的TensorFlow-Lite,您可以轻松地进行图像大小调整和转换。

ImageProcessor imageProcessor =
        new ImageProcessor.Builder()
            .add(new ResizeWithCropOrPadOp(cropSize, cropSize))
            .add(new ResizeOp(imageSizeX, imageSizeY, ResizeMethod.NEAREST_NEIGHBOR))
            .add(new Rot90Op(numRoration))
            .add(getPreprocessNormalizeOp())
            .build();
return imageProcessor.process(inputImageBuffer);

接下来要与解释器进行推理,您将预处理的图像馈送到TensorFlow-Lite解释器:

tflite.run(inputImageBuffer.getBuffer(), outputProbabilityBuffer.getBuffer().rewind());

请参考this官方示例以获取更多详细信息,此外,您也可以参考this示例。