Selasa, 05 November 2019

CONSOLE DEVELOPER GOOGLE COM

https://console.developers.google.com/apis/dashboard?project=trusty-gradient-251202&authuser=0

Configure a Google API Console project


To configure a Google API Console project, click the button below, and specify your app's package name when prompted. You will also need to provide the SHA-1 hash of your signing certificate. See Authenticating Your Client for information.
https://developers.google.com/identity/sign-in/android/start-integrating






Didapat hasil sbb:

{"web":{"client_id":"61032311926-3k27msvu52bpc3irqthh0q8n8eu1745j.apps.googleusercontent.com","project_id":"trusty-gradient-251202","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"neYcHO9lMtpN7qy1udZSzwPW"}}

Sumber2 Android Clarified:
https://androidclarified.com/category/android-examples/


Praktik:
https://androidclarified.com/google-signin-android-example/












Jumat, 20 September 2019

JSON Parsing 0

<?php

$respon = array();
$respon["sukses"] = 0;
$respon["pesan"] = "0 record";
echo json_encode($respon);

?>

<?php
$record = array();
            $record["kode_mahasiswa"] = "Kode 1";
    $record["nama"] = "Nama 1";

            $respon["sukses"] = 1;
            $respon["record"] = array();

            array_push($respon["record"], $record);
            $respon["pesan"] = "$jum record";
    echo json_encode($respon);
?>

++++++++++++++++

package com.example.pelayanananggotakspsi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

String getIP() {
return "http://192.168.1.11/Siswa/distrokids/";
}

public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

return jObj;
}
}


+++++++++++++++++++++++++++


package com.example.pelayanananggotakspsi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Detail_anggota extends Activity {
String ip="";
String kode_anggota;
String kode_anggota0="";
EditText txtkode_anggota;
EditText txtnama_anggota;
EditText txtnik;
EditText txttgl_lahir;
EditText txtjenis_kelamin;
EditText txtdepartemen;
EditText txttelepon;
EditText txtemail;
EditText txtalamat;
EditText txtusername;
EditText txtpassword;
EditText txtgambar;
EditText txtketerangan;
EditText txtstatus;
Button btnProses;
Button btnHapus;

private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

private static final String TAG_SUKSES = "sukses";
private static final String TAG_record = "record";
private static final String TAG_nama_anggota = "nama_anggota";
private static final String TAG_nik = "nik";
private static final String TAG_tgl_lahir= "tgl_lahir";
private static final String TAG_jenis_kelamin = "jenis_kelamin";
private static final String TAG_departemen = "departemen";
private static final String TAG_alamat = "alamat";
private static final String TAG_username = "username";
private static final String TAG_password = "password";
private static final String TAG_gambar = "gambar";
private static final String TAG_keterangan = "keterangan";
private static final String TAG_status = "status";

@Override  
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_anggota);
ip=jsonParser.getIP();
callMarquee();
txtkode_anggota = (EditText) findViewById(R.id.txtkode_anggota);
txtnama_anggota= (EditText) findViewById(R.id.txtnama_anggota);
txtalamat= (EditText) findViewById(R.id.txtalamat);
txtnik= (EditText) findViewById(R.id.txtnik);
txttgl_lahir= (EditText) findViewById(R.id.txttgl_lahir);
txtjenis_kelamin= (EditText) findViewById(R.id.txtjenis_kelamin);
txtdepartemen= (EditText) findViewById(R.id.txtdepartemen);
txtusername = (EditText) findViewById(R.id.txtusername);
txtpassword= (EditText) findViewById(R.id.txtpassword);
txtgambar= (EditText) findViewById(R.id.txtgambar);
txtketerangan= (EditText) findViewById(R.id.txtketerangan);
txtstatus= (EditText) findViewById(R.id.txtstatus);
btnProses= (Button) findViewById(R.id.btnproses);
btnHapus = (Button) findViewById(R.id.btnhapus);
Intent i = getIntent(); 
kode_anggota0 = i.getStringExtra("pk");
if(kode_anggota0.length()>0){
new get().execute();
btnProses.setText("Update Data");
btnHapus.setVisibility(View.VISIBLE);
}
else{
btnProses.setText("Add New Data");
btnHapus.setVisibility(View.GONE);
}

btnProses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
kode_anggota= txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lalamat= txtalamat.getText().toString();
String lnik= txtnik.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lgambar= txtgambar.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lstatus= txtstatus.getText().toString();
if(kode_anggota.length()<1){lengkapi("kode_anggota");}
else if(lnama_anggota.length()<1){lengkapi("nama_anggota");}
else if(lalamat.length()<1){lengkapi("alamat");}
else if(lnik.length()<1){lengkapi("nik");}
else if(ltgl_lahir.length()<1){lengkapi("tgl_lahir");}
else if(ljenis_kelamin.length()<1){lengkapi("jenis_kelamin");}
else if(ldepartemen.length()<1){lengkapi("departemen");}
else if(lusername.length()<1){lengkapi("username");}
else if(lpassword.length()<1){lengkapi("password");}
else if(lgambar.length()<1){lengkapi("gambar");}
else if(lketerangan.length()<1){lengkapi("keterangan");}
else if(lstatus.length()<1){lengkapi("status");}
else{
if(kode_anggota0.length()>0){
new update().execute();
}
else{
new save().execute();
}
}//else
}});

