Friday, 27 November 2015

Write a MATLAB script to perform thresholding

SOURCE CODE



OUTPUT



Thursday, 26 November 2015

MATLAB Code to perform Grayscale slicing , preserving the background

SOURCE CODE



OUTPUT


Please note , You can choose , any range for the slicing .
It is totally dependent on what application you will use this method for pre processing .

Though i have carefully added comments to make the code more readable  ,  it is highly recommended that you follow a standard text book and read the concepts before attempting to go through all these examples and code snippets .

** If there are any questions , suggestions regarding the code , then do leave them as comments**

Write a MATLAB script to Demonstrate BitPlane slicing and Perform Reconstruction

SOURCE CODE



OUTPUT


Write a Matlab Script to Obtain a Negative Image

SOURCE CODE

OUTPUT


Thursday, 19 November 2015

Implementing Median Blur using MATLAB , without using medfilt2() .

To read about the basics of median blur , click here. 


SOURCE CODE: 



OUTPUT:


** If you can suggest any optimisations , or useful changes to the given code , then do leave your valuable suggestions as comments .

Thursday, 12 November 2015

Calculating Histogram of an Image in MATLAB ( without using inbuilt functions)


Write a MATLAB script to calculate and plot a histogram of a given image .

 

**Check the plotted histogram  vs the Histogram created using imhist().
**If both the histograms look similar , then the code is correct. 

**The first step for calculating a histogram will be finding out the gray image of the input image .
Try to do this also using custom code and not use rgb2gray()

OUTPUT




Feel free to download and use this code.



** For those who do not have access to MATLAB ( extremely expensive  !!! ) ,  i will be releasing similar code in OpenCV soon . **

If you can suggest any optimisations , or useful changes to the given code , then do leave your valuable suggestions as comments .

Custom Average Blur using MATLAB (without the use of inbuilt functions )

QUESTION :

Write a script in MATLAB to perform an average blur without using any inbuilt function


OUTPUT


Try the average blur with a 5*5 kernel .
The Method will be the same , the only change will be that the amount of blurring will be increased .
So on increasing the size of the kernel will result in increased blurring .

There is a lot of material on the basics of masking on the web .
Go through them to understand what the mask will be and why the kernel is a square matrix of of size 3*3 , 5*5 , 7*7 and not 2*2 or 4*4 .  Try to figure out the reason for having a zero padding as well .

** For those who do not have access to MATLAB ( extremely expensive  !!! ) ,  i will be releasing similar code in OpenCV soon . **

Monday, 2 March 2015

SQL For Beginners : Assignment 1

(Note : The following assignments have been done using Oracle 10G )


** Try to code along , for a better understanding . **
I hope you guys like this post .
In case of any doubts or queries , please do leave your comments behind .
If you want a video demonstration of this , please do mention that in the comments as well .

Sunday, 2 November 2014

Data Structures and Algorithm programs in C




I hope you guys like this post .
In case of any doubts or queries , please do leave your comments behind .

Friday, 31 October 2014

Threads safety reality check

Okay, now this post is dedicated to those who have just begun reading about threads and processes in java. There is a very simple and interesting code that follows , which demonstrates the synchronization problem with threads.
Before continuing to the next section ,you should be really clear about what threads are , how they work and how the operating system schedules the threads .
For a recap, threads in java can be created in 2 ways :

  1. implementing the Runnable interface
  2. extending the Thread class
Now here is the case :

  • Let us suppose that there is a joint account in a bank and the joint account is accessible by Mr.X and Mr.Y. 
  • Now the available balance in the account is 400$
  • The withdrawal can only be done if Current account balance is greater than the withdrawal amount.
  • Here Mr.X first withdraws some money using 1 thread and then Mr.B withdraws some money using another thread.

**Now please do compile and run the program yourself to see what the output is .
I am sure that you will be surprised on getting the output .


PROGRAM DESCRIPTION :

An Account class is created and a static member curr_bal is initialized to 400 . A withdraw() is used for withdrawing from the account .
Two threads namely Thread1 and Thread2 are run .Basically the 2 joint account holders use these threads to carry out their transactions.




OUTPUT :

