Categories
Programming Python

Run Python Scripts using AutoHotkey and Pass Arguments

So you have a python script that has some code like:

import argparse

# GET ORDER ID
parser = argparse.ArgumentParser(description='For blog.codeonion.com my visitors!')
parser.add_argument("--argument_to_be_passed", required=True, type=str, help="Please pass a value into --argument_to_be_passed")
args = parser.parse_args()

value = args.argument_to_be_passed
print(value)

Now, if we run this script, this is the output:

Execution without passing arguments

But if we pass arguments manually:

Arguments are getting passed manually and then printed on command line.

So you see, it is working. But this is slow and boring.

What if you wanted to automate running a python script in order to QUICKLY test something and development purpose!

I know from experience the process of ALT+TAB into a CMD and then pressing UP arrow and press enter is a repetitive labour. Lets reward ourselves with Autohotkey’s automation and buy some extra minutes into the already tightened day.

ENTER THE AUTOHOTKEY!

Once you have installed AutoHotkey, it is time write this script:

; Autoexecute
    #NoEnv
    #SingleInstance force
return
#^space::
    run cmd.exe
    WinWait, ahk_exe cmd.exe ; Wait for CMD to start
    Send c:{enter} ; Go to C drive
    Send cd C:\python\blog\{enter} ; go to script's folder
    Send python arguments.py --argument_to_be_passed CODEONION{enter}
return

Make sure the path to python script is correct. Run this AutoHotkey script file and then, use CTRL+WINDOWSKEY+SPACE to run the macro. And enjoy the spam show!

See it in action!

https://gist.github.com/codeonion/a348f3cc3e580347266fec8f1de6c0d4

Get code from my Github Gist

I really hope this made your day! Please commend and share if oyu are feeling generous. Thanks! and have a nice day!

Categories
Laravel Programming

Laravel 5.8 Creating a MVC project with CRUD in 5 steps

This Laravel tutorial deals with the Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations.

Don’t know how to setup a new Laravel project or you are a 20 year old pro who is too pro to touch the basics? This is the right place to be.  I’ll keep referencing this tutorial whenever Installation is needed in my other Laravel posts.

It is expected that you are familiar with the basics of windows and linux server administration. If you need more help then please use Google. But I will try to avoid the basics to make sure that the goals are achieved without any fuss.

Now I don’t joke around. As per the tradition of this blog, I will make sure that you achieve this goal with the least effort wasted on figuring out wtf is this blog talking about. Let me know in the comments if you find it helpful. So let’s get started!

The 12345 Steps 🙂 :

  1. Setup of new project and running the server to make sure it bites.
  2. Creating a Database (mysql)
  3. Performing Migration to create schema
  4. Controller to repeatedly insert and render a View
  5. Test! and Conclusion

1. Setup and running new project

Lets learn how to install a new Laravel project with running a server on default port 8000.

Before we start, it is important that you should simply follow the official documentation for the latest Laravel Version installation guideline. I don’t want you to look backward when mentioning my blog. 

Source: https://laravel.com/docs/5.8/installation

So create a folder in your drive and open the console in it like so:

Opening the Laravel root project folder in windows command prompt or terminal
Opening the Laravel root project folder in windows command prompt or terminal

Now, lets create a project by running the following command in console:

laravel new codeonion_tutorial 

This creates a “codeonion_tutorial” folder and will start downloading the assets we need.

Creating a new Laravel project
Creating a new Laravel project

After a decade of waiting, the project will be ready. Now let’s make sure that it is running.

  • I go into the codeonion_tutorial project by  cd codeonion_tutorial
  • Start the Server:

php artisan serve

  • Visit the IP address as provided by the console output. Mine by default shows http://localhost:8000
  • So it works. You can now create a database.

2. Creating a Database (mysql)

Lets learn how to create a database in phpmyadmin for a Laravel project. But first, lets enjoy this breathtaking performance by the star of this blog.

Dancing Banana
Dancing Banana

You might be using XAMPP, LAMPP or plain old terminal based mysql server. I don’t care. AS a professional, you must have to know how to create a database. Heck! You must be able to follow this tutorial with using other database engines as well. So help yourself and learn that part as well. Let me know if you want me to make a tutorial about that. Otherwise, just keep following.

I am using Windows and Xampp. Run the Mysql server and open phpmyadmin

Running a Xampp Server for phpmyadmin
Running a Xampp Server for phpmyadmin

Then visit http://localhost/phpmyadmin/

phpmyadmin interface
phpmyadmin interface

Now, let’s create a database. Press New as shown below:

Create a new Database in phpmyadmin
Create a new Database in phpmyadmin

A Create database page will open which is explained below:

Write name of database and press create
Write name of database and press create
  1. Write name of your database to be.
  2. Press Create
  3. Done! (but also note these sub points)
    1. It could
      1. Fail if it violates any rules of database server
      2. It could also fail if your database is not allowed
      3. It could also fail if your Hosting service limits you by number of databases you can make
    2. Now how many bloggers would tell you about these things !! ;D

3. Performing Migration to create schema

Here, lets learn how to perform migrations and database configuration in Laravel.

Nothing is easy nowadays. You have publishers destroying true game developers and companies and then you have web frameworks made confusing by ignorant bloggers. I am all of them combined. So let’s configure our project database for migrations.

  • Our composer installation of the Laravel has already set the .env configuration file in place. But let’s do that manually to exercise the process.
Pointing out the .env configuration file of the Laravel Project
Pointing out the .env configuration file of the Laravel Project
  • Go to the terminal/command line and execute the following command

The .env file will be created and we will now configure it for our database. Open the .env file in the root folder of your newly created project and find the following highlighted database configuration

Editing the .env configuration file in Laravel
Editing the .env configuration file in Laravel

Lets set it to match our database

Laravel default phpmyadmin mysql configuration
Laravel default phpmyadmin mysql configuration

Migrations

First we have to clean the migration files created by composer. Go to the database/migrations/ folder and delete all files.

Now let’s create a migration file. Execute the following command from the root folder of the project.

php artisan make:migration create_messages_table
Creating migration files in Laravel
Creating migration files in Laravel

Now from the root folder, go to database/migrations/ folder and open the latest file which was created. Migration file that was created for me was:

2019_07_14_162743_create_messages_table.php

It has a timestamp along with the name I designated in the filename.

Open the file and lets add commands to create our “messages” table..

Initially, it will contain up and down functions (which handle what happens when we want the executions to be at up or down state in our database server).

Basic Laravel migration file usage
Basic Laravel migration file usage

Lets add the following line after the “id” column line in the up() function

$table->string(‘message’);

Editing the laravel migration file to refer to the table column
Editing the laravel migration file to refer to the table column

Lets run the migration using 

php artisan migrate

Laravel migration process
Laravel migration process

Note that if you screwed up, then you can “undo” the migration using php artisan migrate:rollback but it is not necessary to do now.

At this time, go to phpmyadmin and you will see that our table has been created.

Table updated in phpmyadmin after migration was performed in Laravel
Table updated in phpmyadmin after migration was performed in Laravel

Now, lets make a web page which repeatedly inserts into that table and fetches all and displays into a page. Sweet!

4. Controller to repeatedly insert and render a View

Lets learn how to create a Model, controller, view and route for our Laravel project.

Our database is connected, migrations are up. Now we need to populate the table and then we need to display it on the screen. So lets start without any regular fuss that I am used to deliberately provide to you include this once.

MODEL CREATION

Lets learn how to create a Model for the messages table. This model will be used by the controller.

First, lets create a model by executing this command

php artisan make:model Message

Open the model file at root/app/Message.php and change its content to make sure that it points to the correct table. Add the highlighted line and save it.

Model referring to the database table
Model referring to the database table

Now we can use the model in our controller.

CONTROLLER CREATION

Lets learn how to make a controller for our view. This controller will call out modal to add a random message and fetch all messages.

We need to create a controller. From the root folder, execute this command
php artisan make:controller MessageHandler

Creating a controller in Laravel using command line
Creating a controller in Laravel using command line

This will create a controller file in rootfolder/app/Http/Controllers

Open the root/app/Http/Controllers/MessageHandler.php and change the contents of the controller file as follows:

Laravel controller to insert into table  and get all the records to display in a web page
Laravel controller to insert into table and get all the records to display in a web page

This controller code:

  1. Creates a random message
  2. Saves it to the database in messages table.
  3. Retrieves all the messages
  4. Displays them in separate lines

Now, let’s make a route

ROUTE

Lets learn how to make a route for our controller.’s process_and_display action

Open root/routes/web.php and add this to the bottom of it:

Route::get(‘show_message’, ‘MessageHandler@process_and_display’);

We are now done with the MVC!

5. Test! and Conclusion

So we have done it all. Lets go to the http://localhost:8000/show_message and see what happens after we refresh the page several times.

Successfully showing the tutorial output
Successfully showing the tutorial output
[jetpack_subscription_form show_only_email_and_button=”true” custom_background_button_color=”undefined” custom_text_button_color=”undefined” submit_button_text=”Dancing BananaSubscribe For More” submit_button_classes=”undefined” show_subscribers_total=”true” ]

You should now review the above steps. Go over the project you created and learn what was done in each step.Read documentation and learn more.

Please let me know in the comments about this post and tell me if there is more I can do. We have now learnt about Installation, Setup and Basic Laravel MVC usage to open a page with intro to the CRUD operations .

android autocomplete camera code codeiginter 3 Codeigniter codeigniter 3 computer vision CSS database education files help helpful how how to HTML HybridIgniter installation java knoppix laravel learn libraries linux mobile mvc open opencv OpenCV4Android PHP plugin project responsive review Review – Web Design WYSIWYG SDK solution touchpad tutorial upload Video web design wordpress WYSIWYG

