Binary arithmetic using python

Convert unsinged integer to binary string

bin(10)

‘0b1010′

Convert binary string to unsigned integer

int('1010',2)

10

It also works if you try the binary string with the prefix ‘0b’. For example,

int('0b1010',2)

Convert signed integer to binary string

It is a little bit difficult to deal with negative numbers. Trying to convert it the same way we did with unsigned numbers doesn’t work as expected,

bin(-10)

‘-0b1010′

You would have expected a Two’s complement number as the output but it just prints the binary string of positive number with a ‘-‘ prefix.
This problem can be fixed by specifying the length of the bits you want as output.

bin(-10 & 0xff)

‘0b11110110′

If you want the length to be dynamic,

int("1" * 8, 2)

Convert singed binary string to signed integer

I am not sure if there is a direct way to do this in python. If you find any please let me know! I have written a small function to do it,

face/eye/hand detection using openCV python binding

Haar transform can be used to detect a required object in an image. To detect an object using haar transform, we have to train by providing it some positive and negative images and generate an xml containing the required object’s features. It might take several days to completely train it. In this post, let us look at some already trained cases like face, eye or hand detection. If you have installed openCV python bindings provided by ubuntu, /usr/share/opencv/haarcascades/ directory has few trained xml feature files. Let us use few of them.

face detection

#!/usr/bin/python
import sys, os
from opencv.cv import *
from opencv.highgui import *
import opencv

def detectObjects(image):
    grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
    cvCvtColor(image, grayscale, CV_BGR2GRAY)

    storage = cvCreateMemStorage(0)
    cvClearMemStorage(storage)
    cvEqualizeHist(grayscale, grayscale)
    cascade = cvLoadHaarClassifierCascade('/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml',
                                          cvSize(1, 1))
    faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(50, 50))
    if faces:
        for i in faces:
            cvRectangle(image, cvPoint( int(i.x), int(i.y)),
                         cvPoint(int(i.x + i.width), int(i.y + i.height)),
                         CV_RGB(0, 255, 0), 3, 8, 0)

def main():
    cvNamedWindow("cam", 1)
    capture = cvCreateCameraCapture(0)
    orig = cvQueryFrame(capture)
    grey = cvCreateImage(cvGetSize(orig), IPL_DEPTH_8U, 1)
    face = cvCreateImage(cvGetSize(grey), IPL_DEPTH_8U, 1)
    while True:
        orig = cvQueryFrame(capture)
        cvCvtColor(orig, grey, CV_RGB2GRAY)
        detectObjects(orig)
        cvShowImage("cam", orig)
        k = cvWaitKey(10)
        if k == 'q': # press q to quit
            break

if __name__ == "__main__":
    main()

Here is the output,

eye detection

#!/usr/bin/python
import sys, os
from opencv.cv import *
from opencv.highgui import *
import opencv

def detectObjects(image):
    grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
    cvCvtColor(image, grayscale, CV_BGR2GRAY)

    storage = cvCreateMemStorage(0)
    cvClearMemStorage(storage)
    cvEqualizeHist(grayscale, grayscale)
    cascade = cvLoadHaarClassifierCascade('/usr/share/opencv/haarcascades/haarcascade_mcs_righteye.xml',
                                          cvSize(1, 1))
    faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(50, 50))
    if faces:
        for i in faces:
            cvRectangle(image, cvPoint( int(i.x), int(i.y)),
                         cvPoint(int(i.x + i.width), int(i.y + i.height)),
                         CV_RGB(0, 255, 0), 3, 8, 0)

def main():
    cvNamedWindow("cam", 1)
    capture = cvCreateCameraCapture(0)
    orig = cvQueryFrame(capture)
    grey = cvCreateImage(cvGetSize(orig), IPL_DEPTH_8U, 1)
    face = cvCreateImage(cvGetSize(grey), IPL_DEPTH_8U, 1)
    while True:
        orig = cvQueryFrame(capture)
        cvCvtColor(orig, grey, CV_RGB2GRAY)
        detectObjects(orig)
        cvShowImage("cam", orig)
        k = cvWaitKey(10)
        if k == 'q': # press q to quit
            break

if __name__ == "__main__":
    main()

In our next post, let us see how we can train haar transform to detect an object of our desire.

python – split string delimited by runs of whitespace

In python, a string can be split using string.split() function. This function splits a string using a delimiter.

Example:
>>> “split this string”.split(‘ ‘)
[‘split’, ‘this’, ‘string’]

>>> “split,this,string”.split(‘,’)
[‘split’, ‘this’, ‘string’]

The first and second example are delimited by ‘ ‘ and ‘,’ respectively. If suppose we want to delimit using runs of whitespace, we can use

Example:
>>> ”   split   this text   “.split()
[‘split’, ‘this’, ‘text’]

Thus by using split function without any arguments, python splits on runs of whitespace.