btnHapus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new del().execute();
}});
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class get extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Load data detail. Silahkan tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
int sukses;
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("kode_anggota", kode_anggota0));
String url=ip+"anggota/anggota_detail.php";
Log.v("detail",url);
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params1);
Log.d("detail", json.toString());
sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
JSONArray myObj = json.getJSONArray(TAG_record); // JSON Array
final JSONObject myJSON = myObj.getJSONObject(0);
runOnUiThread(new Runnable() {
public void run() {
try {
txtkode_anggota.setText(kode_anggota0);
txtnama_anggota.setText(myJSON.getString(TAG_nama_anggota));
txtgambar.setText(myJSON.getString(TAG_gambar));
txtketerangan.setText(myJSON.getString(TAG_keterangan));
txtalamat.setText(myJSON.getString(TAG_alamat));
txtnik.setText(myJSON.getString(TAG_nik));
txttgl_lahir.setText(myJSON.getString(TAG_tgl_lahir));
txtjenis_kelamin.setText(myJSON.getString(TAG_jenis_kelamin));
txtdepartemen.setText(myJSON.getString(TAG_departemen));
txtusername.setText(myJSON.getString(TAG_username));
txtpassword.setText(myJSON.getString(TAG_password));
txtstatus.setText(myJSON.getString(TAG_status));
catch (JSONException e) {e.printStackTrace();}
}});
}
else{
// jika id tidak ditemukan
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class save extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Menyimpan data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
kode_anggota = txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lnik= txtnik.getText().toString();
String lalamat= txtalamat.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lgambar= txtgambar.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lstatus= txtstatus.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota0", kode_anggota0));
params.add(new BasicNameValuePair("kode_anggota", kode_anggota));
params.add(new BasicNameValuePair("nama_anggota", lnama_anggota));
params.add(new BasicNameValuePair("alamat", lalamat));
params.add(new BasicNameValuePair("nik", lnik));
params.add(new BasicNameValuePair("tgl_lahir", ltgl_lahir));
params.add(new BasicNameValuePair("jenis_kelamin", ljenis_kelamin));
params.add(new BasicNameValuePair("departemen", ldepartemen));
params.add(new BasicNameValuePair("gambar", lgambar));
params.add(new BasicNameValuePair("keterangan", lketerangan));
params.add(new BasicNameValuePair("username", lusername));
params.add(new BasicNameValuePair("password", lpassword));
params.add(new BasicNameValuePair("status", lstatus));
String url=ip+"anggota/anggota_add.php";
Log.v("add",url);
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("add", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
} else {
// gagal update data
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

class update extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Mengubah data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
kode_anggota = txtkode_anggota.getText().toString();
String lnama_anggota= txtnama_anggota.getText().toString();
String lalamat= txtalamat.getText().toString();
String lgambar= txtgambar.getText().toString();
String lnik= txtnik.getText().toString();
String ltgl_lahir= txttgl_lahir.getText().toString();
String ljenis_kelamin= txtjenis_kelamin.getText().toString();
String ldepartemen= txtdepartemen.getText().toString();
String lketerangan= txtketerangan.getText().toString();
String lusername= txtusername.getText().toString();
String lpassword= txtpassword.getText().toString();
String lstatus= txtstatus.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota0", kode_anggota0));
params.add(new BasicNameValuePair("kode_anggota", kode_anggota));
params.add(new BasicNameValuePair("nama_anggota", lnama_anggota));
params.add(new BasicNameValuePair("alamat", lalamat));
params.add(new BasicNameValuePair("nik", lnik));
params.add(new BasicNameValuePair("tgl_lahir", ltgl_lahir));
params.add(new BasicNameValuePair("jenis_kelamin", ljenis_kelamin));
params.add(new BasicNameValuePair("departemen", ldepartemen));
params.add(new BasicNameValuePair("gambar", lgambar));
params.add(new BasicNameValuePair("username", lusername));
params.add(new BasicNameValuePair("status", lstatus));
String url=ip+"anggota/anggota_update.php";
Log.v("update",url);
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("add", json.toString());
try {
int sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
} else {
// gagal update data
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class del extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Detail_anggota.this);
pDialog.setMessage("Menghapus data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

protected String doInBackground(String... args) {
int sukses;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("kode_anggota", kode_anggota0));

String url=ip+"anggota/anggota_del.php";
Log.v("delete",url);
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("delete", json.toString());
sukses = json.getInt(TAG_SUKSES);
if (sukses == 1) {
Intent i = getIntent();
setResult(100, i);
finish();
}
catch (JSONException e) {e.printStackTrace();}
return null;  
}

protected void onPostExecute(String file_url) {pDialog.dismiss();}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public void lengkapi(String item){
  new AlertDialog.Builder(this)
  .setTitle("Lengkapi Data")
  .setMessage("Silakan lengkapi data "+item +" !")
  .setNeutralButton("Tutup", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dlg, int sumthin) {
    finish();
   }}).show();
 
 
void callMarquee(){
         Calendar cal = Calendar.getInstance();          
         int jam = cal.get(Calendar.HOUR);
         int menit= cal.get(Calendar.MINUTE);
         int detik= cal.get(Calendar.SECOND);

         int tgl= cal.get(Calendar.DATE);
         int bln= cal.get(Calendar.MONTH);
         int thn= cal.get(Calendar.YEAR);

         String stgl=String.valueOf(tgl)+"-"+String.valueOf(bln)+"-"+String.valueOf(thn);
         String sjam=String.valueOf(jam)+":"+String.valueOf(menit)+":"+String.valueOf(detik);
        
         TextView  txtMarquee=(TextView)findViewById(R.id.txtMarquee);
         txtMarquee.setSelected(true);
         String kata="Selamat Datang @lp2maray.com Aplikasi Android  "+stgl+"/"+sjam+" #";
         String kalimat=String.format("%1$s",TextUtils.htmlEncode(kata));
         txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat)); 
  }
 
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}   
 
}
+++++++++++++++++++





