Current location - Recipe Complete Network - Healthy recipes - Raspberry Pi using PaddleX to do object classification
Raspberry Pi using PaddleX to do object classification
1. First run the code using Baidu AI. Refer to the /aistudio/projectdetail/2160041 link URL to get the model. But the model obtained from paddlex run can't be run directly on Raspberry Pi. So do the second step.

2. Convert the model to a model supported by paddle-lite. Run it in Baidu studio, in the code from the previous step

paddle_lite_opt --model_fie=your model pathway

--param_file=your weight pathway

--valid_targets=arm

--optimize_ out_type=naive_buffer

--optimize_out=The route and name of the output nb model you want

3. Execute the following categorization code to modify the parameters that belong to you

from paddlelite.lite import *

import cv2

import numpy as np

import sys

import time

from PIL import Image

from PIL import ImageFont

from PIL import ImageDraw

# load model

def create_predictor(model_dir):

config = MobileConfig()

config.set_model_from_file( model_dir)

predictor = create_paddle_predictor(config)

return predictor

#Image normalization

def process_img(image, input_ image_size):

origin = image

img = origin.resize(input_image_size, Image.BILINEAR)

resized_img = img.copy()

if img. mode ! = 'RGB':

img = img.convert('RGB')

img = np.array(img).astype('float32').transpose((2, 0, 1)) # HWC to CHW

img -= 127.5

img *= 0.007843

img = img[np.newaxis, :]

return origin,img

# predict

def predict(image, predictor, input_image_size):

# Input data processing

input_tensor = predictor.get_input(0)

input_tensor.resize([1, 3, input_image_size[0], input_image_size[1]])

< p> image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA))

origin, img = process_img(image, input_image_size)

image_ data = np.array(img).flatten().tolist()

input_tensor.set_float_data(image_data)

#Execute the prediction

predictor.run()

#Get the output< /p>

output_tensor = predictor.get_output(0)

print("output_tensor.float_data()[:] : ", output_tensor.float_data()[:])

res = output_tensor.float_data()[:]

return res

# Show results

def post_res(label_dict, res):

print(max(res))

target_ index = res.index(max(res))

print("The result is:" + " " + label_dict[target_index])

if __name__ == '__main__':

# Initial definitions

label_ dict = {0: "metal", 1: "paper", 2: "plastic", 3: "glass"}

image = ". /test_pic/images_orginal/glass/glass300.jpg"

model_dir = ". /trained_model/ResNet50_trash_x86_model.nb"

image_size = (224, 224)

# Initialize

predictor = create_predictor(model_dir)

< p> # Read in the image

image = cv2.imread(image)

# Predict

res = predict(image, predictor, image_size)

# Show results

post_res(label_ dict, res)

cv2.imshow("image", image)

cv2.waitKey()