Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用自定义模型时如何解决tensorflow形状问题?_Android_Tensorflow_Tensorflow Lite - Fatal编程技术网

Android 使用自定义模型时如何解决tensorflow形状问题?

Android 使用自定义模型时如何解决tensorflow形状问题?,android,tensorflow,tensorflow-lite,Android,Tensorflow,Tensorflow Lite,我一直在尝试将一个座椅安全带python代码转换为android应用程序,如果有打开或关闭的座椅安全带检测,该代码将执行TensorFlow检测。我正在尝试使用tensorflow lite在Android中移植同样的功能。到目前为止,模型实际上检测到了图像,但形状似乎是个问题,因为我使用的是自定义模型。python文件中的模型如下所示。它可以工作并且正在检测是否有安全带的图像 def predict(image): # Define image size, this is fixed f

我一直在尝试将一个座椅安全带python代码转换为android应用程序,如果有打开或关闭的座椅安全带检测,该代码将执行TensorFlow检测。我正在尝试使用tensorflow lite在Android中移植同样的功能。到目前为止,模型实际上检测到了图像,但形状似乎是个问题,因为我使用的是自定义模型。python文件中的模型如下所示。它可以工作并且正在检测是否有安全带的图像

def predict(image):
   # Define image size, this is fixed for the current model
   width = 100
   height = 120
   
   # Preprocess image
   # resize
   img = cv2.resize(np.copy(image),(width,height))
        
   # Convert to gray scale
   gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
   gray = gray[:,:,np.newaxis] 
      
   # Convert image data into float32
   gray = gray.astype(‘float32’)
        
   # Normalize the data to (0,1) 
   gray = np.divide(gray, 255.) 
      
   # Expand to match place holder of shape [self.batch_size, height, width, channels]
   input_image = np.expand_dims(gray, axis=0)
   
   # Path to the Seatbelt detection lite model
   model = ‘./models/lite_model.tflite’
   “”" predict using tflite model”“”
   interpreter = tf.lite.Interpreter(model_path=model)
         
   interpreter.allocate_tensors()
   input_tensor = interpreter.get_input_details()
   output_tensor = interpreter.get_output_details()
         
   input_shape = input_tensor[0][‘shape’]
     
   interpreter.set_tensor(input_tensor[0][‘index’], input_image)
   interpreter.invoke()
         
   # Make prediction
   output = interpreter.get_tensor(output_tensor[0][‘index’])
   predictions = softmax(output[0])
   predicted_label = np.argmax(predictions)
   confidence = round(np.max(predictions),2)
   
   if predicted_label == 1:
      predicted_class = “Seatbelt on”
      
   else:
        predicted_class = “No seatbelt”
   “”"
   # prediction using tensorflow session
   tf_config = tf.ConfigProto()
   tf_config.gpu_options.allow_growth = True
         
   with tf.Session(config=tf_config) as sess:
         
       predicted_label = tf.argmax(predictions, 1).eval()
       #label = dict[str(predicted_labels[0])]
       pred = predictions.eval()
       
       confidence = round(np.max(pred),2)
        
       if predicted_label[0] == 1:
        predicted_class = “Seatbelt on”
      
       else:
        predicted_class = “No seatbelt”
   “”"   
   return predicted_class, confidence          
 
在我的活动课上,我正在做一个tensorflow检测,如下所示。。应用程序抛出异常maskDetectorTFLite!!。识别此行中的图像(detectedFace.bitmap)

fun doTensorFlowDetection(detectedFace:BoundingBox){
试一试{
maskDetectorTFLite!!.recognizeImage(detectedFace.bitmap)
maskGrayResults=maskDetectorTFLite!!.getGrayOutput()
}catch(e:java.lang.IllegalArgumentException){
e、 printStackTrace()
//showSnackbar(例如message.toString())
maskGrayResults=2
}
如果(maskGrayResults==0){
imageReceivedEvent.SEAT BELT=BWConstants.SEAT BELT\u ENUM.SEAT\u BELT\u OFF
BWLog.d(标签“安全带关闭”)
}else if(maskGrayResults==2){
BWLog.d(标签“未知安全带”)
imageReceivedEvent.SEAT BELT=BWConstants.SEAT BELT\u ENUM.SEAT\u BELT\u未检测到
}否则{
imageReceivedEvent.SEAT BELT=BWConstants.SEAT BELT\u ENUM.SEAT\u BELT\u ON
BWLog.d(标签“安全带打开”)
}
}
识别图像是它抛出异常的位置


