Convert a grayscale image into a black-white image in MATLAB without im2bw

In MATLAB there is a function ‘im2bw’ which converts an input image into a black&white image. You can provide the function with a level of thresholding otherwise the default value is 0.5.

Here I show you how to implement the same functionality in a few lines of code. Check out the following function:

function S = my_im2bw(Ig,level)
S = Ig;
S(Ig > level) = 1;
S(Ig <= level) = 0;

Now let’s compare this function with the one of MATLAB:

Ig = rgb2gray(im2double(imread('test.png')));
level = 0.4;
B1 = im2bw(Ig,level);
B2 = my_im2bw(Ig,level);

The result is shown here:



Posted in Machine Learning, MATLAB, programming, Linux, Ubuntu, Optimization, Software, OpenCV | Tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Sampling from Normal (Gaussian) Distribution in MATLAB

Sampling from Normal Distribution for a single variable

Consider you want to sample 1000 points for a single variable from a normal distribution with mean equal to 5 and standard deviation equal to 1. The easiest way is using normrand function, as follows:

mu = 5;
sigma = 1;
nSample = 1000;
r = normrnd(mu,sigma,[1 nSample]);

The result can be seen in the following plot:

Sampling from Normal Distribution for multiple variables

Consider you want to sample 1000 points for two variables from a normal distribution with mean vector equal to [2,3] and covariance matrix equal to [1,1.5;1.5,3]. The easiest way is using mvnrand function, as follows:

MU = [2,3];
SIGMA = [1,1.5;1.5,3];
rng default  % For reproducibility
R = mvnrnd(MU,SIGMA,nSample);
hold on;ksdensity(R(:,2));

The result can be seen in the following plot:


Posted in Robotics, Machine Learning, MATLAB, programming, Linux, Ubuntu, Statistics, Software | Tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Find if an element is repeated exactly m times in a vector

Check if some elements of the vector are repeated exactly m times. To do so, we can use two very useful funcitons, namely ‘unique’ and ‘ismember’. The former creates a new array from the input array including only its unique elements. The later checks if an element is a member of an array or a matrix. Here is the code:

function y = mTimes(x,m)
y = [];
C = unique(x);
for kk=1:numel(C)
if sum(ismember(x,C(kk)))== m
y = [y C(kk)];


>> x = [1 2 5 2 2 7 8 3 3 1 3 8 8 8];
>> mTimes(x,3)
>> [2 3]
Posted in Linux, MATLAB, programming, Software, Ubuntu | Tagged , , , , , , , , , , , , , , , , , , , , | Leave a comment

A Script for Toolbox Validation in MATLAB

Sometimes you want to check (through your MATLAB code), if the user of your code has a specific toolbox. If you want to do it through command-line in MATLAB, you should use the following command:

>> ver

Otherwise, use the following piece of code, to detect the existance of a specific toolbox:

requiredToolboxes = 'Image Processing Toolbox';
[installedToolboxes{1:length(v)}] = deal(v.Name);
tf = all(ismember(requiredToolboxes,installedToolboxes));

So if the output is 1 means that the toolbox exists otherwise no.

Posted in MATLAB, SIMULINK, programming, Linux, Ubuntu, Software | Tagged , , , , , , , , , , , , , , , , , , , , , , | Leave a comment

People we should get to know – Part 1: John Bardeen

John Bardeen was a physicist and electrical engineer who have won the Nobel Prize twice. He is the only person who managed to won the Nobel prize twice in physics. The first time, he won the prize for the invention of the transistor that revolutionized the electronic industry and ignited the information age (1956). This invention made possible the development of almost every modern electronic device like telephones, computers, etc.

He won the Nobel prize again in physics for developing the theory of conventional superconductivity (1972). This theory is used in nuclear magnetic resonance spectroscopy or its medical sub-tool magnetic resonance imaging known as MRI.

Posted in Thoughts | Tagged , , , , , , , , , , , , , , , | Leave a comment

Estimating the value of Pi using Python (For educational Purposes)

You can estimate the value of `Pi` up to specific precision with the following method:

1- draw a square and draw the corresponding circle inside it (a quarter of the circle inscribed inside the square). So the edge length of the square and the radius of the circle would be equal (r).













