【发布时间】:2019-07-31 02:28:24
【问题描述】:
我阅读了多个代码实验室,其中 Google 将属于一个类别的图像分类。如果我需要使用 2 个或更多类怎么办。例如,如果我想对图像中是否包含水果或蔬菜进行分类,然后分类它是哪种类型的水果或蔬菜。
【问题讨论】:
我阅读了多个代码实验室,其中 Google 将属于一个类别的图像分类。如果我需要使用 2 个或更多类怎么办。例如,如果我想对图像中是否包含水果或蔬菜进行分类,然后分类它是哪种类型的水果或蔬菜。
【问题讨论】:
您可以使用 TensorFlow(特别是使用 Keras)轻松训练卷积神经网络 (CNN)。互联网上有大量的例子。见here 和here。
接下来,我们使用tf.lite.TFLiteConverter将Keras保存的模型(.h5文件)转换为.tflite文件,
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_keras_model_file("keras_model.h5")
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
见here。
现在,在 Android 中,我们获取 Bitmap 图像并将其转换为 float[][][][],
private float[][][][] convertImageToFloatArray ( Bitmap image ) {
float[][][][] imageArray = new float[1][modelInputDim][modelInputDim][1] ;
for ( int x = 0 ; x < modelInputDim ; x ++ ) {
for ( int y = 0 ; y < modelInputDim ; y ++ ) {
float R = ( float )Color.red( image.getPixel( x , y ) );
float G = ( float )Color.green( image.getPixel( x , y ) );
float B = ( float )Color.blue( image.getPixel( x , y ) );
double grayscalePixel = (( 0.3 * R ) + ( 0.59 * G ) + ( 0.11 * B )) / 255;
imageArray[0][x][y][0] = (float)grayscalePixel ;
}
}
return imageArray ;
}
其中modelInputDim 是模型的图像输入大小。上面的sn-p将RGB图像转换为灰度图像。
现在,我们执行最终推理,
private int modelInputDim = 28 ;
private int outputDim = 3 ;
private float[] performInference(Bitmap frame , RectF cropImageRectF ) {
Bitmap croppedBitmap = getCroppedBitmap( frame , cropImageRectF ) ;
Bitmap croppedFrame = resizeBitmap( croppedBitmap );
float[][][][] imageArray = convertImageToFloatArray( croppedFrame ) ;
float[][] outputArray = new float[1][outputDim] ;
interpreter.run( imageArray , outputArray ) ;
return outputArray[0] ;
}
我准备了一系列使用 Android 中的 TFLite 模型的 Android 应用程序。见here。
【讨论】: