Blogger Widgets

Search This Blog

Tuesday, 18 December 2012

OpenCV - Open Computer Vision in Python

                 OpenCV is a library used for real time computer vision.It is open source under BSD License. Here a quick start of OpenCV in python is explained.It is very useful module for robotics , Image processing, Object tracking etc.

We can directly explain a Helloworld example before actually study this - Here we open an image and change its pixel values and save its inverted colour image.
    image                              processed image


#!/usr/bin/python
import cv2

cv2.namedWindow("Image")
cv2.namedWindow("Processed Image")

if __name__ == '__main__':
    import sys
    try: image = cv2.imread(sys.argv[1])
    except: image = cv2.imread("lena.jpg")

processedImage = image.copy()

height, width, nColors = processedImage.shape

for y in xrange(height):
    for x in xrange(width):
        B = processedImage.item(y, x, 0)
        G = processedImage.item(y, x, 1)
        R = processedImage.item(y, x, 2)
        processedImage.itemset(y, x, 0, 255 - B)
        processedImage.itemset(y, x, 1, 255 - G)
        processedImage.itemset(y, x, 2, 255 - R)

cv2.imshow("Image", image)
cv2.imshow("Processed Image", processedImage)

cv2.waitKey(0)
cv2.destroyAllWindows()


                    Where we first import opencv module and create two windows for image and processed image. And copy the given image to a variable named  "processedImage".Then we access its parameters height, width. The color of all pixels are inverted using for loop by accessing individual pixel informations.Then shows both the image.




Monday, 17 December 2012

AVR PROGRAMMING - QUICK START





Here I just gives a brief introduction for AVR programming in Linux. I'm using ubuntu 11.10 . Finally we can able to blink an LED( Hello world program). Here I'm uses ATMEGA8 and usbasp programmer.


Step1 : Install the tool chains required for AVR programming
  •           sudo apt-get install gcc-avr
  •           sudo apt-get install avrdude
  •           sudo apt-get install libc

Step2 : Next step is to write an Hello world program - Here it is to just
            blink an LED .save this as led.c
  
               #include<avr/io.h>
               main()
              {   
                      DDRB = 0xff;
                      PORTB = 0xff;
              }
   
                     
                    Where <avr/io.h> is the header file for AVR programming.DDRB is the data direction register of PORTB, by writing 0xff we set this as output port.Then we write PORTB = 0xff it will set PORTB (8pins) to HIGH.

Step3 : Here we want to compile the program and make it hex code . for that  use the following steps.
  •           convert led.c to the object file led.o
                 avr-gcc -mmcu=atmega8  led.c -o led.o
                 some times we need to optimize the code
              
                 avr-gcc -mmcu=atmega8 -Os led.c -o led.o

  •           then convert the object file to hex file
                 avr-objcopy -j .text -j .data -O ihex  led.o  led.hex
          

 Step3 : Connect the usbasp programmer to the usb of the lap top
usbasp programmer


usbasp - development board
Step 4: To burn the hex code in to the ATMEGA8 connect the development  board to usb-asp. Then connect to the usb of the laptop .Connect a LED with a resistor to PORTB. Then run the following command
   
  • sudo avrdude -c usbasp -p m8 -U flash:w:led.hex:a 


you can see that the led connected to portB is blinking

some more avr-programming codes are adde in my github

Wednesday, 12 December 2012

Weather App using Tornado


Tornado is a scalable, non-blocking web server and web application framework. It was developed by FriendFeed.The framework is distinct from most mainstream web server frameworks (and certainly most Python frameworks) 
because it is non-blocking and reasonably fast.

Starting with Tornado


import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Run this code using python and go to http://www.localhost:8888 will print 
"Hello, world" in firefox.

How we have done it ? 

The problem is to create a weather app using tornado frame work.For this we need to fetch the live whether data.I'm using openwhethermap.org to fetch climate data. I'm uses urllib library to get weather data from the weather server. And converted it to dict format using ast module in python. Then filter the required data(Temperature, Humidity, Pressure) from dict. Up to this first section of the project is completed.

Now I want to create a template

