Post Top Ad

September 13, 2014

Optical Character Recognition (OCR)


For the 3rd year SEP project we  had to create a management dashboard. The requirement was the management  dashboard should give you the high level over view of the existing system. so there i wanted to read existing data of the repots and show them in the dashboard. I achieved using OCR technology. 

Requirements

This solution requires that you have Microsoft Office 2003 or above  installed. Since office 2010 do not support this method you will need to have previous version of office packages installed.  Office has included a library called, Microsoft Office Document Imaging, (MODI . The dll file what we really needs to reference from our code is called MDIVWCTL.DLL. 
And also this library needs to be installed in any client machine, if we want to use the office document imaging facilities to do the OCR functionality

Assumptions

Here, we’ll assume that you already have an Image to work with. we need a area where we want to extract the image details and show them in the dashboard so lets take values as X1, Y1, X2, Y2. Let the (X1,Y1) be the top left corner of the area, and that (X2, Y2)  be the  right corner of the area.

How solution Works

  private void btn_View(object sender, RoutedEventArgs e)
    {
        string result = "";
        Bitmap b = new Bitmap("..\\..\\Priyankara\\testBMP.jpeg");

        //calling Extract method
        // var newBmp = Extract(b , 1, 88, 290, 126);
        Bitmap newBmp = Extract(b, 816, 584, 1161, 612);
        if (newBmp == null)
        {
            result = string.Empty;
        }
        else
        {
            String tempFile = CreateTempFile(newBmp);
            result = OcrTempFile(tempFile);


            TextWriter tsw = new StreamWriter(@"..\\..\\Priyankara\\xmlWriter.txt"); // true without overriting


            //Writing text to the file.
            tsw.WriteLine(result);


            //Close the file.
            tsw.Close();
          //  MessageBox.Show("File written Successfully");


        }

        //converting text File to XML

        String[] data = File.ReadAllLines(@"..\\..\\Priyankara\\xmlWriter.txt");
             XElement root = new XElement("orders",
                                        from item in data
                                        select new XElement("Values", item));
             root.Save(@"..\\..\\Priyankara\\xmlWriter.xml");

        //Loading text File

             XDocument xmlDoc = XDocument.Load(@"..\\..\\Priyankara\\xmlWriter.xml");
             String[] test = xmlDoc.Descendants("orders").Elements("Values").Select(r => r.Value).ToArray();
             String result1 = string.Join("|", test);

            

             string fullName = result1;
             var names = fullName.Split('|');
             string firstName = names[0];
            string lastName = names[1];
            string ccc = names[2];
       // TextBox1.t
             txtUsername.Text = names[0];
             txtUsername1.Text = names[1];
             txtUsername2.Text = names[2];
          //  MessageBox.Show(ccc);

        // Early
        //string[] letters = result.Select(c => c.ToString()).ToArray();

        //textBox1.Text = Convert.ToString(result[0]);       

        }

        //Extracting part of the image
        Bitmap Extract(Bitmap bmp, int x1, int y1, int x2, int y2)
        {
            try
            {
                int width = x2 - x1;
                int height = y2 - y1;
                if (bmp == null || width < 1 || height < 1)
                {
                    return null;
                }
                Bitmap subImage = bmp.Clone(new System.Drawing.Rectangle(x1, y1, width, height), bmp.PixelFormat);
                return subImage;
            }
            catch
            {
                return null;
            }
        }

        // save the newly created image into a temp file.
        private string CreateTempFile(Bitmap img)
        {
            String fId = Guid.NewGuid().ToString("N");
            String path = string.Format("{0}{1}.tiff", System.IO.Path.GetTempPath(), fId);
            img.Save(path, ImageFormat.Tiff);
          //  Globals.TempFiles.Add(path);
            return path;
        }

     // read the data from the image.
        [HandleProcessCorruptedStateExceptions]
        string OcrTempFile(string path) {
            try {

                MODI.Document Modi = new MODI.Document();
                Modi.Create(path);
                Modi.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
                MODI.Image img = (MODI.Image)Modi.Images[0];
                MODI.Layout layout = img.Layout;
                String str = layout.Text;
                Modi.Close();
                return str.Trim();

            } catch
            {
                return string.Empty;
            }
        }

        private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }


September 13, 2014

How to send GPS cordinates from android app to web server

First of all this is my solution for a one of my SE project @ SLIIT. 

Here this solution sends the gps cordinaes of the users location in to the server and the server will be abele to capture the signels and show them in the defined page.

Later we can manipulate these data in the server and display them in a separate place. Ex: a dashboard



LocationGPSTrackerActivity class 

This class checkes wheter the network is availabale and the gps is working corretly in the device. if not it will
display on screen messages based on the results

public class LocationGPSTrackerActivity extends Activity implements LocationListener {

    private final static String CONNECTIVITY = "android.net.conn.CONNECTIVITY_CHANGE";

    private LocationManager locationManager;
    private ConnectivityManager connectivityManager;

    SharedPreferences preferences;
    private EditText edit_url;
    private TextView text_gps_status;
    private TextView text_network_status;
    private ToggleButton button_toggle;
    private TextView text_running_since;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(LocationGPSTrackerService.NOTIFICATION)) {
                updateServiceStatus();
            }
            if (action.equals(CONNECTIVITY)) {
                updateNetworkStatus();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gpstracker);

        edit_url = (EditText)findViewById(R.id.edit_url);
        text_gps_status = (TextView)findViewById(R.id.text_gps_status);
        text_network_status = (TextView)findViewById(R.id.text_network_status);
        button_toggle = (ToggleButton)findViewById(R.id.button_toggle);
        text_running_since = (TextView)findViewById(R.id.text_running_since);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (preferences.contains("URL") && ! preferences.getString("URL", "").equals("")) {
            edit_url.setText(preferences.getString("URL", getString(R.string.hint_url)));
            edit_url.clearFocus();
        } else {
            edit_url.requestFocus();
        }
        edit_url.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("URL", s.toString().trim());
                editor.commit();
            }
        });
       
        registerReceiver(receiver, new IntentFilter(LocationGPSTrackerService.NOTIFICATION));
        registerReceiver(receiver, new IntentFilter(LocationGPSTrackerActivity.CONNECTIVITY));
       
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        int pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));   
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            onProviderEnabled(LocationManager.GPS_PROVIDER);
        } else {
            onProviderDisabled(LocationManager.GPS_PROVIDER);
        }

        updateNetworkStatus();
       
        updateServiceStatus();
    }


