OpenCV-Python | (page 4 of 4)



OpenCV Python Tutorials

Solve this Puzzle in Python


I would like to present you a very interesting puzzle. It was asked by maths teacher in high school ( not to solve in Python, but solve in pen and paper ). I could solve it back then ( where my "method" was not good and the way i found it is still a "mystery" to me. ). Even a few days back, I admit I couldn't find a method to solve this except brute forcing.

So I decided to apply brute-forcing for this puzzle in Python, and I asked this question in But I was really surprised seeing the answers provided there. I would like to share this with you.

This is the puzzle :

A merchant has a 40 kg weight which he used in his shop. Once, it fell from his hands and was broken into 4 pieces. But surprisingly, now he can weigh any weight between 1 kg to 40 kg with the combination of these 4 pieces.
So question is, what are weights of those 4 pieces?
Try to solve this puzzle in Python. If you can't, find its answer here.
With Regards,

Install OpenCV in Windows for Python

Hi Friends,

Here I will tell you how to install OpenCV 2.4x in Windows  for Python 2.7.

Pre-requisites ( need to be downloaded ) :

Python : Download latest version of Python 2.7 from Python site.
Numpy : Download Numpy for Python 2.7 from here.
OpenCV 2.4 : Download OpenCV for windows from here.


1)  First install Python 2.7. Leave all settings as default. In that case, Python will be installed in default folder C:\Python27\

2) Now install Numpy. Again leave everything default. Numpy will find Python directory and will be installed to most appropriate folder.

3) Now double-click OpenCV.exe. It will ask for extraction folder. Give it as just C:\. It will extract all files to C:\opencv\  . Wait until everything is extracted.

4) Now copy everything in the folder C:\opencv\build\python\x86\2.7\ ( most probably, there will be only one file cv2.pyd ) and paste it in the folder C:\Python27\Lib\site-packages\

5) Now open your "Python IDLE" ( from Start > All Programmes > Python 2.7 > Python IDLE ) and just type following :
import cv2

If everything OK, it will import cv2 module, otherwise an error message will be shown.

So it is very simple procedure. Try it yourself and let me know how it goes.

NB : Even if you are using 64-bit windows, do the same procedure. ( Better don't go for 64-bit Python and Numpy )

With Regards,

Drawing Histogram in OpenCV-Python

Hi Friends,

Do you want to draw a histogram for an image as below?

Drawing Histogram in OpenCV-Python

See the histogram for above image for RGB channels.

Drawing Histogram in OpenCV-Python

The code:

import cv2
import numpy as np

img = cv2.imread('zzzyj.jpg')
h = np.zeros((300,256,3))

bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for ch, col in enumerate(color):
hist_item = cv2.calcHist([img],[ch],None,[256],[0,256])
pts = np.column_stack((bins,hist))



You can see the same code written using numpy functions on histogram here  : Drawing histogram in OpenCV- Python.

Don't forget to send your comments, doubts etc.

With Regards,
Abid Rahman K.

Simple Digit Recognition OCR in OpenCV-Python

Hi Friends, 

It is  a long since i have posted an article.

Now i present you a Simple Digit Recognition OCR using kNearestNeighbour features in OpenCV-Python.

It demonstrats how to train the data and recongnize digits from previously trained data.

The code is using new Python interface, cv2. ( OpenCV v 2.3+)

The code and explanation can be found here:
Test Image:

Simple Digit Recognition OCR in OpenCV-Python

Result image:

Simple Digit Recognition OCR in OpenCV-Python

Waiting for your feedback!!
Abid Rahman K.

Contour features

For more details on contours, visit :

1) Contours - 1 : Getting Started

2) Contours - 2 : Brotherhood

''' filename :

This sample calculates some useful parameters of a contour. This is an OpenCV implementation of regionprops function in matlab with some additional features.

Benefit : Learn to find different parameters of a contour region.
          Get familier with different contour functions in OpenCV.

Level : Beginner or Intermediate

Usage : python <image_file>

Abid Rahman 3/25/12 '''