Categories
Godot Engine Programming

Learn Godot 3 GDScript, Calling an API and parsing JSON

So you think that Godot can’t handle general purpose utility and non-game applications? I am trying to answer this question and this post is part of my attempt to use Godot for apps which are not games at all.

As a web application developer, I have decided that this post should deal with using Godot to call an API on a server and then fetch some JSON data. Afterwards, I will parse the data and maybe print it in the console.

It is expected that:

  • You know what is Godot
  • You have Godot Installed already
  • You have some basic knowledge of Game development and Godot usage. Not like my codeigniter and Android series (RIP maybe?)

So what is Godot Engine? Godot engine is…. well fk it. My last post was in 2016 so I’ll skip the bs.

We are going to use the APIs available at the following links but you can use any JSON dataset of your own choice and your own API end poitns

https://jsonplaceholder.typicode.com/todos

Get All Todo list items https://jsonplaceholder.typicode.com/todos
Get Single Todo list item by user idhttps://jsonplaceholder.typicode.com/todos/{id}
E.g.
https://jsonplaceholder.typicode.com/todos/8

Data looks like
{
“userId”: 1,
“id”: 8,
“title”: “quo adipisci enim quam ut ab”,
“completed”: true
}

With Godot installed, and my API url ready, lets get into action.

So I have a new project with a scene containing nodes like

Nodes in the scene

And the scene itself is organized like this with some poor design choices made to make sure I don’t get lost in the midst of working on this

Just setting up the stage for ladies and gentlemen

Due to lack of talent, I first chose to create a visual script on the button shown above. But then I realized that it was lacking in some HTTPRequest departments so I instead went with GDScript. Otherwise, Visual Scripting is pretty good!

Ich bin ein mann, Der Mann

Attach a GDScript to the Canvas Layer

Save it

Now, we need to connect the following two signals to the CanvasLayer script node. To do this:

  1. Button’s pressed() signal
  2. HTTPrequest’s request_completed( int result, int response_code, PoolStringArray headers, PoolByteArray body ) signal
Steps to connect the signal of Button

Do the same for HTTPRequest’s request_completed( int result, int response_code, PoolStringArray headers, PoolByteArray body ) signal as well.


Now lets edit the code. Click on the Script icon next to the CanvasLayer

Click to start scripting
The auto-generated functions will be used to call API

Lets replace this code with this

extends CanvasLayer

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _on_Button_pressed():
	print("Requesting")
	$HTTPRequest.request("https://jsonplaceholder.typicode.com/todos/8")

func _on_HTTPRequest_request_completed( result, response_code, headers, body ):
	print("Processing the Response")
	var json = JSON.parse(body.get_string_from_utf8())
	print(json.result)

Lets run the program

We are successfully calling the API

But lets up the anti and show this response in RichTextLabel. To do that, we will

  1. Get the values from the JSON response
  2. Show it in the RichTextLabel

So lets update our script and use the following code and run the program.

extends CanvasLayer

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

func _on_Button_pressed():
	print("Requesting")
	$HTTPRequest.request("https://jsonplaceholder.typicode.com/todos/8")

func _on_HTTPRequest_request_completed( result, response_code, headers, body ):
	print("Processing the Response")
	var json = JSON.parse(body.get_string_from_utf8())
	var api_result = (json.result)
	
	# Get the handle of RichTextLabel
	var rtl = get_node("RichTextLabel")
	
	# Clear the RichTextLabel to  avoit clutter
	rtl.clear()
	
	# Concatenate the text of the RichTextLabel on separate lines
	rtl.text += var2str(api_result["userId"]) + "\n"
	rtl.text += var2str(api_result["id"]) + "\n"
	rtl.text += api_result["title"] + "\n"
	rtl.text += var2str(api_result["completed"]) + "\n"
The JSON output is now called, processed (a bit) and shown in the RichTextLabel

So, we did it! In the next post, I will continue this quest and we will look into using headers and secure authentication. Thanks for taking interest. Lets spread the world and learn together.

Join the Godot Engine’s Discord server https://discordapp.com/invite/zH7NUgz

Please do share this post and let me know what more I can do to improve this post and what I can do in the next posts.

Thanks
Codeonion

Categories
Programming

LibGDX Android Studio: Download and set up a new LibGDX Project

Hey fellow developers!

Welcome to the beginning of LibGDX for Android tutorials. In this tutorial, you will learn how to download, setup and create a new LibGDX project in Android Studio.

At the end of this tutorial, you will:

  1. Download LibGDX
  2. Setup LibGDX
  3. Create a new LibGDX project in Android Studio

So lets get Started!


Download LibGDX

First of all, lets download LibGDX. (I am assuming that you already have Android Studio.)

  1. Go to official LibGDX website.
  2. Go to Download
  3. Download (Duh!)
  4. And open the folder

This process is given here

 LibGDX Android Studio - Download

Now, we will setup LibGDX for our project.


Setup LibGDX

