当前位置:首页 > 行业动态 > 正文

安卓图像识别源码例子

安卓图像识别可基于CameraX采集图像,结合TensorFlow Lite加载模型推理,配置权限后实现实时识别并显示

环境准备

  1. 开发工具:Android Studio(推荐4.1+版本)
  2. 依赖库:ML Kit(Firebase)图像识别
  3. 模型准备:使用预训练模型(如TensorFlow Lite或ONNX格式)

项目结构

文件/目录 说明
app/src/main/java/com/example/imagerecognition 主代码目录
app/src/main/res/layout/activity_main.xml 布局文件
app/src/main/ml 存放模型文件(如model.tflite
build.gradle 依赖配置

核心代码实现

配置依赖(build.gradle

dependencies {
    implementation 'com.google.mlkit:image-labeling:17.0.0' // ML Kit图像标注
    implementation 'com.google.android.material:material:1.6.1' // UI组件
}

布局文件(activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="16dp">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_foreground" />
    <Button
        android:id="@+id/btn_select"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择图片" />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="识别结果"
        android:textSize="18sp"
        android:paddingTop="16dp" />
</LinearLayout>

主逻辑代码(MainActivity.kt

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.labeling.ImageLabeling
import com.google.mlkit.vision.labeling.ImageLabeler
import java.io.IOException
class MainActivity : BaseActivity() {
    private lateinit var imageView: ImageView
    private lateinit var tvResult: TextView
    private val imageLabeler: ImageLabeler by lazy { ImageLabeling.getClient() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        imageView = findViewById(R.id.imageView)
        tvResult = findViewById(R.id.tv_result)
        findViewById<Button>(R.id.btn_select).setOnClickListener { selectImage() }
    }
    // 选择图片
    private fun selectImage() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_IMAGE_PICK)
    }
    // 处理选中的图片
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK) {
            val uri: Uri? = data?.data
            uri?.let { loadImageAndAnalyze(it) }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }
    // 加载图片并分析
    private fun loadImageAndAnalyze(uri: Uri) {
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
            imageView.setImageBitmap(bitmap)
            analyzeImage(bitmap)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    // 图像识别核心逻辑
    private fun analyzeImage(bitmap: Bitmap) {
        val image = InputImage.fromBitmap(bitmap, 0)
        imageLabeler.process(image)
            .addOnSuccessListener { labels ->
                val result = labels.map { it.text + ": " + it.confidence }.joinToString(", ")
                tvResult.text = result
            }
            .addOnFailureListener { e ->
                tvResult.text = "识别失败: ${e.message}"
            }
    }
    companion object {
        private const val REQUEST_IMAGE_PICK = 1001
    }
}

权限配置(AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
    ...>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

测试步骤

  1. 运行应用,点击“选择图片”按钮。
  2. 从相册选择一张图片(建议包含明确物体,如狗、猫、水果等)。
  3. 识别结果会显示在下方的TextView中。

常见问题与解答

问题1:模型加载失败或识别不准确?

  • 原因:可能是网络问题或模型不适配。
  • 解决方案
    • 检查ML Kit依赖版本是否最新。
    • 确保图片清晰度足够(建议分辨率≥200×200)。
    • 尝试更换预训练模型(如改用ImageLabeling.getClient(options)指定自定义模型)。

问题2:应用崩溃提示“未获取存储权限”?

  • 原因:Android 6.0+需要动态申请权限。
  • 解决方案
    // 在`onCreate`中添加权限请求逻辑
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_STORAGE_PERMISSION)
    }
0