抽象类MaskDetectorTFLite(
上下文:上下文,
设备:TensorFlowAndroid。设备?,
numThreads:Int
):MaskDetector(){
private val tfliteOptions=解释器.Options()
私有模型:ByteArray?
受保护的var-tflite:解释器?
私有变量gpuDelegate:gpuDelegate?=null
//-------------------------------------公共方法----------------------------------------
趣味识别图像(位图:位图?){
位图?.let{展平图像(it)}
运行推断()
}
打开getGrayOutput():Int{
val temp:MutableList=ArrayList()
对于(预测[0]中的f){
温度添加(f)
}
//BWLog.d(“掩码输出:”,Arrays.toString(temp.toTypedArray())//显示灰色输出值
//System.out.println(“掩码输出:+Arrays.toString(temp.toArray());//显示灰色输出值
返回索引的温度(集合的最大值(温度))
}
有趣的结尾(){
if(tflite!=null){
tflite!!.close()
tflite=null
}
if(gpuDelegate!=null){
gpuDelegate!!.close()
gpuDelegate=null
}
tfliteModel=null
}
//
//-------------------------------------私有方法----------------------------------------
@抛出(IOException::类)
私有趣味加载模型文件(上下文:上下文):ByteArray{
//todo在使用其他模型名称时更改此选项
val fileName=bwstants.TENSOR_安全带_文件
val streams=context.openFileInput(文件名)
//val assetFile=context.assets.open(文件名)
返回streams.readBytes()
//返回文件(context.filesDir,文件名)
//val fileDescriptor=context.assets.openFd(modelPath!!)
val inputStream=流
//FileInputStream(fileDescriptor.fileDescriptor)
val fileChannel=inputStream.channel
val STARTOFSET=0升
val declaredLength=inputStream.channel.size()
//返回fileChannel.map(
//FileChannel.MapMode.READ_只读,
//startOffset,
//申报长度
//        )
}
//-------------------------------抽象方法----------------------------------------
抽象val模型路径:字符串?
抽象推理()
伴星{
@抛出(IOException::类)
趣味创造(
上下文:上下文?,
型号:TensorFlowAndroid。型号?,
设备:TensorFlowAndroid。设备?,
numThreads:Int
):MaskDetectorTFLite{
返回MaskDetectorTFLiteFloat(上下文、设备、numThreads)
}
}
//---------------------------------------建造师------------------------------------------
初始化{
tfliteModel=loadModelFile(上下文)
何时(设备){
TensorFlowAndroid.Device.NNAPI、TensorFlowAndroid.Device.GPU、TensorFlowAndroid.Device.CPU->println(
“使用CPU”
)
}
val buffer=ByteBuffer.allocateDirect(tfliteModel!!.size).order(ByteOrder.nativeOrder())
buffer.put(tfliteModel)
tfliteOptions.setNumThreads(numThreads)
tflite=解释器(缓冲区、tflite选项)
}
}
为了使图像平坦,我正在做这样的事情

抽象类MaskDetector:TensorFlowAndroid{
var flattedImage=FloatArray(IN_IMAGE_H*IN_IMAGE_W*DIM_PIXEL_SIZE)
var值=
阵列(在图像中高*在图像中低)
var预测=
数组(1){FloatArray(3)}
受保护的图像(位图:位图){
位图.getPixels(
intValues,
0,
位图宽度,
0,
0,
位图宽度,
位图高度
)
var指数=0
用于(i在0中直到在图像中){
用于(0中的j,直到图像中的W){
val pixelValue=intValues[i*IN_IMAGE_W+j]
展平图像[索引++]=(像素值shr 0和0xFF)/255.0f
}
}
}
伴星{
保护常数值阈值=0.5f
val IN_IMAGE\u W:Int=遮罩大小\u宽度
val IN_IMAGE_H:Int=遮罩大小调整高度
val DIM_像素_大小=1
val阈值=0.15f
}
}