I'm create template in html . Now we need to put weather data's  (Temperature , Humidity, Pressure) in template. For integrating this values I'm uses jinja2 .

Main code for weather app 

weather.py

'''
-----------------------------------------------------------------------------------------------------
Created on 12-Dec-2012
@author: unais

This is the main program for the weather app

weather server used : http://openweathermap.org/data/2.1/forecast/city?q=Kochin

Here urllib is used to fetch climate data from openweathermap.org

"jinja2" template engine is used to render html pages with tornado

Template is saved in /template/weather.html

we can give different city names in plase of "Palakkad" for getting weather datas of different citys
------------------------------------------------------------------------------------------------------
'''
import urllib2
import ast
import tornado.ioloop
import tornado.web
import jinja2
import os


jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"))

def getWeatherCondition(city) :
    try :
        url = "http://openweathermap.org/data/2.1/forecast/city?q="
        url += city
        req = urllib2.Request(url)
        response=urllib2.urlopen(req)
    except Exception :
        print("Not a matched city")
    return response.read()

def print_weather(place):
    Data_str =  getWeatherCondition(place)
    Data = ast.literal_eval(Data_str) # converting string to dict type
    Temperature =  Data['list'][0]['main']['temp']
    Humidity    =  Data['list'][0]['main']['humidity']
    Pressure    =  Data['list'][0]['main']['pressure']
    Result      =  place , Temperature , Humidity , Pressure
    return Result
  
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        weather_data = print_weather("Palakkad") # by changing the name we get the weather datas of different city's
        template_values = { 'place':weather_data[0], 'temperature': str(weather_data[1] -272.15), 'humidity': str(weather_data[2]), 'pressure': str(weather_data[3])}
        template = jinja_environment.get_template('weather.html')
        self.write(template.render(template_values))

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
  

HTML code for template

<!DOCTYPE html>
<html>
<body>
<div style="width:450px;height:250px;border:1px solid #000;background-color:LightBlue;">
 <img border="0" src="sun.png" style="float:right; margin:20px 20px 15px 15px;border:0" alt=" " width="150" height="150">

<pre>

<font size="8"><b>  {{temperature}}<sup>o</sup>C</b> </font>

<font size= "4"><b>   Humidity : {{humidity}}%</font></b>
<font size= "4"><b>   Pressure : {{pressure}} mbar</font></b>   
</pre>
</div>
</body>
</html>

where we need create folder templates and save the above html file as weather.html

and run the python code
then go to http://localhost:8888 we can see like



 The complete code Click Here


Sunday, 30 September 2012

Basics of R : Statistical Programming Language for Data Analysis

                  R is a free software environment for statistical computing and graphics.It is an integrated suite of software facilities for data manipulation, calculation and graphical display. It has
  •  an effective data handling and storage facility,
  •  a suite of operators for calculations on arrays, in particular matrices,
  •  a large, coherent, integrated collection of intermediate tools for data  analysis,
  • graphical facilities for data analysis and display either directly at the computer or on hardcopy, and a well developed, simple and effective programming language (called ‘S’) which includesconditionals, loops, user defined recursive functions and input and output facilities.

       R is helpful when you dealing with data's of large size, for eg: Analyzing the amount of air contents of different countries  during one year (This data may contain numerical data's more than 3 GB) using classical methods may take days for its computation and analysis. But by using the simple coding by R language we can analyze it within minutes.

Saturday, 11 August 2012

Reverse Polish Calculator in C

                
                   Recently while done the exercises from KNR, I got an interesting excersise for calculator,..It is Reverse polish calculator. The major advantage of this is that this method saves our time, becouse here we can write a mathematical expression without using parentheses and brackets.
                 Here you never have to account for the parentheses while doing calculations. The process is similar to the way you learned math on paper. You can see the intermediary results as you perform your computations rather than just the answer at the end. This is an extremely helpful byproduct. Math teachers are using this feature to improve student understanding of mathematics. An intermediate result allows the user to check the results and correct errors more easily. It's easier to follow the stream of calculation. The user defines the priority of operators. RPN is logical because the user first gives the number and then tells what to do with it.

                     for eg : 
                       The reverse polish notation of (1 - 2) * (4 + 5) this
                        is entered as ----         1 2 - 4 5 + *