Kamis, 22 Agustus 2019

Android TM Lib

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:opencv="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="landscape">

    <org.opencv.android.JavaCameraView
        android:id="@+id/deteksi"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        opencv:camera_id="any"
        opencv:show_fps="true"

        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center|bottom"
        android:layout_margin="16dp"
        android:gravity="center"
        android:orientation="horizontal"
        android:weightSum="2"
        android:layout_marginTop="260dp">

        <Button
            android:id="@+id/btnCek"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="COMPARE"
            android:layout_gravity="center"/>
    </LinearLayout>

</RelativeLayout>




package com.example.fau.deteksidaun;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.DMatch;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.Scalar;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.DescriptorMatcher;
import org.opencv.features2d.FeatureDetector;
import org.opencv.features2d.Features2d;
import org.opencv.imgproc.Imgproc;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

public class Deteksi extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{


    String gab="";
    int jd=10;
    Button btnCek;
    String[]arObject;
    String[]arNama;

String hasilObject="";
    private static final String TAG = "OCVSample::Activity";
    private static final int REQUEST_PERMISSION = 100;
    private int w, h;
    private CameraBridgeViewBase mOpenCvCameraView;
    TextView tvName;
    Scalar RED = new Scalar(255, 0, 0);
    Scalar GREEN = new Scalar(0, 255, 0);
    FeatureDetector detector;
    DescriptorExtractor descriptor;
    DescriptorMatcher matcher;

    Mat descriptors2;
    MatOfKeyPoint keypoints2;

    MatOfKeyPoint [] key1;
    Mat desc1[],citra1[];

    static {
        if (!OpenCVLoader.initDebug())
            Log.d("ERROR", "Unable to load OpenCV");
        else
            Log.d("SUCCESS", "OpenCV loaded");
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    Log.i(TAG, "OpenCV loaded successfully");
                    // mOpenCvCameraView.enableView();
                    try {
                        initializeOpenCVDependencies();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
                default: {
                    super.onManagerConnected(status);
                }
                break;
            }
        }
    };

    private void initializeOpenCVDependencies() throws IOException {
        mOpenCvCameraView.enableView();
        detector = FeatureDetector.create(FeatureDetector.ORB);
        descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
        matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

        Button btnCek=(Button)findViewById(R.id.btnCek);
        btnCek.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent i = new Intent(Deteksi.this, HasilKlasifikasi.class);
                i.putExtra("hasil ", hasilObject);
                startActivity(i);
            }});



        arObject=new String[jd];
