forked from SandroMachado/openalpr-android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainActivity.java
190 lines (164 loc) · 7.83 KB
/
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package com.sandro.openalprsample;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.squareup.picasso.Picasso;
import org.openalpr.OpenALPR;
import org.openalpr.model.Results;
import org.openalpr.model.ResultsError;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE = 100;
private static final int STORAGE=1;
private String ANDROID_DATA_DIR;
private static File destination;
private TextView resultTextView;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ANDROID_DATA_DIR = this.getApplicationInfo().dataDir;
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkPermission();
}
});
resultTextView = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
resultTextView.setText("Press the button below to start a request.");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
final ProgressDialog progress = ProgressDialog.show(this, "Loading", "Parsing result...", true);
final String openAlprConfFile = ANDROID_DATA_DIR + File.separatorChar + "runtime_data" + File.separatorChar + "openalpr.conf";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
// Picasso requires permission.WRITE_EXTERNAL_STORAGE
Picasso.with(MainActivity.this).load(destination).fit().centerCrop().into(imageView);
resultTextView.setText("Processing");
AsyncTask.execute(new Runnable() {
@Override
public void run() {
String result = OpenALPR.Factory.create(MainActivity.this, ANDROID_DATA_DIR).recognizeWithCountryRegionNConfig("us", "", destination.getAbsolutePath(), openAlprConfFile, 10);
Log.d("OPEN ALPR", result);
try {
final Results results = new Gson().fromJson(result, Results.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (results == null || results.getResults() == null || results.getResults().size() == 0) {
Toast.makeText(MainActivity.this, "It was not possible to detect the licence plate.", Toast.LENGTH_LONG).show();
resultTextView.setText("It was not possible to detect the licence plate.");
} else {
resultTextView.setText("Plate: " + results.getResults().get(0).getPlate()
// Trim confidence to two decimal places
+ " Confidence: " + String.format("%.2f", results.getResults().get(0).getConfidence()) + "%"
// Convert processing time to seconds and trim to two decimal places
+ " Processing time: " + String.format("%.2f", ((results.getProcessingTimeMs() / 1000.0) % 60)) + " seconds");
}
}
});
} catch (JsonSyntaxException exception) {
final ResultsError resultsError = new Gson().fromJson(result, ResultsError.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
resultTextView.setText(resultsError.getMsg());
}
});
}
progress.dismiss();
}
});
}
}
private void checkPermission() {
List<String> permissions = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissions.isEmpty()) {
Toast.makeText(this, "Storage access needed to manage the picture.", Toast.LENGTH_LONG).show();
String[] params = permissions.toArray(new String[permissions.size()]);
ActivityCompat.requestPermissions(this, params, STORAGE);
} else { // We already have permissions, so handle as normal
takePicture();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case STORAGE:{
Map<String, Integer> perms = new HashMap<>();
// Initial
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for WRITE_EXTERNAL_STORAGE
Boolean storage = perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (storage) {
// permission was granted, yay!
takePicture();
} else {
// Permission Denied
Toast.makeText(this, "Storage permission is needed to analyse the picture.", Toast.LENGTH_LONG).show();
}
}
default:
break;
}
}
public String dateToString(Date date, String format) {
SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault());
return df.format(date);
}
public void takePicture() {
// Use a folder to store all results
File folder = new File(Environment.getExternalStorageDirectory() + "/OpenALPR/");
if (!folder.exists()) {
folder.mkdir();
}
// Generate the path for the next photo
String name = dateToString(new Date(), "yyyy-MM-dd-hh-mm-ss");
destination = new File(folder, name + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
@Override
protected void onResume() {
super.onResume();
if (destination != null) {// Picasso does not seem to have an issue with a null value, but to be safe
Picasso.with(MainActivity.this).load(destination).fit().centerCrop().into(imageView);
}
}
}