Now, we will setup the LibGDX project using the downloaded gdx-setup.java file.

  1. First of all, fill in the basic project information
    1. Run gdx-setup.java
    2. Provide your Project name.
    3. Provide package information according to your settings
    4. Game Class is the java class file name that you will eventually be working with.
    5. Destination is where you will work on your project.
    6. Android SDK is where your Android SDK is installed. Give its path.
  2. Sub-Projects is where you provide the platforms that you wish to support.
    1. Chose Android
      (Only because this is an android based tutorial. But you are not limited to that.)
  3. Extensions is where you tell the setup what extensions to load.
    1. For simplicity, just chose Box2d
      (you can learn more later)
  4. Press Generate
    1. Wait until the download completes.

Here is the screen shot of my completed setup.

This entire process is given below.

 LibGDX Android Studio - Setup

Now, we will open this project in Android Studio


Open in Android Studio

Follow these steps to load the LibGDX project in Android Studio

  1. Open Android Studio
  2. Click Import Project
    • Here is how
  3. Give path to the LibGDX download location (which you provided in setup) and press OK
    • Here is how
  4. Wait till the project is loaded in Android Studio

This entire process is given below:

LibGDX Android Studio - Load project in Android Studio

This is it. You have just loaded LibGDX in Android Studio. Now lets run it in Android Virtual Device 😀


Run LibGDX in Android Virtual Device

Follow these steps to run your new LibGDX project in AVD

  1. Launch your Android Virtual Device (AVD)
  2. Press the Run button in Android Studio
  3. Now, the app will run on your AVD. Done!

This process is given below:

LibGDX Android Studio -Launch app in AVD

This is it. You have just created and run a new LibGDX project in Android Studio.

Lets draw some shapes in the next tutorial.

Return to the LibGDX Tutorials

Categories
Android OpenCV Programming

Use OpenCV to show camera on android App with correct orientation

Return to OpenCV 4 Android Tutorials List

In this series of tutorials, you are learning OpenCV for Android using Android Studio. So far, you have made a working OpenCV Android Studio Project containing OpenCV module.

In Here is the overview of what we are going to achieve:

  • Create an OpenCV for Android Project (As in previous tutorial in this series) (Here)
  • Show Camera on the Screen
    1. Edit Manifest
      1. Add permission to allow camera.
      2. Support various screen sizes and adaptability of camera.
      3. Use specific features of the camera.
    2. Add a custom Layout show_camera.xml to display camera in it.
    3. Edit MainActivity_show_camera.java 
      1. Import required android classes
      2.  Import OpenCV classes
      3. Connect to OpenCV manager
      4. Initiate LogCat to log events of out app
      5. SHOW CAMERA ON LAYOUT
      6. Corrected Orientation (portrait)

Trust me, it is very simple to do. Lets do it!


 

Manifest.xml

We need to edit the AndroidManifest.xml file like following:

  1. Allow permission to use camera
    <uses-permission android:name="android.permission.CAMERA"/>
  2. Allow camera to optimize to the dimensions of the device in use
    <supports-screens android:resizeable="true"
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:anyDensity="true" />
  3. Use Front camera and autofocus of camera :S
     <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"/>

The Manifest.xml file in its entirety is given here

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="opencv.codeonion.com.opencv_test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name=".MainActivity_show_camera"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <supports-screens   android:resizeable="true"
                        android:smallScreens="true"
                        android:normalScreens="true"
                        android:largeScreens="true"
                        android:anyDensity="true" />

    <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"/>

</manifest>

 

This entire process is given here:

Show camera on android App using OpenCV for Android - Edit Manifest

This is all you need to do in AndroidManifest.xml


Create a new layout (show_camera.xml )

Now in your project, do the following:

  1. Create a new layout called show_camera.xml
  2. Add the following code it to:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        xmlns:opencv="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent">
    
        <org.opencv.android.JavaCameraView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            android:id="@+id/show_camera_activity_java_surface_view"
            opencv:show_fps="true"
            opencv:camera_id="any" />
    
    </LinearLayout>

    Note that the JavaCameraView has the id of show_camera_activity_java_surface_view

This is given below:

 


MainActivity_show_camera.java

Import the following Android Classes in your MainActivity_show_camera:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

Import the following OpenCV classes in your MainActivity_show_camera:

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

Now, lets work with the MainActivity_show_camera Class 🙂 (Code in the end). I will explain every line of OpenCV code in detail.

  • Implement the OpenCV class CvCameraViewListener2 to allow OpenCV to communicate with android camera functionalities.
public class MainActivity extends AppCompatActivity implements CvCameraViewListener2 {
  • Declare the following items in the class
    // Used for logging success or failure messages
        private static final String TAG = "OCVSample::Activity";
    
        // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
        private CameraBridgeViewBase mOpenCvCameraView;
    
        // Used in Camera selection from menu (when implemented)
        private boolean              mIsJavaCamera = true;
        private MenuItem             mItemSwitchCamera = null;
    
        // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
        Mat mRgba;
        Mat mRgbaF;
        Mat mRgbaT;
  • Now, lets call OpenCV manager to help our app communicate with android phone to make OpenCV work
    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();
                    } break;
                    default:
                    {
                        super.onManagerConnected(status);
                    } break;
                }
            }
        };
    • CameraBridgeViewBase mOpenCvCameraView
      This variable acts as a bridge between camera and OpenCV library.
    • BaseLoaderCallback mLoaderCallback = …..
      Well, once OpenCV library is loaded, you may want to perform some actions. For example, displaying a success or failure message.
  • Initiate the LogCat
    public MainActivity_show_camera() {
            Log.i(TAG, "Instantiated new " + this.getClass());
        }
  • Now, when the activity is created, display the OpenCV camera in the layout. show_camera.xml.
    @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.show_camera);
    
            mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);
    
            mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    
            mOpenCvCameraView.setCvCameraViewListener(this);
        }
  •  The following three functions handle the events when the app is Paused, Resumed and Closed/Destroyed
    @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_0_0, this, mLoaderCallback);
            } else {
                Log.d(TAG, "OpenCV library found inside package. Using it!");
                mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
            }
        }
    
        public void onDestroy() {
            super.onDestroy();
            if (mOpenCvCameraView != null)
                mOpenCvCameraView.disableView();
        }
  • Now, we will do two main things:
    • Receive Image Data when the camera preview starts on your screen 😀
      public void onCameraViewStarted(int width, int height) {
      
              mRgba = new Mat(height, width, CvType.CV_8UC4);
              mRgbaF = new Mat(height, width, CvType.CV_8UC4);
              mRgbaT = new Mat(width, width, CvType.CV_8UC4);
          }
    • Destroy image data when you stop camera preview on your phone screen
      public void onCameraViewStopped() {
              mRgba.release();
          }
    • Now, this one is interesting! OpenCV orients the camera to left by 90 degrees. So if the app is in portrait more, camera will be in -90 or 270 degrees orientation. We fix that in the next and the most important function. There you go!
          public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
      
              // TODO Auto-generated method stub
              mRgba = inputFrame.rgba();
              // Rotate mRgba 90 degrees
              Core.transpose(mRgba, mRgbaT);
              Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
              Core.flip(mRgbaF, mRgba, 1 );
      
              return mRgba; // This function must return
          }

The entire code is given below:

package opencv.codeonion.com.opencv_test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.WindowManager;

import org.opencv.android.JavaCameraView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

// OpenCV Classes

public class MainActivity_show_camera extends AppCompatActivity implements CvCameraViewListener2 {

    // Used for logging success or failure messages
    private static final String TAG = "OCVSample::Activity";

    // Loads camera view of OpenCV for us to use. This lets us see using OpenCV
    private CameraBridgeViewBase mOpenCvCameraView;

    // Used in Camera selection from menu (when implemented)
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    // These variables are used (at the moment) to fix camera orientation from 270degree to 0degree
    Mat mRgba;
    Mat mRgbaF;
    Mat mRgbaT;

    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();
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    public MainActivity_show_camera() {
        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.show_camera);

        mOpenCvCameraView = (JavaCameraView) findViewById(R.id.show_camera_activity_java_surface_view);

        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_0_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    public void onCameraViewStarted(int width, int height) {

        mRgba = new Mat(height, width, CvType.CV_8UC4);
        mRgbaF = new Mat(height, width, CvType.CV_8UC4);
        mRgbaT = new Mat(width, width, CvType.CV_8UC4);
    }

    public void onCameraViewStopped() {
        mRgba.release();
    }

    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

        // TODO Auto-generated method stub
        mRgba = inputFrame.rgba();
        // Rotate mRgba 90 degrees
        Core.transpose(mRgba, mRgbaT);
        Imgproc.resize(mRgbaT, mRgbaF, mRgbaF.size(), 0,0, 0);
        Core.flip(mRgbaF, mRgba, 1 );

        return mRgba; // This function must return
    }
}

The entire process of editing MainActivity_show_camera.java is shown here:

Show camera on android App using OpenCV for Android - MainActivity_show_camera


Note: The camera disorientation problem is a bitch an issue not to be takien lightheartedly. Thanks for noting.

This concludes this tutorial, now that you have created a camera app, it is now time to continue this and perform more Computer Vision! In the next tutorial, I will draw a simple object on the screen. Be sure to check out the list of OpenCV for Android tutorials for latest tutorials.

Thanks for reading, and please share and comment if this helped and to share your ideas and opinions.

Return to OpenCV 4 Android Tutorials List

Categories
Programming

Update Knoppix 7.6 from Terminal

So you downloaded Knoppix and realized that it is a little bit rusty. There is a way to make it fresh and update all the packages with two simple commands.

First you need to Refresh the packages database. Go to terminal and type the following command and press enter.

sudo apt-get update

 