** Spend a moment thinking what just happened , before reading the discussions section.
Basically you should be asking yourself ,that firstly how was the second thread even allowed to do a transaction since the condition (current balance > withdrawal amount ) would not be met after the first thread completes transaction ,as the current balance would then become 100.
(300$ + 200$=500$ total ) was deducted from 400$ ...leaving to negative balance . How on earth did we have a negative balance !!!
DISCUSSIONS:

Now if you are very new to threads, you will be racking your brains over this , and it is very much desired ,that you think over this as its only that when you face a problem , that you search looking for a solution .
Now isn't the problem here a grave one ? Just try to imagine how much losses would a bank incur if the programmers coded in the similar fashion and the amount was billions of dollars . Surely makes an impact right ? .

Ok so now getting straight to the point . What basically happens here that you have 2 threads accessing the same resource that is CURRENT BALANCE . Why do we use threads in the first place ? CONCURRENCY !! . Imagine a net banking system managed by some bank . Now if you didnt have a concurrent solution then all your customers would be queuing up to complete their transactions one after another and if one was transaction messed up , the entire queue of customers would have to wait the entire time . We use threads in such scenario so that several customers can operate at the same time using the same portal .

Coming back to the point . Concurrency along with its advantage has some disadvantages . Here
the first thread is started first.and it tries to make the withdrawal .... the condition (curr_bal>amt) is fulfilled , so it enters the block .Now come the catch . This thread is then made to sleep for 1000ms(1 sec) i.e the thread stays inactive basically during the sleep time .

So the balance  is not yet updated and adjusted and the withdrawal is yet not complete . what happens now is that , while the first thread is sleeping ,the second thread tried to make the withdrawal. now again the condition checking is performed (curr_bal> amt) . THIS IS TRUE AGAIN !! because the thread1 hasn't yet woken up and updated the new current balance . So Thread2 gets passed the condition and now the Thread1 wakes up and at the same time Thread2 is put to sleep .
Now the deductions takes place one after another and the final balance that shows up is -100.
Well done BANK !! you've hired the worlds best programmers to GIVE YOU GOOD LOSS .
Hire me instead lol :P .

In case of any doubts , make use of the comments section .
If you have enjoyed reading , you can contribute by typing in your valuable feedback .


Friday, 10 October 2014

Mini Voice controlled Home Automation project : Arduino uno R3 + bluetooth module + Android app

Project video :


Pictures:




Requirements :

  • Arduino uno r3 board ( a clone or any other variant will do fine )
  • Jumper / connecting wires
  • Bluetooth Module (HC-06) : ** the default password is 1234 **
  • 1k resistors - 2 
  • Red Led + Blue Led ( you can use any other colour , but make necessary changes in the program )

Sketch :

** See the diagram very carefully 

SOURCE CODE:

  fff
** Please Note : Before you upload the sketch to the Arduino , disconnect the wires hooked onto the TX and RX pins of the arduino . Then upload the sketch , and connect the wires back again .

The Final Lap :

Now you have finished wiring up the circuit , and also the code has been uploaded . You can see your Bluetooth module blinking already . 
The final step is to use the android app to connect to your Bluetooth module and control the Led's .
The app you are going to use here is already available in the play store . The name is BT voice control for arduino . Use this app to first search your Bluetooth module and then connect to it , using the default passcode 1234. 
** You can also make your own android application to connect to this project . For simplicity sake I have used this app, you can make your own using MIT appinventor 2 or Eclipse .**
The voice commands i have used here are :
  1. Turn both on 
  2. Turn both off
  3. Switch red light on
  4. Switch red light off 
  5. Switch blue light on 
  6. Switch blue light off
Your automation project will not function if you say something else . In case you want to make modification of what you wish to say to control a specific function ; fiddle with the strings entered in the source code .
------------------------------------------------------------------------------------------------------------------------
If you have benefited from this blog post , then please subscribe and hit the like button. 
Trust me guys , this helps a lot . 
In case you have any doubts / queries or you need specific help , then make use of the comments section or reach me at : shrobon.biswas@gmail.com

Saturday, 4 October 2014

Python Threads made easy