Saturday, 28 July 2012

Some tricky programs from KNR

Qn : 1 --   Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.
Explanation about the question :--                                 
xxx...xxxa....aax..xx and
yyyyyyyy....ynnnn..n
_____________________    and the result will be
xxx...xxxn....nnx..xx

  for eg:
if     x =    10110101
and y =    10111010

and we want to find setbits(x,4,3,y)

then we want to replace  x =    10110101 the underlined bits to the last three bits of y.


ie the result must be x =    10101001

Friday, 6 July 2012

INTERFACING JHD162A LCD TO MSP430 Launch Pad

JHD162A LCD is a commonly available display for hobby circuits.Recently I'm trying to interface LCD to my Launch Pad and display the resistance range of a 10k pot.
         The problem is that MSP430G2231 has only 8 i/o pins.So we need to use LCD in 4 bit mode

Here is a circuit for 4 bit mode

Monday, 25 June 2012

HM2007...Simplest Hardware for speech Processing

                           Hi.......We all are use many risky programs for speech processing . Here is simple solution for this.We can done speech processing like a toy by using HM2007 processor and its training kit.There is no need to program.HM2007 is a single chip CMOS voice recognition LSI circuit with the on-chip analog front end,voice analysis,recognition process and system control functions.A 40 isolated-word voice recognition system can be composed of external microphone,keyboard,64K SRAM and some other components.Combining it with microcontroller we build an intelligent recognition system. 

The figure below shows the speech training circuit using HM2007




The Scala Programming Language

                  Freands..... Today I'm just trying run Hello world program using scala. Here I just add sume basic information about scala for biginners                  
             Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.

How to make an Automatic Street Light Controller Using MSP430 Launch Pad


           Hi..There is an idea to make a simple automatic street light controller ..ie bulb automatically glow at night and turn off at day time ,using MSP430 launch pad.But the problem is that it is complex compared to cheap existing technology (using LDR and comparator arrangement ),any way I'm happy because I need a simple program to work it. And I use the LED on the Launch Pad for light sensing. mhj The interesting fact I studied from here is that we can use the same LED as light sensing and to glow.

Thursday, 21 June 2012

VOICE CONTROLLED OBJECT RECOGNITION AND PICKING ROBOT


                     This robot searches the object we told , move towards and pick it.Here Matlab is used for speech processing and Image processing. The color of object is used for identification.I'm using the arrangement inside the CD player for making a simple arm.
Front view of Robotic arrangement

Enlarged view of Robotic Arm arrangement

Tuesday, 1 May 2012

MATLAB PROGRAM FOR OBJECT DETECTION USING COLOUR INFORMATION

    Here for object detection we uses the color of the object.Using this method we can identify the object more accurately than correlation method. Here also the Background intensity cause some problem for accurate detection

 clc
vid=videoinput('winvideo',1,'YUY2_640x480');
preview(vid)
pause(5)
q=getsnapshot(vid);
a=ycbcr2rgb(q);

MATLAB PROGRAM FOR OBJECT DETECTION USING CORRELATION FUNCTION

             It is a simple Matlab program for object detection using color information .But the code has some problem when the background conditions are varying.In my program it produces correlation .5 or above when the image is detected.So using this correlation value we can decide the object.

q=imread('a.jpg');
r=rgb2gray(q);
size{128*488)
vid=videoinput('winvideo',1, 'YUY2_1024x768')
p=getsnapshot(vid)
s=rgb2gray(p)
for {i=1:1:128}
    for {j=1:1:488}
        c=s(i:i+60;j:j+100}
        corr2(r,c)
    end
end

Monday, 30 April 2012

MSP430 LaunchPad FROM TEXAS INSTRUMENTS

   MSP430 LaunchPad is an low cost, low power development board from Texas Instruments. You can easily done Embedded programming using this.
For more   www.ti.com/LaunchPadWiki
Blogger Widgets