안드로이드에서 Tesnorflow Lite 모델 사용하기

LeeEunJae·2022년 8월 5일
1

Study Kotlin

목록 보기
7/20

📌 실행 결과

📌 Tensorflow 모델 추가하기

프로젝트의 assets 폴더에 학습된 tflite 모델을 추가합니다.

📌 의존성 추가

implementation 'org.tensorflow:tensorflow-lite-task-vision:0.3.1'

📌 이미지에서 객체를 감지하고 출력하는 메소드

private fun runObjectDetection(bitmap: Bitmap) {
        //TODO: Add object detection code here

        // 1. 이미지 객체 만들기
        val image = TensorImage.fromBitmap(bitmap)

        // 2. 검사 프로그램 객체 만들기
        val options = ObjectDetector.ObjectDetectorOptions.builder()
            .setMaxResults(5) // 모델에서 감지해야 하는 최대 객체 수
            .setScoreThreshold(0.5f) // 감지된 객체를 반환하는 객체 감지기의 신뢰도
            .build()

        val detector = ObjectDetector.createFromFileAndOptions(
            this,
            "model.tflite",
            options
        )

        // 3. 검사 프로그램에 피드 이미지
        val results = detector.detect(image) // 검사 프로그램에 이미지 전달
        // 4. 결과 출력 메소드 호출
        debugPrint(results)

        // 입력 이미지에 감지 결과 그리기
        val resultToDisplay = results.map{
            val category = it.categories.first()
            val text = "${category.label}, ${category.score.times(100).toInt()}%"

            DetectionResult(it.boundingBox, text)
        }
        val imgWithResult = drawDetectionResult(bitmap, resultToDisplay)
        runOnUiThread {
            inputImageView.setImageBitmap(imgWithResult)
        }
    }
    
private fun debugPrint(results: List<Detection>){
        for((i, obj) in results.withIndex()){
            val box = obj.boundingBox

            Log.d(TAG, "Detected object : $i")
            Log.d(TAG, "  boundingBox : (${box.left}, ${box.top}) - (${box.right}, ${box.bottom})")

            for((j, category) in obj.categories.withIndex()){
                Log.d(TAG, "    Label $j: ${category.label}")
                val confidence: Int = category.score.times(100).toInt()
                Log.d(TAG, "    Confidence: ${confidence}%")
            }
        }
    }

✅ 응용해볼만한 것

이번에 배운것을 토대로 지난 학기에 인공지능 수업을 들으면서 만들었던 동물 분류 모델을 적용해보는 것도 좋을 것 같다.

👀 참고자료 👀

https://developers.google.com/codelabs/tflite-object-detection-android?hl=ko&%3Bauthuser=1&authuser=1#6

profile
매일 조금씩이라도 성장하자

0개의 댓글