This will initiate an activity on the terminal that will download the latest packages information. This will take a few minutes. After the activity finishes, you will have the latest packages information. This is time to Upgrade the packages that are already installed in your Knoppix system to the latest versions that are available in online repositories.

Simply, type in the following command in terminal:

sudo apt-get upgrade

 

This will initiate a download activity on your terminal that will download all the upgradable packages from online repositories. This will take longer than the “update” activity.

At the end, you will have the latest packages installed and you will be running smooth!

 

Categories
Android OpenCV Programming

Creating a new OpenCV project in Android Studio

Return to OpenCV for Android Tutorials List

In this tutorial, we will create a new OpenCV project in Android Studio. Since you have everything downloaded already, we are ready to move on. By the end of this tutorial, you will have a new project set up, which you can use to build your projects upon. So lets do some CV!

Note: This tutorial has been tested on Android Studio 1.5 and 2.0

In short, the steps are, (2) Create simple project. (3) Import OpenCV SDK as a Module in Android Studio. (4) Set OpenCV Version. in Project (5) Fix Library association in project. (6) Done! Now actual OpenCV code can be written in future. The longer and detailed guided tutorial is given below.

  1. I beg you to open Android studio.
  2. Create a new project
    • I named it “OpenCV_Test”. (It could be different in the following GIF)
    • Minimum SDK is “API 19: Android 4.4 (KitKat).
    • Default Activity is “Basic Activity” (easily changeable later on)
    • Activity name is “MainActivity” (i.e. default settings)
    • I have shown the entire process in this GIF.
      Android-Studio-Create-New-Project
    • After pressing Finish, Gradle will perform some processes and eventually, you will be presented with your Android project.
    • Now, we can start importing OpenCV into the project.
  3. Import the OpenCV for Android SDK module in Android Studio.
    • To import the OpenCV SDK as a module in your project, go to File>New>Import Module.
    • Then Give path to your OpenCV as ..\OpenCV-android-sdk\sdk\java
    • You can chose to modify your module’s name.
    • Press Next and Finish the Dialogue.
    • The entire process is given here:
      OpenCV-Android-Import-Module-Android-Studio
    • Note that in the end, there are some errors in the code as well as the console. This is because you need to fix the Version number and link the libraries with your own project. This is shown in the next two steps.
  4. In this step, we will fix the Android Project SDK information in the OpenCV build.gradle file.
    • In project explorer, switch to Project view.
    • Go to OpenCVLibrary300 > build.gradle file and open it.
      • I have updated the contents of the file with the following code
        apply plugin: 'com.android.library'
        
        android {
            compileSdkVersion 23
            buildToolsVersion "23.0.2"
        
            defaultConfig {
                minSdkVersion 19
                targetSdkVersion 23
            }
        
            buildTypes {
                release {
                    minifyEnabled false
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
                }
            }
        }
      • Note that the android project’s SDK information can be obtained from the project’s own build.gradle file.
    • Once the Android SDK settings are updated, press “Try Again” button.
    • This entire process is given below:
      OpenCV-Android-Update-DefaultProject-SDK-Information
    • Now. we need to fix library association.
  5. Looking good so far! We now need to make sure that the OpenCV for Android libraries are associated with our Android Studio project. Currently, Android Studio will not recognize the OpenCV code that we type in our files. We fix this as follows.
    • Go to File>Project Structure.
    • When window opens, under Modules, select app.
    • Click Dependencies.
    • Click +.
    • Select Module Dependencies.
    • (In my case) Select :openCVLibrary300.
    • Press Ok and Ok.
    • After a few seconds, the libraries will be associated with your Android project.
    • This entire process is shown here:
      OpenCV-SDK-library-association
    • You can now write more OpenCV code in future in the same project.
  6. We did it! Project is ready for future OpenCV development.

This concludes this tutorial. You are now ready to start making your own Android Studio Project that consists of OpenCV SDK features limited only by your imagination. In the next tutorial, I will SHOW CAMERA on android app screen using OpenCV. Make sure that you read it. Do not forget to SHARE this post and write your opinions, ideas and views  in the  COMMENT  section below.

Thanks for reading :). Please like my Facebook page and follow my Twitter for more tutorials.

Return to OpenCV for Android Tutorials List

Categories
Android OpenCV Programming

Learning the Packages of OpenCV SDK for Android

Return to OpenCV for Android Tutorials List

In the previous tutorial, you learnt about the file structure of OpenCV SDK for Android. Now, we will learn the packages which are available for us to use in OpenCV SDK for Android. At the end of this tutorial, you will definitely know what OpenCV for android has to offer.

Each package is imported like this:

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;

Each packages has java classes which contain functions which you use.

First of all, lets find the packages in the sdk folder manually. On your computer, once you have downloaded the OpenCV SDK, you can browse to the following address in order to find all the OpenCV for Android classes.

OpenCV-android-sdk\sdk\java\src\org\opencv

There, you will find the following packages (OpenCV 3.0):