import cv2
import numpy as np

class Contour:
    ''' Provides detailed parameter informations about a contour

        Create a Contour instant as follows: c = Contour(src_img, contour)
                where src_img should be grayscale image.


        c.area -- gives the area of the region
        c.parameter -- gives the perimeter of the region
        c.moments -- gives all values of moments as a dict
        c.centroid -- gives the centroid of the region as a tuple (x,y)
        c.bounding_box -- gives the bounding box parameters as a tuple => (x,y,width,height)
        c.bx,,, -- corresponds to (x,y,width,height) of the bounding box
        c.aspect_ratio -- aspect ratio is the ratio of width to height
        c.equi_diameter -- equivalent diameter of the circle with same as area as that of region
        c.extent -- extent = contour area/bounding box area
        c.convex_hull -- gives the convex hull of the region
        c.convex_area -- gives the area of the convex hull
        c.solidity -- solidity = contour area / convex hull area -- gives the center of the ellipse
        c.majoraxis_length -- gives the length of major axis
        c.minoraxis_length -- gives the length of minor axis
        c.orientation -- gives the orientation of ellipse
        c.eccentricity -- gives the eccentricity of ellipse
        c.filledImage -- returns the image where region is white and others are black
        c.filledArea -- finds the number of white pixels in filledImage
        c.convexImage -- returns the image where convex hull region is white and others are black
        c.pixelList -- array of indices of on-pixels in filledImage
        c.maxval -- corresponds to max intensity in the contour region
        c.maxloc -- location of max.intensity pixel location
        c.minval -- corresponds to min intensity in the contour region
        c.minloc -- corresponds to min.intensity pixel location
        c.meanval -- finds mean intensity in the contour region
        c.leftmost -- leftmost point of the contour
        c.rightmost -- rightmost point of the contour
        c.topmost -- topmost point of the contour
        c.bottommost -- bottommost point of the contour
        c.distance_image((x,y)) -- return the distance (x,y) from the contour.
        c.distance_image() -- return the distance image where distance to all points on image are calculated
    def __init__(self,img,cnt):
        self.img = img
        self.cnt = cnt
        self.size = len(cnt)


        #Contour.area - Area bounded by the contour region'''
        self.area = cv2.contourArea(self.cnt)

        # contour perimeter
        self.perimeter = cv2.arcLength(cnt,True)

        # centroid
        self.moments = cv2.moments(cnt)
        if self.moments['m00'] != 0.0:
   = self.moments['m10']/self.moments['m00']
   = self.moments['m01']/self.moments['m00']
            self.centroid = (,
            self.centroid = "Region has zero area"

        # bounding box
        (self.bx,,, = self.bounding_box

        # aspect ratio
        self.aspect_ratio =

        # equivalent diameter
        self.equi_diameter = np.sqrt(4*self.area/np.pi)

        # extent = contour area/boundingrect area
        self.extent = self.area/(*

        ### CONVEX HULL ###

        # convex hull
        self.convex_hull = cv2.convexHull(cnt)

        # convex hull area
        self.convex_area = cv2.contourArea(self.convex_hull)

        # solidity = contour area / convex hull area
        self.solidity = self.area/float(self.convex_area)

        ### ELLIPSE  ###

        self.ellipse = cv2.fitEllipse(cnt)

        # center, axis_length and orientation of ellipse
        (,self.axes,self.orientation) = self.ellipse

        # length of MAJOR and minor axis
        self.majoraxis_length = max(self.axes)
        self.minoraxis_length = min(self.axes)

        # eccentricity = sqrt( 1 - (ma/MA)^2) --- ma= minor axis --- MA= major axis
        self.eccentricity = np.sqrt(1-(self.minoraxis_length/self.majoraxis_length)**2)


        self.approx = cv2.approxPolyDP(cnt,0.02*self.perimeter,True)

        ### EXTRA IMAGES ###

        # filled image :- binary image with contour region white and others black
        self.filledImage = np.zeros(self.img.shape[0:2],np.uint8)

        # area of filled image
        filledArea = cv2.countNonZero(self.filledImage)

        # pixelList - array of indices of contour region
        self.pixelList = np.transpose(np.nonzero(self.filledImage))

        # convex image :- binary image with convex hull region white and others black
        self.convexImage = np.zeros(self.img.shape[0:2],np.uint8)

        # mean value, minvalue, maxvalue
        self.minval,self.maxval,self.minloc,self.maxloc = cv2.minMaxLoc(self.img,mask = self.filledImage)
        self.meanval = cv2.mean(self.img,mask = self.filledImage)

        ### EXTREME POINTS ###

        # Finds the leftmost, rightmost, topmost and bottommost points
        self.leftmost = tuple(self.cnt[self.cnt[:,:,0].argmin()][0])
        self.rightmost = tuple(self.cnt[self.cnt[:,:,0].argmax()][0])
        self.topmost = tuple(self.cnt[self.cnt[:,:,1].argmin()][0])
        self.bottommost = tuple(self.cnt[self.cnt[:,:,1].argmax()][0])
        self.extreme = (self.leftmost,self.rightmost,self.topmost,self.bottommost)

    def distance_image(self,point=None):
        '''find the distance between a point and adjacent point on contour specified. Point should be a tuple or list (x,y)
            If no point is given, distance to all point is calculated and distance image is returned'''
        if type(point) == tuple:
            if len(point)==2:
                self.dist = cv2.pointPolygonTest(self.cnt,point,True)
                return self.dist
            dst = np.empty(self.img.shape)
            for i in xrange(self.img.shape[0]):
                for j in xrange(self.img.shape[1]):

            dst = dst+127
            dst = np.uint8(np.clip(dst,0,255))

            # plotting using palette method in numpy
            palette = []
            for i in xrange(256):
                if i<127:
                elif i==127:
                elif i>127:
                    l = i-128
            palette = np.array(palette,np.uint8)
            self.h2 = palette[dst]
            return self.h2

#### DEMO ######
if __name__=='__main__':

    import sys
    if len(sys.argv)>1:
        image = sys.argv[1]
        image = 'new.bmp'
        print "Usage : python <image_file>"
    im = cv2.imread(image)
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    thresh = cv2.adaptiveThreshold(imgray,255,0,1,11,2)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    k = 1000
    for cnt in contours:

        # first shows the original image
        im2 = im.copy()
        c = Contour(imgray,cnt)
        print c.leftmost,c.rightmost
        cv2.putText(im2,'original image',(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))      
        if cv2.waitKey(k)==27:
        im2 = im.copy()

        # Now shows original contours, approximated contours, convex hull
        string1 = 'green : original contour'
        cv2.putText(im2,string1,(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))
        if cv2.waitKey(k)==27:
        approx = c.approx
        string2 = 'blue : approximated contours'
        cv2.putText(im2,string2,(20,40), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))
        if cv2.waitKey(k)==27:
        hull = c.convex_hull
        string3 = 'red : convex hull'
        cv2.putText(im2,string3,(20,60), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))
        if cv2.waitKey(k)==27:

        im2 = im.copy()

        # Now mark centroid and bounding box on image
        (cx,cy) = c.centroid,(int(cx),int(cy)),5,(0,255,0),-1)
        cv2.putText(im2,'green : centroid',(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))

        (x,y,w,h) = c.bounding_box
        cv2.putText(im2,'red : bounding rectangle',(20,40), cv2.FONT_HERSHEY_PLAIN, 1.0,(0,255,0))

        (center , axis, angle) = c.ellipse
        cx,cy = int(center[0]),int(center[1])
        ax1,ax2 = int(axis[0]),int(axis[1])
        orientation = int(angle)
        cv2.putText(im2,'white : fitting ellipse',(20,60), cv2.FONT_HERSHEY_PLAIN, 1.0,(255,255,255)),c.leftmost,5,(0,255,0),-1),c.rightmost,5,(0,255,0)),c.topmost,5,(0,0,255),-1),c.bottommost,5,(0,0,255))
        if cv2.waitKey(k)==27:

        # Now shows the filled image, convex image, and distance image
        filledimage = c.filledImage
        cv2.putText(filledimage,'filledImage',(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,255)
        if cv2.waitKey(k)==27:

        conveximage = c.convexImage
        cv2.putText(conveximage,'convexImage',(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,255)
        if cv2.waitKey(k)==27:

        distance_image = c.distance_image()
        cv2.putText(distance_image,'distance_image',(20,20), cv2.FONT_HERSHEY_PLAIN, 1.0,(255,255,255))
        if cv2.waitKey(k)==27:

Welcome to OpenCV-Python !!!

Welcome to OpenCV-Python !!!
Welcome to OpenCV-Python !!!
This site provides some tutorials and examples on OpenCV-Python for absolute beginners.

Why this blog?

I started learning OpenCV a few months back. Before that, I used MATLAB for all my image processing purposes. The experience of shifting from MATLAB to OpenCV was amazing. Since i am a Python fan, I decided to use Python-bindings of OpenCV.

But as a beginner, I found a main problem in front of me. There are plenty of OpenCV tutorials available online for beginners, but most of them uses C++ for example codes. I couldn't find a single tutorial in Python for OpenCV. I could find a lot of OpenCV code in Python scattered online, but none of them was good for a beginner to start with. The best one I could find was none other than OpenCV-Python documentation. But it only lists the functions, not the examples using them.

Finally, I decided to start with C++ tutorials itself. I started to convert those codes from C++ to Python with the help of OpenCV-Python documentation. I decided to start a site or blog which shows the route i travelled to learn OpenCV so that it could be really helpful to the beginners. And here is the result.

Remember, I am also a beginner in OpenCV and I am still learning its basics. Here, what I am doing is, to give you only the outline ideas for a beginner to start with. For in-depth understanding, surely, I am not the right person to explain. But I know some good places where you can find them and I will share it with you as far as possible.

Some basic assumptions...

Here, I have made some assumptions...

1. You already know Python very well.
                Remember, this site only provides tutorial on OpenCV only, not on Python. So make sure, you have studied Python before beginning this site.
                Also, if you are good in C++, I would recommend you to use OpenCV in C++ itself. OpenCV can be used in C also.

2. You are using Python 2.7, OpenCV 2.4 and its python-bindings.
               I would recommend you to use Linux. It may be a little difficult at the beginning. But as time passes, you will enjoy it. You will feel the freedom of open-source.

I am always waiting for your suggestions and comments...

Feel free to talk for a better output...

You can contact me at:

Hope you will enjoy here...

Abid K.

Python - A Powerful Friend

Python - A Powerful Friend "Remarkable power with very clear syntax"" - That is Python if explained in simple words.

Are you bored of writing lots of lines and another large number of symbols used in C++  and C? Go to Python. Everything is fine there.

Python is an interpreted, general-purpose high-level programming language whose design philosophy emphasizes code readability. Its standard library is large and comprehensive.

Guido Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL).

The Python implementation is under an open source license that makes it freely usable and distributable, even for commercial use. The Python license is administered by the Python Software Foundation.

Some of its key distinguishing features include:
  • very clear, readable syntax
  • strong introspection capabilities
  • intuitive object orientation
  • natural expression of procedural code
  • full modularity, supporting hierarchical packages
  • exception-based error handling
  • very high level dynamic data types
  • extensive standard libraries and third party modules for virtually every task
  • extensions and modules easily written in C, C++
  • embeddable within applications as a scripting interface
Large organizations that make use of Python include Youtube, BitTorrent, Google, Yahoo!, CERN, NASA and ITA. Most of the Sugar software for the One Laptop per Child XO, now developed at Sugar Labs, is written in Python.

Presently, Python 3.2 has been released. But Linux distributions like Fedora, Ubuntu still uses Python 2.7.
(NB:- In this tutorial we will be using Python 2.7)


Official Website:
Documentation for Python 2.7:

Recommended Books:

" A Byte of Python" by Swaroop C. H.
       Simplest tutorial on Python. A good location to start, if you are new to Python. Read the book here,

" Dive into Python" by Mark Pilgrim.
        Next step after "A byte of Python". Read the book here,

" Learning Python" by Mark Lutz.
       A really big book with more than 1000 pages. Have a look at the book here: "Learning Python"

Or even better, just Google "Python Tutorials". You will get 1000s of books. But I think above three will be more than enough.


For instant help, use IRC channel : #python
Ask your doubts there. You will get answers in seconds.
( For those who haven't use IRC before:      visit,     give a nickname you like, enter #python in channel field, type the captcha in captcha field, skip all other fields, then click on connect. You will be led to a chat room where you can ask your doubts. Someone will reply)

OpenCV - A Library with Eyes

OpenCV - A Library with Eyes
OpenCV (Open Source Computer Vision Library) is a library of programming functions mainly aimed at real time computer vision, developed by Intel and now supported by Willow Garage. It is free for use under the open source BSD license. The library is cross-platform. It focuses mainly on real-time image processing. The library has more than 2000 optimized algorithms.


OpenCV was started at Intel in 1999 by Gary Bradski for the purposes of accelerating research in and commercial applications of computer vision in the world and, for Intel, creating a demand for ever more powerful computers by such applications. Vadim Pisarevsky joined Gary to manage Intel's Russian software OpenCV team. Over time the OpenCV team moved on to other companies and other Research. Several of the original team eventually ended up working in robotics and found their way to Willow Garage. In 2008, Willow Garage saw the need to rapidly advance robotic perception capabilities in an open way that leverages the entire research and commercial community and began actively supporting OpenCV, with Gary and Vadim once again leading the effort.

OpenCV's application areas include:
  • 2D and 3D feature toolkits
  • Egomotion estimation
  • Facial recognition system
  • Gesture recognition
  • Human–computer interaction (HCI)
  • Mobile robotics
  • Motion understanding
  • Object Identification
  • Segmentation and Recognition
  • Stereopsis Stereo vision: depth perception from 2 cameras
  • Structure from motion (SFM)
  • Motion tracking
To support some of the above areas, OpenCV includes a statistical machine learning library that contains:

  • Boosting
  • Decision tree learning
  • Gradient boosting trees
  • Expectation-maximization algorithm
  • k-nearest neighbor algorithm
  • Naive Bayes classifier
  • Artificial neural networks
  • Random forest
  • Support vector machine (SVM)
( All details extracted from Wikipedia)


OpenCV official page:
OpenCV Documentation:
OpenCV Q&A Forum :
OpenCV Developer Zone :

Community Support

OpenCV Q&A Forum and are the best two places where you can find answers to your problems.

mailing list:
IRC channel:    #opencv
        Core developers of OpenCV won't be present at IRC channels. So it is difficult to find an answer at IRC.
( For those who haven't use IRC before:      visit,     give a nickname you like, enter #opencv in channel field, type the captcha in captcha field, skip all other fields, then click on connect. You will be led to a chat room where you can ask your doubts. Someone may reply)

Recommended Books

"Learning OpenCV: Computer Vision with the OpenCV Library" by Gary Bradski and Adrian Kaehler.
        This is considered to be the best book on OpenCV written by founder of OpenCV himself. Everything is explained in great detail and nice examples, but in C++. Whatever language do you use, whether it is Python,C++ or C, this book is a must read book, if you want to understand OpenCV.
See a look inside the book here:    "Learning OpenCV"

Welcome to OpenCV-Python !!!OpenCV - A Library with Eyes

Report "OpenCV-Python"

Are you sure you want to report this post for ?