Up and running with python threads:
I have taken the pain to write this blog post, as i clearly understand how intimidating it is for a beginner to work with threads in python. I have had an experience no different, when i started picking up python.

In python you can work with threads by using these two modules :
1. thread (deprecated )
2.threading

Implementations :

i am definitely not going to bore you with too much theory . Lets quickly jump into an example .

a.  Creating threads using the thread module 


Problem Statement :
Create 2 threads named FIRST THREAD & SECOND THREAD using the thread module in python.Both threads use a function func() which accepts thread name and delay time as parameter .
Now iterate each thread 5 times and within the loop print the following information
1. iteration number
2. thread name
3. current system time

Each iteration of the thread should be delayed for a particular time interval.
Consider delay =3 for  FIRST THREAD and delay =5 for SECOND THREAD.


Please do read the above code thoroughly before proceeding
OUTPUT :

  
  ** output on your system might be different from the output that i obtained.

did you notice any peculiarity in the output pattern ? ?
if you did not , then match the output with the code again .
What you will observe is that the line 
print("******** All the tasks have finished executing *****") has been printed first ,when it was supposed to be printed after the threads finished executing, right ? 
This does not happen as the functions of starting both the threads are happening concurrently . The proof is the overlapping output sequence .
It is not that first the FIRST THREAD will finish and then the next will start, but both of them are happening concurrently.Here the main program is also another thread , so the line print("******** All the tasks have finished executing *****")happens and gets printed without waiting for the other threads to complete. All the threads work asynchronously on their own .

b. Creating threads using the threading module 

Now having worked with the thread module , you see that there are a lot of limitations . You cannot wait till all the threads have finished executing and then print some completion message . The threading module is comparatively new and has a lot more features .

 Now let us consider the last problem only for simplicity sake and implement it using the threading module .

The slight difference you notice in this code is that we have used the functions start() and join(). Now the start() is similar to start_new_thread() while the join() is a kind of a wait funtion. The t1.join() stops the main program i.e the main thread to continue its execution of t1 is complete , same is the case with t2.

Now lets observe the output


now do you notice print("******** All the tasks have finished executing *****")
gets printed only after all the jobs are complete ? . This was accomplished using  join() .


for further readings do look up the official documentation at python.org .

**Now There is a bad boy in this program that affects the system performance drastically while the program is executing :

Here is the video .
 
if you have any doubts regarding this post , or if you want me to create posts on certain topics , then please do leave it in the comments section .





Monday, 18 August 2014

ARDUINO Burglar Alarm Using Infrared Emitter-Detector pair

Basic Idea:




In this tutorial i will show you , how to make a simple Inexpensive Intrusion Detection(Burglar alarm) using an Arduino Uno board . This project uses the Infrared Emitter-Detector pair to detect intrusion and triggers an alarm as soon as the object crosses the infrared field .
** To see a Similar Project Made with an LDR  click here
REQUIREMENTS :


  1. Arduino uno R3
  2. Breadboard
  3. Connecting wires / Jumper cables
  4. Infrared Emitter and Detector pair LED(not the sensor module) 
  5. PCB mount BUZZER
  6. 1kohm Resistor 
  7. 10kohm Potentiometer
** the white LED is the Infrared emitter ,While the black is the Infrared Detector .

CIRCUIT DIAGRAM :



SOURCE CODE:



DISCUSSIONS:
First build the circuit according to the circuit diagram provided .
Now i will explain to you how the circuit works .

  • The white Led you see in the pictures is an Infrared Emitter . You power it on like a normal LED . 
  • Now if this is your first time with an IR Led , its very common that you'll mistake your LED to be spoiled as you wont find it glowing ,but that isn't the case really . 
  • Infrared light is out of the visible spectrum range so even if it is glowing , you wont be able to see it with naked eyes .
  •  To see if your emitter LED(White) is working properly : switch on your cell phone camera and see the LED through it , you will see that there is a purple Glow . 
  • This ensures that your IR emitter (White ) is working perfectly and it is emitting light of a particular range of frequency . 
  • Now lets come to the Black LED . The back LED is the IR detector. 
  • The reason that it is made black is that Black color has the highest absorption ; so it Absorbs most of the infrared light Emitted by the Emitter . 
  • Now what happens if an object stands in between the Emitter and the detector ?? . OBVIOUSLY the amount of infrared radiations intercepted by the detector will now be lesser due to the obstruction .
  • This is the catch !! . When such a situation occurs , I trigger the alarm to denote Intrusion . 


