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


Blogger Widgets