private void updateServiceStatus() {
       
        if (LocationGPSTrackerService.isRunning) {
            Toast.makeText(this, getString(R.string.toast_service_running), Toast.LENGTH_SHORT).show();
            button_toggle.setChecked(true);
            text_running_since.setText(getString(R.string.text_running_since) + " "
                    + DateFormat.getDateTimeInstance().format(LocationGPSTrackerService.runningSince.getTime()));
        } else {
            Toast.makeText(this, getString(R.string.toast_service_stopped), Toast.LENGTH_SHORT).show();
            button_toggle.setChecked(false);
            if (preferences.contains("stoppedOn")) {
                long stoppedOn = preferences.getLong("stoppedOn", 0);
                if (stoppedOn > 0) {
                    text_running_since.setText(getString(R.string.text_stopped_on) + " "
                            + DateFormat.getDateTimeInstance().format(new Date(stoppedOn)));
                } else {
                    text_running_since.setText(getText(R.string.text_killed));
                }
            }
        }
    }
   
    private void updateNetworkStatus() {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
            text_network_status.setText(getString(R.string.text_network_status_enabled));
            text_network_status.setTextColor(Color.BLACK);
        } else {
            text_network_status.setText(getString(R.string.text_network_status_disabled));
            text_network_status.setTextColor(Color.RED);
        }
    }
    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        locationManager.removeUpdates(this);
        unregisterReceiver(receiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menue, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;
        switch (item.getItemId()) {
        case R.id.menu_settings:
            i = new Intent(this, LocationGPSTrackerPrefs.class);
            startActivity(i);
            break;
        default:
        }
        return super.onOptionsItemSelected(item);
    }

    public void onToggleClicked(View view) {
        Intent intent = new Intent(this, LocationGPSTrackerService.class);
        if (((ToggleButton) view).isChecked()) {
            startService(intent);
        } else {
            stopService(intent);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
        text_gps_status.setText(getString(R.string.text_gps_status_disabled));
        text_gps_status.setTextColor(Color.RED);
    }

    @Override
    public void onProviderEnabled(String provider) {
        text_gps_status.setText(getString(R.string.text_gps_status_enabled));
        text_gps_status.setTextColor(Color.BLACK);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

}

LocationGPSTrackerService

This class is used to display tracking details on the tracker app and to call the LocationGPSTrackerRequest class to open a Http request to the server

public class LocationGPSTrackerService extends IntentService implements LocationListener {

    public static final String NOTIFICATION = "com.example.testmapv2";

    public static boolean isRunning;
    public static Calendar runningSince;
    public Calendar stoppedOn;

    private final static String MY_TAG = "LocationGPSTrackerService";
   
    private SharedPreferences preferences;
    private String urlText;
    private LocationManager locationManager;
    private int pref_gps_updates;
    private long latestUpdate;
    private int pref_max_run_time;

    public LocationGPSTrackerService() {
        super("LocationGPSTrackerService");
    }
   
    @Override
    public void onCreate() {
        super.onCreate();       
        Log.d(MY_TAG, "in onCreate, init GPS stuff");
       
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            onProviderEnabled(LocationManager.GPS_PROVIDER);
        } else {
            onProviderDisabled(LocationManager.GPS_PROVIDER);
        }
       
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong("stoppedOn", 0);
        editor.commit();
        pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));
        pref_max_run_time = Integer.parseInt(preferences.getString("pref_max_run_time", "24"));
        urlText = preferences.getString("URL", "");
        if (urlText.contains("?")) {
            urlText = urlText + "&";
        } else {
            urlText = urlText + "?";
        }
       
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(MY_TAG, "in onHandleIntent, run for maximum time set in preferences");
        new LocationGPSTrackerRequest().execute(urlText + "tracker=start");
               
        isRunning = true;
        runningSince = Calendar.getInstance();
        Intent i = new Intent(NOTIFICATION);
        sendBroadcast(i);
   
        Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.toast_service_running), System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, LocationGPSTrackerActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, getText(R.string.app_name), getText(R.string.toast_service_running), pendingIntent);
        startForeground(R.id.logo, notification);
               
    }
   
    @Override
    public void onDestroy() {
        // destroy when user clicked the stop button or maximum run time has been reached
        Log.d(MY_TAG, "in onDestroy, stop listening to the GPS");
        new LocationGPSTrackerRequest().execute(urlText + "tracker=stop");
       
        locationManager.removeUpdates(this);
       
        isRunning = false;
        stoppedOn = Calendar.getInstance();
       
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong("stoppedOn", stoppedOn.getTimeInMillis());
        editor.commit();
       
        Intent intent = new Intent(NOTIFICATION);
        sendBroadcast(intent);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(MY_TAG, "in onLocationChanged, latestUpdate == " + latestUpdate);
       
        if ((System.currentTimeMillis() - latestUpdate) < pref_gps_updates*1000) {
            return;
        } else {
            latestUpdate = System.currentTimeMillis();
        }
       
        new LocationGPSTrackerRequest().execute(urlText + "lat=" + location.getLatitude() + "&lon=" + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

 Sending Http request to the server

 public class LocationGPSTrackerRequest extends AsyncTask<String, Void, Void> {
    private final static String MY_TAG = "LocationGPSTrackerRequest";
  
    protected Void doInBackground(String... urlText) {
        try {
            URL url = new URL(urlText[0]);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 );
            conn.setConnectTimeout(15000 );
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(MY_TAG, "HTTP request done : " + response);
          
        } catch (Exception e) {
            // whrn network down
            Log.d(MY_TAG, "HTTP request failed");
        }
        return null;
    }
}







My Instagram