2- sample some points in the boundaries of the square uniformly.

3- Count the number of points inside the circle (obviously all the points are inside the square)

4- The area of the square is r^2 and the area of the circle is pi*r^2 / 4. By considering the fact that finally the sampled points can fill the whole area of the square we can assume that the number of points inside the square describe the area of the square and the number of points inside the circle describe the area of the circle. So if we divide the number of points that are inside the circle by the number of total points the result is:
[(pi*r^2)/4] / [r^2]

Now by multiplying the obtained value we will have Pi.

Let’s show this in a simple code:

from __future__ import division
import numpy as np

a = 1
n = 1000000
s1 = np.random.uniform(0,a,n)
s2 = np.random.uniform(0,a,n)


for item in range(n):
if ((s1[item])**2 + (s2[item])**2) < 1:
ii = ii + 1

# A(circle) = pi/4
# A(square) = 1
print float(ii*4/(n))

This method is called Monte Carlo and you can find more information starting from wikipedia. (The gif image is also borrowed from Wikipedia).

Posted in programming, Linux, Ubuntu, Python, Software | Tagged , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Step-by-step Tutorial on Face Detection with MATLAB – Part 1

This is a step-by-step, easy to use, beginner level, and detailed tutorial for face detection with MATLAB. Let’s start!!

List available devices

In order to list the available webcams that can be detected and used by MATLAB do as follows:


The result should be something similar to this:

ans =
'FJ Camera'


Webcam is not detected

If MATLAB cannot detect your webcam, you need to install the package for USB cameras provided by mathworks.
Enter the following command in MATLAB command-line and press enter:


This will bring up a window that you need to select an action, Install from Internet is a good option. Then you have to scroll down and find USB camera and select it. After that MATLAB will ask you to log in with your mathworks account. If you do not have it, you can create one. Finally, the process will begin and you have to wait a little bit.

In order to see that everything is fine, check to see if MATLAB can find the camera:


The result should be something similar to this:

ans =
'FJ Camera'


Preview webcam

Firstly, get a list of existing (detectable) webcams. And use the one that you want to make a webcam object. In the following example I have chosen the first item in the list.


When the object is created, you can check its properties by just typing the name of the object:

>> cam
cam =
Name: 'FJ Camera'
Resolution: '640x480'
AvailableResolutions: {'640x480'  '352x288'  '320x240'  '176x144'  '160x120'  '1280x1024'}
Gain: 0
Contrast: 32
BacklightCompensation: 1
Saturation: 64
Brightness: 0
Gamma: 100
Sharpness: 0
WhiteBalance: 4600
Hue: 0

To get a preview, you can do as follows:


To close the preview windows:




Capture a single Image

To capture a single image from the webcam while the preview window is open, you can use the following commands:

img = snapshot(cam);

The result would be captured as a matrix in MATLAB called img. To show the image in a new window you can use:


if you have the image processing toolbox, otherwise use:


remember if you close a preview using closePreview command, you should also clear the object from the memory:


Simple face detection

In order to do a simple face detection, you need to take a snapshot and check to see if there is a face in there.first create a face detection object. (you have to have the computer vision toolbox).

faceDetector = vision.CascadeObjectDetector;

and then easily pass the taken snapshot to the face detector. If it finds a face in the input image, the return would be 4 coordinates of the corners a box around the detected face.

bboxes = step(faceDetector, img);


Source Code – A simple face detection by MATLAB

Because most of webcam cameras are low quality and noisy, you can use the following loop, in order to avoid manual repetition.

C = webcamlist;
NotYet = false;
faceDetector = vision.CascadeObjectDetector;
while ~NotYet
I = snapshot(cam);
disp('took a snapshot. checking to find a face ....')
bboxes = step(faceDetector, I);
if ~isempty(bboxes)
NotYet = true;
disp('face found!');
disp('no face detected :(, repeating...');
IFaces = insertObjectAnnotation(I, 'rectangle', bboxes, 'Face');
figure, imshow(IFaces), title('Detected faces');



Posted in Robotics, Machine Learning, MATLAB, programming, Linux, Ubuntu, OpenCV | Tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a comment