Also, when you have created an OpenCV project in Android Studio, you will find the packages in the project browser like this:

Now, I will explain to you the purpose of each and every package so that you learn about OpenCV without any effort :D. You won’t regret coming on my blog 🙂

Note that each package can be imported like this as I told before:

import org.opencv.android.BaseLoaderCallback;
Package  Name Purpose Description
android OpenCV interaction with Android platform This package has functions which can allow you to implement an OpenCV project in your Android device. This package handles interactions between OpenCV and Your phone.
calib3d  Project 3D coordinates of objects in a scene. “calib3d” stands for Camera Calibration and 3D Reconstruction. This package has functions which can determine 3D coordinates of objects. So lets say you have a box in a picture. calib3D functions can project 3D coordinates of that box if you provide “intrinsic” and “extrinsic” coordinates.

There are functions to estimate intrinsic and extrinsic parameters 🙂

core Brain of OpenCV. Does all what OpenCV does elsewhere.  “core” is the core package of OpenCV. This package contains functions which provide the base functionality of OpenCV. This include mathematical and matrix operations, algorithmic procedures and much more.

This library is not responsible for image processing. That library is called “imgproc” and it is discussed below.

engine  Provides basic information about current OpenCV SDK installation in your project  Basically, if in your project, you wish to obrain basic information about your OpenCV SDK such as  its packages, version, SDK path, and list of libraries.

Moreover, you can specify a specific version of OpenCV that user’s phone should download from play store. Pretty cool, right?

features2d  Detect and track features in a a 2D test image/frame  You will use this library to detect features, draw them and track them on the screen.
imgcodecs  Read/write images from your disc  Well, imagine you wish to work on an image that is in your disk instead of receiving it from camera. In this case, you will use this library. Its functions allow you to do the following:

  • Read single image
  • Read multiple images
  • Write an image (output)
  • Read specific formats of images in different ways to suit your project and purpose (encode/decode)
imgproc  Image Processing. DUH!  Whether you have loaded an image, or are using camera as input, you will be needing OpenCV to process the image. Well, “imgproc” is the library that has all the functions that you can use, manipulate and exploit to your liking.

This library has functions and classes which allow you to blur image, draw shapes, compare shapes, write text on image, apply enhancement functions and much, much, much more!

This library also has functions which detect points of interest of your liking.

ml  Machine Learning (Artificial Intelligence)  You can train OpenCV to do do Computer Vision according to your requirements. All you need to do is to teach it.

This library has classes and functions that train OpenCV to perform computer vision job for you 🙂

 

objdetect  Detect features or an object  This library has functions that give you the ability to implement detection of a specific custom-defined object in an image or camera feed.

Ever heard of Haar like feature detection? You can do that in this library.

photo  Image Enhancement  This library handles Image enhancement.

Want to set ISO? Exposure setting? contrast? Saturation? hue? Shit? Well, this library has all these functionalities and much more! You can calibrate so much.

One interesting feature is de-noising which will let you play with noise in your image ;D. Useful, right?

utils  Compatibility converters to support different formats of data This library has functions that convert image data from one mathematical format into another. For example, you can convert from one matrix format into another for image processing using a specifically designed code. It is a life saver.
video  Video Processing  This library will help you to perform video processing. You can track objects in a video, subtract background, apply video filters and much more.
videoio  Interact with video files  Using this library, you can open video files, open different format of video files and work with them.

 

This tutorial was brief and was supposed to give you the starting knowledge in order to grow your knowledge about OpenCV by yourself. Let me know in the comments what you think. I will be glad to answer. Now proceed to hte next tutorial 🙂

Return to OpenCV for Android Tutorials List

Categories
Android OpenCV Programming

OpenCV SDK for Android File Structure

Return to OpenCV for Android Tutorials List

In this tutorial, you will learn about the file structure of OpenCV SDK for Android. The information here is very short and lacks details. My purpose here is to provide just enough information to get going with the rest of the tutorials. I highly recommend reading more about the folders, algorithms, libraries and classes on your own.

OpenCV-for-Android-filestructure

So you have downloaded SDK but you may be curious what the SDK files do. Lets see to that now. You can skip this tutorial if you are interested in going directly to the development.

When you extract the “OpenCV-3.0.0-android-sdk-1.zip” from the precious tutorial, you will get a folder /OpenCV-android-sdk/.

Inside the /OpenCV-android-sdk/ folder, you will see:

  • /apk/
  • /samples/
  • /sdk/
  • LICENSE
  • README.android

Lets look at these in detail.

OpenCV for Android SDK file structure
OpenCV for Android SDK file structure

S.No
Name
Description

1

/apk/ This folder contains OpenCV manager API for different android device architectures. Chose the .apk file which is supported by your android device. Or simply download one from Google Play Store because that way, you will be downloading the apk file that is supported by your device/

2

/samples/ This folder contains sample android apps that you can install into your android device to test features of OpenCV. Also note that the source code of each sample is included in the /samples/ folder. It is a good place to start.

