Skip to content

Commit 49631fe

Browse files
authored
Merge pull request #16 from vens8/native-neural-networks
Native neural networks
2 parents 5689e18 + df13829 commit 49631fe

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+1229
-10
lines changed

Assignment2/.idea/misc.xml

-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Assignment3/TensorFlowCNN/.gitignore

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
*.iml
2+
.gradle
3+
/local.properties
4+
/.idea/caches
5+
/.idea/libraries
6+
/.idea/modules.xml
7+
/.idea/workspace.xml
8+
/.idea/navEditor.xml
9+
/.idea/assetWizardSettings.xml
10+
.DS_Store
11+
/build
12+
/captures
13+
.externalNativeBuild
14+
.cxx
15+
local.properties

Assignment3/TensorFlowCNN/.idea/.gitignore

+3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/build
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
plugins {
2+
alias(libs.plugins.androidApplication)
3+
alias(libs.plugins.jetbrainsKotlinAndroid)
4+
}
5+
6+
android {
7+
namespace = "com.example.tensorflowcnn"
8+
compileSdk = 34
9+
10+
defaultConfig {
11+
applicationId = "com.example.tensorflowcnn"
12+
minSdk = 24
13+
targetSdk = 34
14+
versionCode = 1
15+
versionName = "1.0"
16+
17+
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
18+
vectorDrawables {
19+
useSupportLibrary = true
20+
}
21+
}
22+
23+
buildTypes {
24+
release {
25+
isMinifyEnabled = false
26+
proguardFiles(
27+
getDefaultProguardFile("proguard-android-optimize.txt"),
28+
"proguard-rules.pro"
29+
)
30+
}
31+
}
32+
compileOptions {
33+
sourceCompatibility = JavaVersion.VERSION_1_8
34+
targetCompatibility = JavaVersion.VERSION_1_8
35+
}
36+
kotlinOptions {
37+
jvmTarget = "1.8"
38+
}
39+
buildFeatures {
40+
compose = true
41+
mlModelBinding = true
42+
}
43+
composeOptions {
44+
kotlinCompilerExtensionVersion = "1.5.1"
45+
}
46+
packaging {
47+
resources {
48+
excludes += "/META-INF/{AL2.0,LGPL2.1}"
49+
}
50+
}
51+
}
52+
53+
dependencies {
54+
55+
implementation(libs.androidx.core.ktx)
56+
implementation(libs.androidx.lifecycle.runtime.ktx)
57+
implementation(libs.androidx.activity.compose)
58+
implementation(platform(libs.androidx.compose.bom))
59+
implementation(libs.androidx.ui)
60+
implementation(libs.androidx.ui.graphics)
61+
implementation(libs.androidx.ui.tooling.preview)
62+
implementation(libs.androidx.material3)
63+
implementation(libs.tensorflow.lite.support)
64+
implementation(libs.tensorflow.lite.metadata)
65+
implementation(libs.tensorflow.lite.gpu)
66+
testImplementation(libs.junit)
67+
androidTestImplementation(libs.androidx.junit)
68+
androidTestImplementation(libs.androidx.espresso.core)
69+
androidTestImplementation(platform(libs.androidx.compose.bom))
70+
androidTestImplementation(libs.androidx.ui.test.junit4)
71+
debugImplementation(libs.androidx.ui.tooling)
72+
debugImplementation(libs.androidx.ui.test.manifest)
73+
implementation(libs.androidx.core.splashscreen)
74+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Add project specific ProGuard rules here.
2+
# You can control the set of applied configuration files using the
3+
# proguardFiles setting in build.gradle.
4+
#
5+
# For more details, see
6+
# http://developer.android.com/guide/developing/tools/proguard.html
7+
8+
# If your project uses WebView with JS, uncomment the following
9+
# and specify the fully qualified class name to the JavaScript interface
10+
# class:
11+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12+
# public *;
13+
#}
14+
15+
# Uncomment this to preserve the line number information for
16+
# debugging stack traces.
17+
#-keepattributes SourceFile,LineNumberTable
18+
19+
# If you keep the line number information, uncomment this to
20+
# hide the original source file name.
21+
#-renamesourcefileattribute SourceFile
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.example.tensorflowcnn
2+
3+
import androidx.test.platform.app.InstrumentationRegistry
4+
import androidx.test.ext.junit.runners.AndroidJUnit4
5+
6+
import org.junit.Test
7+
import org.junit.runner.RunWith
8+
9+
import org.junit.Assert.*
10+
11+
/**
12+
* Instrumented test, which will execute on an Android device.
13+
*
14+
* See [testing documentation](http://d.android.com/tools/testing).
15+
*/
16+
@RunWith(AndroidJUnit4::class)
17+
class ExampleInstrumentedTest {
18+
@Test
19+
fun useAppContext() {
20+
// Context of the app under test.
21+
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22+
assertEquals("com.example.tensorflowcnn", appContext.packageName)
23+
}
24+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3+
xmlns:tools="http://schemas.android.com/tools">
4+
5+
<application
6+
android:allowBackup="true"
7+
android:dataExtractionRules="@xml/data_extraction_rules"
8+
android:fullBackupContent="@xml/backup_rules"
9+
android:icon="@mipmap/ic_launcher"
10+
android:label="@string/app_name"
11+
android:roundIcon="@mipmap/ic_launcher_round"
12+
android:supportsRtl="true"
13+
android:theme="@style/Theme.MySplashScreen"
14+
tools:targetApi="31">
15+
<activity
16+
android:name=".MainActivity"
17+
android:exported="true"
18+
android:label="@string/app_name"
19+
android:theme="@style/Theme.MySplashScreen">
20+
<intent-filter>
21+
<action android:name="android.intent.action.MAIN" />
22+
23+
<category android:name="android.intent.category.LAUNCHER" />
24+
</intent-filter>
25+
</activity>
26+
</application>
27+
28+
</manifest>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
package com.example.tensorflowcnn
2+
3+
import android.content.Context
4+
import android.graphics.Bitmap
5+
import android.graphics.ImageDecoder
6+
import android.net.Uri
7+
import android.os.Build
8+
import android.provider.MediaStore
9+
import androidx.activity.compose.rememberLauncherForActivityResult
10+
import androidx.activity.result.contract.ActivityResultContracts
11+
import androidx.compose.foundation.Image
12+
import androidx.compose.foundation.layout.Arrangement
13+
import androidx.compose.foundation.layout.Box
14+
import androidx.compose.foundation.layout.Column
15+
import androidx.compose.foundation.layout.Row
16+
import androidx.compose.foundation.layout.Spacer
17+
import androidx.compose.foundation.layout.fillMaxSize
18+
import androidx.compose.foundation.layout.fillMaxWidth
19+
import androidx.compose.foundation.layout.padding
20+
import androidx.compose.foundation.layout.size
21+
import androidx.compose.foundation.layout.width
22+
import androidx.compose.foundation.rememberScrollState
23+
import androidx.compose.foundation.shape.RoundedCornerShape
24+
import androidx.compose.foundation.verticalScroll
25+
import androidx.compose.material3.Button
26+
import androidx.compose.material3.ButtonDefaults
27+
import androidx.compose.material3.CardDefaults
28+
import androidx.compose.material3.ExperimentalMaterial3Api
29+
import androidx.compose.material3.Icon
30+
import androidx.compose.material3.MaterialTheme
31+
import androidx.compose.material3.OutlinedCard
32+
import androidx.compose.material3.Scaffold
33+
import androidx.compose.material3.Text
34+
import androidx.compose.material3.TopAppBar
35+
import androidx.compose.material3.TopAppBarDefaults
36+
import androidx.compose.runtime.Composable
37+
import androidx.compose.runtime.getValue
38+
import androidx.compose.runtime.mutableStateOf
39+
import androidx.compose.runtime.remember
40+
import androidx.compose.runtime.setValue
41+
import androidx.compose.ui.Alignment
42+
import androidx.compose.ui.Modifier
43+
import androidx.compose.ui.graphics.asImageBitmap
44+
import androidx.compose.ui.platform.LocalContext
45+
import androidx.compose.ui.res.painterResource
46+
import androidx.compose.ui.text.style.TextAlign
47+
import androidx.compose.ui.unit.dp
48+
import com.example.tensorflowcnn.tflite.ImageClassifier
49+
50+
@OptIn(ExperimentalMaterial3Api::class)
51+
@Composable
52+
fun ImagePicker() {
53+
var imageUris by remember { mutableStateOf<List<Uri>?>(null) }
54+
val context = LocalContext.current
55+
val launcher = rememberLauncherForActivityResult(
56+
contract = ActivityResultContracts.GetMultipleContents(),
57+
onResult = { uris -> imageUris = uris }
58+
)
59+
60+
Scaffold(
61+
modifier = Modifier.fillMaxSize(),
62+
topBar = {
63+
TopAppBar(
64+
title = { Text("Image Classifier") },
65+
colors = TopAppBarDefaults.smallTopAppBarColors(
66+
containerColor = MaterialTheme.colorScheme.primaryContainer,
67+
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
68+
)
69+
)
70+
},
71+
content = { innerPadding ->
72+
Column(
73+
Modifier
74+
.fillMaxSize()
75+
.padding(innerPadding)
76+
.padding(horizontal = 16.dp)
77+
) {
78+
Box(
79+
Modifier
80+
.weight(1f)
81+
.fillMaxWidth()
82+
.verticalScroll(rememberScrollState()),
83+
contentAlignment = Alignment.Center
84+
) {
85+
if (imageUris.isNullOrEmpty()) {
86+
// Placeholder UI when no images are selected
87+
PlaceholderContent()
88+
} else {
89+
// Display images if available
90+
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
91+
imageUris!!.chunked(2).forEach { rowUris ->
92+
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
93+
rowUris.forEach { uri ->
94+
ImageCard(context, uri)
95+
}
96+
}
97+
}
98+
}
99+
}
100+
}
101+
Button(
102+
onClick = { launcher.launch("image/*") },
103+
modifier = Modifier
104+
.fillMaxWidth()
105+
.padding(16.dp),
106+
colors = ButtonDefaults.buttonColors(
107+
containerColor = MaterialTheme.colorScheme.primaryContainer,
108+
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
109+
)
110+
) {
111+
Text(text = "Pick images")
112+
}
113+
}
114+
}
115+
)
116+
}
117+
118+
@Composable
119+
fun ImageCard(context: Context, uri: Uri) {
120+
val bitmap = loadImage(context, uri)
121+
bitmap?.let {
122+
OutlinedCard(
123+
modifier = Modifier
124+
.padding(8.dp)
125+
.width(175.dp),
126+
shape = RoundedCornerShape(16.dp),
127+
elevation = CardDefaults.elevatedCardElevation(
128+
defaultElevation = 4.dp
129+
)
130+
) {
131+
Column(
132+
Modifier.padding(16.dp),
133+
horizontalAlignment = Alignment.CenterHorizontally
134+
) {
135+
Image(
136+
bitmap = it.asImageBitmap(),
137+
contentDescription = "Selected image",
138+
modifier = Modifier.size(150.dp)
139+
)
140+
Spacer(modifier = Modifier.padding(4.dp))
141+
val resizedBitmap = resizeBitmap(it, ImageClassifier.imageSize, ImageClassifier.imageSize)
142+
ImageClassifier.Classify(resizedBitmap) { classification ->
143+
Text(
144+
text = classification,
145+
style = MaterialTheme.typography.bodyMedium,
146+
color = MaterialTheme.colorScheme.primary
147+
)
148+
}
149+
}
150+
}
151+
}
152+
}
153+
154+
// Auxiliary function to load an image
155+
fun loadImage(context: Context, uri: Uri): Bitmap? {
156+
return if (Build.VERSION.SDK_INT < 28) {
157+
MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
158+
} else {
159+
val source = ImageDecoder.createSource(context.contentResolver, uri)
160+
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
161+
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
162+
decoder.isMutableRequired = true
163+
}
164+
}
165+
}
166+
167+
fun resizeBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
168+
return Bitmap.createScaledBitmap(source, width, height, true)
169+
}
170+
171+
@Composable
172+
fun PlaceholderContent() {
173+
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
174+
Column(horizontalAlignment = Alignment.CenterHorizontally) {
175+
Icon(painter = painterResource(id = R.drawable.placeholder), contentDescription = "Placeholder", modifier = Modifier.size(120.dp))
176+
Text("No images selected. Click the button below to choose images.", textAlign = TextAlign.Center)
177+
}
178+
}
179+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.example.tensorflowcnn
2+
3+
import android.os.Bundle
4+
import androidx.activity.ComponentActivity
5+
import androidx.activity.compose.setContent
6+
import androidx.compose.foundation.layout.fillMaxSize
7+
import androidx.compose.material3.MaterialTheme
8+
import androidx.compose.material3.Surface
9+
import androidx.compose.material3.Text
10+
import androidx.compose.runtime.Composable
11+
import androidx.compose.ui.Modifier
12+
import androidx.compose.ui.tooling.preview.Preview
13+
import com.example.tensorflowcnn.ui.theme.TensorflowcnnTheme
14+
15+
class MainActivity : ComponentActivity() {
16+
override fun onCreate(savedInstanceState: Bundle?) {
17+
super.onCreate(savedInstanceState)
18+
setContent {
19+
TensorflowcnnTheme {
20+
// A surface container using the 'background' color from the theme
21+
Surface(
22+
modifier = Modifier.fillMaxSize(),
23+
color = MaterialTheme.colorScheme.background
24+
) {
25+
ImagePicker()
26+
}
27+
}
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)