arNama=new String[jd];
desc1=new Mat[jd];
citra1=new Mat[jd];
key1=new MatOfKeyPoint[jd];

        arObject[0]="obj1.jpg";
        arObject[1]="obj2.jpg";
        arObject[2]="obj3.jpg";

        arNama[0]="Object 1";
        arNama[1]="Object 2";
        arNama[2]="Object 3";

        AssetManager assetManager = getAssets();

        for(int k=0;k<jd;k++) {
            citra1[k] = new Mat();
            InputStream istr1 = assetManager.open(arObject[k]);//a.jpeg
            Bitmap bitmap1 = BitmapFactory.decodeStream(istr1);
            Utils.bitmapToMat(bitmap1, citra1[k] );
            Imgproc.cvtColor(citra1[k] , citra1[k] , Imgproc.COLOR_RGB2GRAY);


            citra1[k] .convertTo(citra1[k] , 0);
            desc1[k] = new Mat();
            key1[k] = new MatOfKeyPoint();
            detector.detect(citra1[k] , key1[k]);
            descriptor.compute(citra1[k] , key1[k], desc1[k]);
        }
        //============================================1
    }
    public Deteksi() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_deteksi);


        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION);
        }
        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.deteksi);
        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
        mOpenCvCameraView.setCvCameraViewListener(this);
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }
    @Override
    public void onResume() {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, Deteksi.this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }

        }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }
    @Override
    public void onCameraViewStarted(int width, int height) {
        w = width;
        h = height;
    }

    @Override
    public void onCameraViewStopped() {

    }

    public Mat recognize(Mat aInputFrame) {//aInputFrame=objek dari Kamera
        double nmin = 10000000;
        int indexKe=0;

        Imgproc.cvtColor(aInputFrame, aInputFrame, Imgproc.COLOR_RGB2GRAY);
        descriptors2 = new Mat();
        keypoints2 = new MatOfKeyPoint();
        detector.detect(aInputFrame, keypoints2);
        descriptor.compute(aInputFrame, keypoints2, descriptors2);


        MatOfDMatch matches = null;
        Double max_dist = 0.0;
        Double min_dist = 100.0;
        int JM = 0;

        matches = new MatOfDMatch();
        for(int k=0;k<jd;k++){
        if (citra1[k].type() == aInputFrame.type()) {
            try {
                matcher.match(desc1[k], descriptors2, matches);

                List<DMatch> matchesList1 = matches.toList();

                max_dist = 0.0;
                min_dist = 100.0;

                JM = matchesList1.size();
                for (int i = 0; i < JM; i++) {
                    Double dist = (double) matchesList1.get(i).distance;
                    if (dist < min_dist)
                        min_dist = dist;
                    if (dist > max_dist)
                        max_dist = dist;
                }
                Log.d("MAXMIN15", "@Object1=" + max_dist + "@" + min_dist + "@" + (1.2 * min_dist));
                if (min_dist < nmin) {
                    indexKe = k;
                    nmin = min_dist;
                }

            } catch (Exception ee) {
            }
        } else {
            return aInputFrame;
        }

    }//loop


        //=================================================================================3
        matches = new MatOfDMatch();
        if (citra1[indexKe].type() == aInputFrame.type()) {
            try {
                matcher.match(desc1[indexKe], descriptors2, matches);
            } catch (Exception ee) {
            }

        } else {
            return aInputFrame;
        }

        List<DMatch> matchesListOut = matches.toList();
        JM = matchesListOut.size();
        List<DMatch>  listBest=null;
        Mat imgBest=new Mat();
        MatOfKeyPoint keyBest=null;

            listBest=matchesListOut;
            imgBest=citra1[indexKe];
            keyBest=key1[indexKe];
        hasilObject=arNama[indexKe];

        //=================================================================================================LAST
        int mm=0;
        LinkedList<DMatch> good_matches = new LinkedList<DMatch>();
        for (int i = 0; i < JM; i++) {
            if (listBest.get(i).distance <= (1.2 * min_dist)) {//1.5 * min_dist
                good_matches.addLast(listBest.get(i));
                mm++;
            }
        }
        gab=gab+String.valueOf(mm)+"#";
        Log.d("GAB","#"+gab+"+++++++++++++++++++++++++++++++++++++++++++++");

        MatOfDMatch goodMatches = new MatOfDMatch();
        goodMatches.fromList(good_matches);
        Mat outputImg = new Mat();


        MatOfByte drawnMatches = new MatOfByte();
        if (aInputFrame.empty() || aInputFrame.cols() < 1 || aInputFrame.rows() < 1) {
            return aInputFrame;
        }
        Features2d.drawMatches(imgBest, keyBest, aInputFrame, keypoints2, goodMatches, outputImg, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS);
        Imgproc.resize(outputImg, outputImg, aInputFrame.size());


        return outputImg;
    }


        @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        return recognize(inputFrame.rgba());
    }
}


+++++
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fau.apps">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature   android:name="android.hardware.camera"  android:required="false" />
    <uses-feature  android:name="android.hardware.camera.autofocus"  android:required="false" />
    <uses-feature  android:name="android.hardware.camera.front" android:required="false" />
    <uses-feature   android:name="android.hardware.camera.front.autofocus"   android:required="false" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".HalamanUtama">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Deteksi" />
        <activity android:name=".HasilKlasifikasi"></activity>
    </application>

</manifest>


HTML Assets Post Data to Android




<html lang="en">
<head>
  <meta charset="utf-8">
  <title>HTML POST</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form action="http://localhost/aplikasi/add.php?&ket=register via HTML" id="searchForm">
  <input type="text" name="nama_user" placeholder="Search...">
  <input type="submit" value="Search">
</form>
<div id="result"></div>

<script>


$( "#searchForm" ).submit(function( event ) {

  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $( this ),
    term = $form.find( "input[name='s']" ).val(),
    url = $form.attr( "action" );

  // Send the data using post post
  var posting = $.get( url, { s: term } );

  // Put the results in a div
  posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  alert( "success" );
  });
});
</script>

</body>
</html>

++++++++++++++++++++++++++++++++++++THE PHP

$nama_user=$_GET["nama_user"];
$ket=$_GET["ket"];

$sql="INSERT INTO `tb_user`
(`id_user`, `nama_user`,  `keterangan`) VALUES('', '$nama_user', '$ket')";

$simpan=process($conn,$sql);
echo"#content:sukses";
+++++++++++++++++++++++++++++++++++++



Selasa, 20 Agustus 2019

Aplikasi Mencari Kesamaan Objek