Now that you've got your concept right , LETS FOCUS ON THE CODE . 

  • In line 10 we begin the serial communication to see the values being intercepted on the serial monitor 
  • for both the cases  i.e  
  • case 1.) no obstruction in the path of the emitter and the detector . 
  • case 2.)obstruction in the path of the emitter and the detector .
  • for both these cases , we have to observe the values being reflected on the serial monitor , based on which we will decide for which value being exceeded we will be triggering the alarm .
  • Note that for my experiment the threshold value was set to 1005 . This might not be the case for you. 
  • Hence try to monitor the values that you are intercepting and choose your threshold accordingly .

Well , hope I have covered all the concepts in detail regarding this project . If you face problems or if you need further detailing on any sub-topic , then please do leave me a comment .

PROJECT VIDEO:








Saturday, 16 August 2014

Grab Alarm

Basic idea :


This small project will teach you, how to make a simple Grab alarm using an LDR ( light dependent resistor).
When you try to move your hand over the LDR, there is a loud alarm that goes on , and the alarm turns off as soon as you move your hand away from the LDR. The LDR works on the following principle " WHEN LIGHT FALLING ON THE LDR IS HIGH;RESISTANCE IS LOW ." and vice-versa. Basically for an LDR , light is inversely proportional to the Resistance.

Requirements :

  1. LDR ( you can choose any variant ), these come in various sizes ,usually based on the size of the area on which the light falls.
  2. Piezo buzzer (PCB MOUNT).
  3. Resistor (220ohm /1kohm)
  4. Connecting wires or Jumper cables
  5. Arduino UNO R3
  6. USB cable 
  7. Breadboard
Procedure:

   1.   Connect one terminal of the piezo buzzer to Digital pin 9(you can choose and PWM enabled pin) , and          connect the other terminal to ground . Your buzzer connection is now complete.

   2.  Now make the connections like this :
   
        the black wire goes to ground
        the green wire goes to pin A0 on the Arduino
        the red wire goes to the 5v pin on the Arduino

Connections Sketch:


Schematics :





Source Code:
Discussion:


  1. I have used ldrval variable to store the value being sent by the LRD connected to the arduino
  2. The value is then printed on the serial monitor . This following part is very crucial .
  3. After you have fully connected your circuit , you should upload your sketch to the arduino and then open the Serial monitor from the tools section on your arduino platform .
  4. If your sketch is working properly then it should send back some values to your serial monitor .
  5. Try to place your hand closer to the serial monitor and observe the readings changing . 
  6. In this manner you have to decide what your threshold value will be ; crossing which your buzzer will start.In my case ,this value was 900. Try to play around with this value , as this decides the sensitivity of the Alarm going on.
  7. See the source code line 28 : you can also play around with the value . In my case i put it to 170 . You can use values ranging from 0-255 , where 0 represents off . 
Picture of the Serial Monitor :

Grab Alarm Project Video:






Tuesday, 12 August 2014

Selection Sort

Complexity :

Best case: O(n^2)
average case:O(n^2)
Worst Case: O(n^2)

Technique :

  1. we first select the ith(for the first iteration i=0) element of the array and assume it to be the smallest 
  2. next we traverse from the i+1 position to the end of the array using the smallest function to find the position of the smallest element and we return its position .
  3. then the current value and the smallest value are compared and swapped.
  4. this entire process continues till the array is completely sorted. 


**Basically what happens is , in every iteration the smallest element element in the array is placed in its proper position.

Source code:


Output :




**the code given above can be sufficiently tweaked . i have purposely made it a bit more lengthy for clarity sake .


Saturday, 2 August 2014

Insertion Sort