3

/sdk/ THE BRAINS OF OpenCV is here. I will explain about this folder below.

4

LICENSE Well, it can’t be said more precisely than what is written there as “By downloading, copying, installing or using the software you agree to this license.If you do not agree to this license, do not download, install,

copy or use the software.”

5

README.android Contains a link to online documentation, resources and feedback. Quiet handy!

http://opencv.org/platforms/android.html

Now that the root file structure of OpenCV is out of the way, we can now take a look at the SDK folder contents to give you the idea of what exactly what it and its contents do.

The /sdk/ folder contains the OpenCV API and libraries that will be used in your android project. You need these to perform all the functionalities that OpenCV offers in order to help you perform your Computer Vision related job.

Inside the SDK folder, in my case, there are three folders:

  1. /sdk/etc/
  2. /sdk/java/
  3. /sdk/native/

Lets look at the contents of SDK folder here:

S.No Name Description
1 /sdk/etc/ This folder contains the “memory” of OpenCV. Memory being like the brain-memory :D. See, as the time passed, the geniuses who made OpenCV for us to feast upon collected data and fine-tuned it for algorithms to use. That data is kept here.

For example, face detection requires some data which is compared with the picture snapped by your x-megapixel camera. That data is kept inside this folder.

2 /sdk/etc/haarcascades HAAR or HAAR-like-features is a folder where you put post-OpenCV-training data.

 

In this folder, you can find data files which contain data generated by training OpenCV in order to detect face, eyes, nose etc detection.

 

You too can create such data files if you wish to detect something such as legs, airplane, cracks on wall (edge detection), pacman, ****, *******, *******888*88* detection 😛

 

Lets say you wish to train OpenCV to detect face of a “sick” person. So you take pictures of a (e.g.) 1000 sick people (positive images) and then resize those picture to a same small size that is easy to process in bulk :D. Now you will also need pictures of people who are NOT sick.  Now, you will train OpenCV on that load of 1000 pictures plus the people who are not sick. This data is put in this folder to be used.

 

HAAR algorithm is very accurate but is slower as compared to LBP.

3 /sdk/etc/lbpcascades LBP stands for local binary pattern. This method is unique in a way that instead of using generated data to detect features (as was the case of HAAR), the LBP takes a pixel and finds the intensity of its neighbor pixels.

 

So lets say there is a pixel. Practically, each pixel has eight neighbor pixels, so our pixel also has eight surrounding pixels. Now, for each pixel, a binary value is obtained. The value of binary number depends on the comparison between the center pixel and its test-neighbor pixel.

 

If pixel intensity is greater than center pixel, then value is 1.

If pixel intensity is lesser than center pixel, then value is 0.

 

LBP algorithm is very fast, but least accurate.

4 /java/ When creating a new Android project, you can import the OpenCV Java Api from this folder.
5 /java/.settings Contains settings that are implemented when importing the OpenCV for android Java API.
6 /java/gen Contains generated files. For example, R.java, when generated is put here.
7 /java/javadoc This folder contains the documentation of OpenCV for Android. In my case, it is the documentation for the version 3.0.0

All the classes of OpenCV for Android are explained here. So if you ever find yourself in trouble, or wish to learn more, visit this folder.

8 /java/res Standard Android project folder that contains resources to be used in an android project. The resource file that came in my case contains camera information.
9 /java/src The /etc/ folder was the memory of OpenCV. But this folder is the actual brain of OpenCV. This folder contains the classes that perform all the functionalities of OpenCV in Android. Classes are written in Java.

 

Root files are self explainatory. If not, then what on Earth are you doing on this post? You should learn Android and then come here.

10 /java/src/org/opencv Exactly this folder contains the classes. Core, mathematical operation algorithm, training and all the shit that OpenCV gets done for you, is actually here. Every improvement in OpenCV is included here. Please respect the contents of this folder if you use OpenCV.
11 /native/ This folder contains C++ .h (header) files and native libraries for multiple android architectures.

This is it for this tutorial. I have explained to you the structure of the OpenCV for Android SDK file structure. In the next tutorial, I will explin to you about the classes available in OpenCV for Android SDK which you can use.

Return to OpenCV for Android Tutorials List

Categories
Android OpenCV Programming

OpenCV for Android: Download Required Software

Return to OpenCV for Android Tutorials List

In this tutorial, you will learn which tools to download for creating your OpenCV project in Android Studio if you follow this tutorial series 🙂

  1. Download and install Android Studio from HERE. Make sure that it is working.
  2. Download  OpenCV for Android SDK from HERE.
    • Demonstration of SDK download.

      OpenCV for Android Download-Required Software
      OpenCV for Android Download-Required Software
  3. Basically, after downloading the SDK, simply extract it on a folder and it will be ready for usage.
  4. That’s it! You have downloaded the OpenCV for Android SDK.

In the next tutorial, you will make a new project and set it up so that your application is ready to OpenCV!

Return to OpenCV for Android Tutorials List