import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
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.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.DMatch;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDMatch;
import org.opencv.core.MatOfKeyPoint;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.features2d.DescriptorExtractor;
import org.opencv.features2d.DescriptorMatcher;
import org.opencv.features2d.FeatureDetector;
import org.opencv.imgproc.Imgproc;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class UJI extends AppCompatActivity {
    int jumMM=0;
    int jumJM;


    String gab="";
    int jd=20;
    Button btnCek;
    String[]arID;

    String kategori,mypath,huruf;
    private static final String TAG = "OCVSample::Activity";
    private static final int REQUEST_PERMISSION = 100;
    TextView tvName;
    Scalar RED = new Scalar(255, 0, 0);
    Scalar GREEN = new Scalar(0, 255, 0);
    FeatureDetector detector;
    DescriptorExtractor descriptor;
    DescriptorMatcher matcher;

    Mat descriptors2;
    MatOfKeyPoint keypoints2;

    MatOfKeyPoint [] key1;
    Mat desc1[],citra1[];

    static {
        if (!OpenCVLoader.initDebug())
            Log.d("ERROR", "Unable to load OpenCV");
        else
            Log.d("SUCCESS", "OpenCV loaded");
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    Log.i(TAG, "OpenCV loaded successfully");
                    try {
                       // initializeOpenCVDependencies();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
                break;
                default: {
                    super.onManagerConnected(status);
                }
                break;
            }
        }
    };

    private void initializeOpenCVDependencies() throws IOException {
     //   mOpenCvCameraView.enableView();
        detector = FeatureDetector.create(FeatureDetector.ORB);
        descriptor = DescriptorExtractor.create(DescriptorExtractor.ORB);
        matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);




        mypath=arID[0];
        AssetManager assetManager = getAssets();
        Mat aInputFrame=new Mat();

        //Bitmap   bitmap1 = BitmapFactory.decodeFile(path);

        InputStream istr2 = null;//a.jpeg
        try {
            istr2 = assetManager.open(mypath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap2 = BitmapFactory.decodeStream(istr2);

        Utils.bitmapToMat(bitmap2, aInputFrame );//aInputFrame=citra1[k]
        Imgproc.cvtColor(aInputFrame , aInputFrame , Imgproc.COLOR_RGB2GRAY);


        aInputFrame.convertTo(aInputFrame , 0);
        descriptors2= new Mat();//descriptors2=desc1[k]
        keypoints2 = new MatOfKeyPoint();//keypoints2=   key1[k]
        detector.detect(aInputFrame ,keypoints2);
        descriptor.compute(aInputFrame , keypoints2, descriptors2);






        for(int k=0;k<jd;k++) {
            citra1[k] = new Mat();
            InputStream istr1 = assetManager.open(arID[k]);//a.jpeg
            Bitmap bitmap1 = BitmapFactory.decodeStream(istr1);
            Utils.bitmapToMat(bitmap1, citra1[k] );
            Imgproc.cvtColor(citra1[k] , citra1[k] , Imgproc.COLOR_RGB2GRAY);


            citra1[k] .convertTo(citra1[k] , 0);
            desc1[k] = new Mat();
            key1[k] = new MatOfKeyPoint();
            detector.detect(citra1[k] , key1[k]);
            descriptor.compute(citra1[k] , key1[k], desc1[k]);

            compareBitmaps(bitmap1, bitmap2);
            //compareMats(descriptors2, desc1[k]);
        }
        //============================================1


//        Log.d("path",kategori+"#"+huruf+"#"+mypath);
//        cekCompare(mypath);

    }


    public UJI() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        setContentView(R.layout.activity_deteksi);

//        Intent io=this.getIntent();
//        kategori=io.getStringExtra("kategori");
//        mypath=io.getStringExtra("mypath");
//        huruf=io.getStringExtra("huruf");
        //btnCek.setText(mypath);
        huruf="A";

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION);
        }


        jd=3;
        arID=new String[jd];
        desc1=new Mat[jd];
        citra1=new Mat[jd];
        key1=new MatOfKeyPoint[jd];

        if(huruf.equalsIgnoreCase("A")) {
            arID[0] = "a1.png";
            arID[1] = "a2.png";
            arID[2] = "a3.png";
        }
        else  if(huruf.equalsIgnoreCase("I")) {
            arID[0] = "i1.png";
            arID[1] = "i2.png";
            arID[2] = "i3.png";
        }
        else  if(huruf.equalsIgnoreCase("U")) {
            arID[0] = "u1.png";
            arID[1] = "u2.png";
            arID[2] = "u3.png";
        }
        else  if(huruf.equalsIgnoreCase("E")) {
            arID[0] = "e1.png";
            arID[1] = "e2.png";
            arID[2] = "e3.png";
        }
        else  if(huruf.equalsIgnoreCase("KA")) {
            arID[0] = "ka1.png";
            arID[1] = "ka2.png";
            arID[2] = "ka3.png";
        }
        else  if(huruf.equalsIgnoreCase("KI")) {
            arID[0] = "ki1.png";
            arID[1] = "ki2.png";
            arID[2] = "ki3.png";
        }
        else  if(huruf.equalsIgnoreCase("KU")) {
            arID[0] = "ku1.png";
            arID[1] = "ku2.png";
            arID[2] = "ku3.png";
        }
        else  if(huruf.equalsIgnoreCase("KE")) {
            arID[0] = "ke1.png";
            arID[1] = "ke2.png";
            arID[2] = "ke3.png";
        }
        else  if(huruf.equalsIgnoreCase("KO")) {
            arID[0] = "ko1.png";
            arID[1] = "ko2.png";
            arID[2] = "ko3.png";
        }
        else  if(huruf.equalsIgnoreCase("SA")) {
            arID[0] = "sa1.png";
            arID[1] = "sa2.png";
            arID[2] = "sa3.png";
        }
        else  if(huruf.equalsIgnoreCase("SHI")) {
            arID[0] = "shi1.png";
            arID[1] = "shi2.png";
            arID[2] = "shi3.png";
        }
        else  if(huruf.equalsIgnoreCase("SU")) {
            arID[0] = "su1.png";
            arID[1] = "su2.png";
            arID[2] = "su3.png";
        }
        else  if(huruf.equalsIgnoreCase("SE")) {
            arID[0] = "se1.png";
            arID[1] = "se2.png";
            arID[2] = "se3.png";
        }
        else  if(huruf.equalsIgnoreCase("SO")) {
            arID[0] = "so1.png";
            arID[1] = "so2.png";
            arID[2] = "so3.png";
        }
        else  if(huruf.equalsIgnoreCase("TA")) {
            arID[0] = "ta1.png";
            arID[1] = "ta2.png";
            arID[2] = "ta3.png";
        }
        else  if(huruf.equalsIgnoreCase("CHI")) {
            arID[0] = "chi1.png";
            arID[1] = "chi2.png";
            arID[2] = "chi3.png";
        }
        else  if(huruf.equalsIgnoreCase("TSU")) {
            arID[0] = "tsu1.png";
            arID[1] = "tsu2.png";
            arID[2] = "tsu3.png";
        }
        else  if(huruf.equalsIgnoreCase("TE")) {
            arID[0] = "te1.png";
            arID[1] = "te2.png";
            arID[2] = "te3.png";
        }
        else  if(huruf.equalsIgnoreCase("TO")) {
            arID[0] = "to1.png";
            arID[1] = "to2.png";
            arID[2] = "to3.png";
        }
        else  if(huruf.equalsIgnoreCase("NA")) {
            arID[0] = "na1.png";
            arID[1] = "na2.png";
            arID[2] = "na3.png";
        }
        else  if(huruf.equalsIgnoreCase("NI")) {
            arID[0] = "ni1.png";
            arID[1] = "ni2.png";
            arID[2] = "ni3.png";
        }
        else  if(huruf.equalsIgnoreCase("NU")) {
            arID[0] = "nu1.png";
            arID[1] = "nu2.png";
            arID[2] = "nu3.png";
        }
        else  if(huruf.equalsIgnoreCase("NE")) {
            arID[0] = "ne1.png";
            arID[1] = "ne2.png";
            arID[2] = "ne3.png";
        }
        else  if(huruf.equalsIgnoreCase("NO")) {
            arID[0] = "no1.png";
            arID[1] = "no2.png";
            arID[2] = "no3.png";
        }
        else  if(huruf.equalsIgnoreCase("HA")) {
            arID[0] = "ha1.png";
            arID[1] = "ha2.png";
            arID[2] = "ha3.png";
        }
        else  if(huruf.equalsIgnoreCase("HI")) {
            arID[0] = "hi1.png";
            arID[1] = "hi2.png";
            arID[2] = "hi3.png";
        }
        else  if(huruf.equalsIgnoreCase("FU")) {
            arID[0] = "fu1.png";
            arID[1] = "fu2.png";
            arID[2] = "fu3.png";
        }
        else  if(huruf.equalsIgnoreCase("HE")) {
            arID[0] = "he1.png";
            arID[1] = "he2.png";
            arID[2] = "he3.png";
        }
        else  if(huruf.equalsIgnoreCase("HO")) {
            arID[0] = "ho1.png";
            arID[1] = "ho2.png";
            arID[2] = "ho3.png";
        }
        else  if(huruf.equalsIgnoreCase("MA")) {
            arID[0] = "ma1.png";
            arID[1] = "ma2.png";
            arID[2] = "ma3.png";
        }
        else  if(huruf.equalsIgnoreCase("MI")) {
            arID[0] = "mi1.png";
            arID[1] = "mi2.png";
            arID[2] = "mi3.png";
        }
        else  if(huruf.equalsIgnoreCase("MU")) {
            arID[0] = "mu1.png";
            arID[1] = "mu2.png";
            arID[2] = "mu3.png";
        }
        else  if(huruf.equalsIgnoreCase("ME")) {
            arID[0] = "me1.png";
            arID[1] = "me2.png";
            arID[2] = "me3.png";
        }
        else  if(huruf.equalsIgnoreCase("MO")) {
            arID[0] = "mo1.png";
            arID[1] = "mo2.png";
            arID[2] = "mo3.png";
        }
        else  if(huruf.equalsIgnoreCase("YA")) {
            arID[0] = "ya1.png";
            arID[1] = "ya2.png";
            arID[2] = "ya3.png";
        }
        else  if(huruf.equalsIgnoreCase("YU")) {
            arID[0] = "yu1.png";
            arID[1] = "yu2.png";
            arID[2] = "yu3.png";
        }
        else  if(huruf.equalsIgnoreCase("YO")) {
            arID[0] = "yo1.png";
            arID[1] = "yo2.png";
            arID[2] = "yo3.png";
        }
        else  if(huruf.equalsIgnoreCase("RA")) {
            arID[0] = "ra1.png";
            arID[1] = "ra2.png";
            arID[2] = "ra3.png";
        }
        else  if(huruf.equalsIgnoreCase("RI")) {
            arID[0] = "ri1.png";
            arID[1] = "ri2.png";
            arID[2] = "ri3.png";
        }
        else  if(huruf.equalsIgnoreCase("RU")) {
            arID[0] = "ru1.png";
            arID[1] = "ru2.png";
            arID[2] = "ru3.png";
        }
        else  if(huruf.equalsIgnoreCase("RO")) {
            arID[0] = "re1.png";
            arID[1] = "re2.png";
            arID[2] = "re3.png";
        }
        else  if(huruf.equalsIgnoreCase("RO")) {
            arID[0] = "ro1.png";
            arID[1] = "ro2.png";
            arID[2] = "ro3.png";
        }
        else  if(huruf.equalsIgnoreCase("WA")) {
            arID[0] = "wa1.png";
            arID[1] = "wa2.png";
            arID[2] = "wa3.png";
        }
        else  if(huruf.equalsIgnoreCase("WO")) {
            arID[0] = "wo1.png";
            arID[1] = "wo2.png";
            arID[2] = "wo3.png";
        }
        else  if(huruf.equalsIgnoreCase("N")) {
            arID[0] = "n1.png";
            arID[1] = "n2.png";
            arID[2] = "n3.png";
        }


        try {
            initializeOpenCVDependencies();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void cekCompare(String path) {//aInputFrame=objek dari Kamera
        Mat aInputFrame=new Mat();
        AssetManager assetManager = getAssets();

        //Bitmap   bitmap1 = BitmapFactory.decodeFile(path);

        InputStream istr1 = null;//a.jpeg
        try {
            istr1 = assetManager.open(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap1 = BitmapFactory.decodeStream(istr1);

        Utils.bitmapToMat(bitmap1, aInputFrame );//aInputFrame=citra1[k]
        Imgproc.cvtColor(aInputFrame , aInputFrame , Imgproc.COLOR_RGB2GRAY);

        //cekCompare2(aInputFrame);


//        String sgab="";
//        aInputFrame.convertTo(aInputFrame , 0);
//        descriptors2= new Mat();//descriptors2=desc1[k]
//        keypoints2 = new MatOfKeyPoint();//keypoints2=   key1[k]
//        detector.detect(aInputFrame ,keypoints2);
//        descriptor.compute(aInputFrame , keypoints2, descriptors2);
//
//
//
//
//        compareBitmaps(bmTemplate, bmLogo);

    }
//======================================


    public   void cekCompare2(Mat aInputFrame) {
        String sgab="";
        aInputFrame.convertTo(aInputFrame , 0);
        descriptors2= new Mat();//descriptors2=desc1[k]
        keypoints2 = new MatOfKeyPoint();//keypoints2=   key1[k]
        detector.detect(aInputFrame ,keypoints2);
        descriptor.compute(aInputFrame , keypoints2, descriptors2);






        double nmin = 10000000;
        int indexKe=0;

        MatOfDMatch matches = null;

        int JM = 0;
        Double max_dist = 0.0;
        Double min_dist = 100.0;

        matches = new MatOfDMatch();
        for(int k=0;k<jd;k++){

            matcher.match(desc1[k],descriptors2,matches);
            MatOfDMatch filtered = filterMatchesByDistance(matches);

            int total = (int) matches.size().height;
            int Match= (int) filtered.size().height;
            Log.d("HITUNG_MM",k+"."+arID[k]+"=Total Bit:" + total + " Match Bit:"+Match);

            if(JM<Match){JM=Match;indexKe=k;}


//                try {
//                    matcher.match(desc1[k], descriptors2, matches);
//                    List<DMatch> matchesList1 = matches.toList();
//
//                    JM = matchesList1.size();
//                    for (int i = 0; i < JM; i++) {
//                        Double dist = (double) matchesList1.get(i).distance;
//                        if (dist < min_dist)
//                            min_dist = dist;
//                        if (dist > max_dist)
//                            max_dist = dist;
//                    }
//
//                    if (min_dist < nmin) {
//                        indexKe = k;
//                        nmin = min_dist;
//                    }
//                    Log.d("MAXMIN", k+"." + max_dist + "@" + min_dist + "@" + (1.2 * min_dist)+"#"+indexKe);
//                } catch (Exception ee) {
//                }
//
//
//            matches = new MatOfDMatch();
//                try {
//                    matcher.match(desc1[k], descriptors2, matches);
//                } catch (Exception ee) {
//                }
//
//
//                    List<DMatch> matchesListOut = matches.toList();
//                    JM = matchesListOut.size();
//                    List<DMatch>  listBest=null;
//                    listBest=matchesListOut;
//
//            //=================================================================================================LAST
//                    int mm=0;
//                    LinkedList<DMatch> good_matches = new LinkedList<DMatch>();
//                    for (int i = 0; i < JM; i++) {
//                        if (listBest.get(i).distance <= (1.2 * min_dist)) {//1.5 * min_dist
//                            good_matches.addLast(listBest.get(i));
//                            mm++;
//                        }
//                    }
//
//            if(jumMM<mm){
//                jumMM=mm;
//            }
//
//            if(jumJM<JM){
//                jumJM=JM;
//            }
//
//            Log.d("HITUNG_MM",k+"."+mm+"#"+jumMM+"#JM="+JM+"#"+jumJM);
//
//            sgab+="GB"+(k+1)+"."+mm+"#"+jumMM+"#JM="+JM+"#"+jumJM+"\n";

        }//loop
hasil(JM+"#"+indexKe);
    }




    public void hasil(String hs){
        new AlertDialog.Builder(this)
                .setTitle("Kategori:"+kategori+":"+huruf)
                .setMessage(hs)
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        finish();
                    }})
                .show();
    }