Insertion sort is a very simple sorting algorithm which the sorted array is built one element at a time.
The main advantage of insertion sort is that it can efficiently be implemented on data set that are already substantially sorted .
For insertion sort the best case occurs when the array is already sorted ; while the worst case happens when the array is sorted in the reverse order.
Best case :O(n)
Worst case :O(n^2)

Technique:

  1. We first divide the array to be sorted into two sets.One that stores the sorted value while the other stores unsorted values.
  2. The sorting algorithm proceeds until there are elements in the unsorted set.
  3. Initially we take the first element of the array (index 0)to be in the sorted set while the rest of the elements are in the unsorted set.
  4. During each iteration of the algorithm, the first element in the unsorted set is picked up and inserted into the correct position of the sorted set. 

Source code :




Output:


Complexity:

The number of comparisons of elements in the worst case is
  (N-1) + (N-2) + ... + 1
= (N-1)*N/2
i.e. O(N2).

The average case time-complexity is O((N-1)*N/4), i.e. O(N2).
The best-case time complexity is when the array is already sorted, and is O(N).


Friday, 1 August 2014

Inheritance and constructors

Inheritance is the process by which objects of one class can acquire the properties of objects of another class.In java one class implements the properties(not private) of another class by using the keyword "extends".

Types of inheritance possible :

  1. Single / simple inhertance
  2. Multiple inheritance 
  3. Hierarchical inheritance 
  4. Multi-level inheritance
In java it is not possible to implement Multiple inheritance directly .

What is a constructor ? 

A constructor is a special type of a function which is used to initialize the instance variables .
A constructor has the following properties

1> it has to have the same name as that of the class 
2.>it does not have a return type , not even void
3.>A constructor can only be called when an object is created .It cannot be called separately unlike                    functions.
** The first line in the calling of a constructor is a call to its super class constructor .

Constructors can be of two types: 
  1. Default constructor 
  2. User-defined constructor 

In case we forget to write any constructor for a class , the compiler during compilation adds a default constructor to the program automatically.
But if we have written a constructor explicitly then the compiler does not add the default constructor .

Constructor Chaining :

Calling one constructor from another constructor is called constructor chaining .
Constructor chaining only works if the classes of which the constructors are being called are the super class i.e the classes involved (Inheritance structure should be present ).

See the following example to understand more clearly


Try to understand the flow of the program .


  1. in line 44 the object is created and the parameterised constructor sub2 is called .
  2. in line 30, the arguments sent from line 15 are received and the call on line 32 sends the control to line 20.
  3. in line 20, the arguments sent from line 32 are received and the call on line 22 sends the control to line5.
  4. here x,y get initialized with the values 10 and 20 that were sent in line 44.
  5. next the control passes to line 23 . Here z gets initialized with 30 (because 'w' received 30 from the caller)
  6. next the control passes to line 33 . Here a,b,c, gets initialized with 40,50,60 .
  7. now the control returns to line 45. where the value stored in x declared in class Inheritance is stored in x of class test.
  8. since data of another class cannot be accessed directly (security feature of java) . An object of that class was created and was used to access Inheritance class's data x through it.

Tuesday, 29 July 2014

Bubble Sorting

The word sorting means arranging items(elements of an array) in a pattern , basically ascending ,descending or alphabetically.
In Bubble sorting algorithm , consecutive adjacent pairs of elements in an array are compared with each other. Now, if we want to sort in an ascending order , we check if the element in the lower index is greater than the element of the higher index. If yes,then the elements are  interchanged,so that the smaller element is placed before the bigger one. If know then we iterate for the the next consecutive pair .

Java source code :


The output :


















Complexity : 
Please note that the complexity of any sorting algorithm depends on the number of comparisons made.
By comparisons, here i am referring to the if check condition on line 23 .

for i=0 ; number of comparisons in j = n-1
for i=1 ; number of comparisons in j = n-2
for i=2 ; number of comparisons in j = n-3
for i=3 ; number of comparisons in j = n-4
for i=4 ; number of comparisons in j = n-5
-----
-----
for i=n-1 ; number of comparisons in j = 0
-------------------------------------------
therefore : total number of comparisons = 0+1+2+....+(n-1)
                                                            =n(n-1)/2
                                                            =O(n^2) //quadratic complexity