//    static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
//        List<DMatch> matches_original = matches.toList();
//        List<DMatch> matches_filtered = new ArrayList<DMatch>();
//
//        int DIST_LIMIT = 30;
//        // Check all the matches distance and if it passes add to list of filtered matches
//        Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
//        for (int i = 0; i < matches_original.size(); i++) {
//            DMatch d = matches_original.get(i);
//            if (Math.abs(d.distance) <= DIST_LIMIT) {
//                matches_filtered.add(d);
//            }
//        }
//        Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");
//
//        MatOfDMatch mat = new MatOfDMatch();
//        mat.fromList(matches_filtered);
//        return mat;
//    }



    //=======================
    private Bitmap findLogo(Bitmap sourceBitmap) {
        Bitmap roiBitmap = null;
        Mat sourceMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC3);
        Utils.bitmapToMat(sourceBitmap, sourceMat);
        Mat roiTmp = sourceMat.clone();

        final Mat hsvMat = new Mat();
        sourceMat.copyTo(hsvMat);

        // convert mat to HSV format for Core.inRange()
        Imgproc.cvtColor(hsvMat, hsvMat, Imgproc.COLOR_RGB2HSV);

        Scalar lowerb = new Scalar(85, 50, 40);         // lower color border for BLUE
        Scalar upperb = new Scalar(135, 255, 255);      // upper color border for BLUE
        Core.inRange(hsvMat, lowerb, upperb, roiTmp);   // select only blue pixels

        // find contours
        List<MatOfPoint> contours = new ArrayList<>();
        List<Rect> squares = new ArrayList<>();
        Imgproc.findContours(roiTmp, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

        // find appropriate bounding rectangles
        for (MatOfPoint contour : contours) {
            MatOfPoint2f areaPoints = new MatOfPoint2f(contour.toArray());
            RotatedRect boundingRect = Imgproc.minAreaRect(areaPoints);

            double rectangleArea = boundingRect.size.area();

            // test min ROI area in pixels
            if (rectangleArea > 400) {
                Point rotated_rect_points[] = new Point[4];
                boundingRect.points(rotated_rect_points);

                Rect rect = Imgproc.boundingRect(new MatOfPoint(rotated_rect_points));
                double aspectRatio = rect.width > rect.height ?
                        (double) rect.height / (double) rect.width : (double) rect.width / (double) rect.height;
                if (aspectRatio >= 0.9) {
                    squares.add(rect);
                }
            }
        }

        Mat logoMat = extractSquareMat(roiTmp, getBiggestSquare(squares));

        roiBitmap = Bitmap.createBitmap(logoMat.cols(), logoMat.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(logoMat, roiBitmap);
        return roiBitmap;
    }
    public static Mat extractSquareMat(Mat sourceMat, Rect rect) {
        Mat squareMat = null;
        int padding = 50;

        if (rect != null) {
            Rect truncatedRect = new Rect((int) rect.tl().x + padding, (int) rect.tl().y + padding,
                    rect.width - 2 * padding, rect.height - 2 * padding);
            squareMat = new Mat(sourceMat, truncatedRect);
        }

        return squareMat ;
    }

    private void compareBitmaps(Bitmap bitmap1, Bitmap bitmap2) {
        Mat mat1 = new Mat(bitmap1.getWidth(), bitmap1.getHeight(), CvType.CV_8UC3);
        Utils.bitmapToMat(bitmap1, mat1);

        Mat mat2 = new Mat(bitmap2.getWidth(), bitmap2.getHeight(), CvType.CV_8UC3);
        Utils.bitmapToMat(bitmap2, mat2);
Log.d("OKDEH","90sukses");
        compareMats(mat1, mat2);
    }


    private void compareMats(Mat img1, Mat img2) {
        FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB);
        DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
        DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);

        Mat descriptors1 = new Mat();
        MatOfKeyPoint keypoints1 = new MatOfKeyPoint();
        detector.detect(img1, keypoints1);
        extractor.compute(img1, keypoints1, descriptors1);

        //second image
        // Mat img2 = Imgcodecs.imread(path2);
        Mat descriptors2 = new Mat();
        MatOfKeyPoint keypoints2 = new MatOfKeyPoint();
        detector.detect(img2, keypoints2);
        extractor.compute(img2, keypoints2, descriptors2);

        Log.d("OKDEH","91sukses");
        //matcher image descriptors
        MatOfDMatch matches = new MatOfDMatch();
        matcher.match(descriptors1,descriptors2,matches);

        // Filter matches by distance
        MatOfDMatch filtered = filterMatchesByDistance(matches);

        int total = (int) matches.size().height;
        int Match= (int) filtered.size().height;
        Log.d("LOGOKDEH", "total:" + total + " Match:" + Match);
    }

    static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
        List<DMatch> matches_original = matches.toList();
        List<DMatch> matches_filtered = new ArrayList<DMatch>();

        int DIST_LIMIT = 30;
        // Check all the matches distance and if it passes add to list of filtered matches
        Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
        for (int i = 0; i < matches_original.size(); i++) {
            DMatch d = matches_original.get(i);
            if (Math.abs(d.distance) <= DIST_LIMIT) {
                matches_filtered.add(d);
            }
        }
        Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");

        MatOfDMatch mat = new MatOfDMatch();
        mat.fromList(matches_filtered);
        return mat;
    }


    public static Rect getBiggestSquare(List<Rect> squares) {
        Rect biggestSquare = null;

        if (squares != null && squares.size() >= 1) {
            Rect square;
            double maxArea;
            int ixMaxArea = 0;

            square = squares.get(ixMaxArea);
            maxArea = square.area();

            for (int ix = 1; ix < squares.size(); ix++) {
                square = squares.get(ix);
                if (square.area() > maxArea) {
                    maxArea = square.area();
                    ixMaxArea = ix;
                }
            }

            biggestSquare = squares.get(ixMaxArea);
        }

        return biggestSquare;
    }

}