Sunday 17 July 2016

TUT8: Basic Drawing - Circle

In this tutorial, we are going to see how can we draw a circle using Python, OpenCV and Numpy.

Code:


import cv2                                          #Line 1
import numpy as np                                  #Line 2

img=np.zeros((500,500,3), np.uint8)                 #Line 3 

cv2.circle(img, (200,200), 150, (255, 0, 0), 2)     #Line 4

cv2.imshow('img',img)                               #Line 5

cv2.waitKey(0)                                      #Line 6
cv2.destroyAllWindows()                             #Line 7

Line 1-2: Import necessary packages

Line 3: Create a blank image using np.zeros().   #see previous tutorial to understand how it works.

Line 4: Use function cv2.circle(image, (x, y), r, color, thickness ) to create a circle on the blank                        image
  • image is the name of the blank image on which we will draw our circle
  • (x,y) is the center of the circle. 
  • r is the radius of the circle
  • color defined as (B, G, R). B, G, R represent the intensity of blue, green and red  color in your circle. Max intensity is 255 for each color. You can experiment with other value too for different color circles.
  • thickness represents the thickness of the circumference line of the circle.
Line 5: Display the picture using imshow() function. 

Line 6: Hold screen infinitely until user closes it.

Line 7: Close any open windows. 

OUTPUT:



So that's it for this tutorial. Hope you are learning to use OpenCV with Python and Numpy. See you in my next tutorial where we will learn to draw more complex drawings which will involve use of both circle and line.

Any queries , please ask in comments section below. :)

Wednesday 13 July 2016

TUT7: Basic Drawing - Line

In this tutorial, We are going to see how to draw a line using OpenCV, Python and Numpy.

Today we will learn to use two new functions:
  • np.zeros()
  • cv2.line()
So let's start:


import cv2                                                #Line 1
import numpy as np                                        #Line 2

img=np.zeros((640,480,3), np.uint8)                       #Line 3
cv2.line(img, (0,0), (480,640), (255, 0, 0), 2)           #Line 4

cv2.imshow('img',img)                                     #Line 5

cv2.waitKey(0)                                            #Line 6
cv2.destroyAllWindows()                                   #Line 7


Line 1: Import OpenCV package using "import cv2"

Line 2: Import numpy package using "import numpy as np". Here "np" is just a short name for                        numpy so if want to call a numpy function zeros() we can simply write np.zeros() instead of                numpy.zeros(). It will save your typing in longer codes.

Line 3: Here we have a new function np.zeros() which is the part of numpy package. This function                has the following syntax:


np.zeros((row,col,channel), dtype, order= 'C')
       
           It is used to create an empty black image of specified size(Row x Col). We need a surface to                draw lines, circle etc. and this function provides us that surface by creating an empty black                  surface where we can make drawings.
  •  row,col: specify row and col in terms of number of pixels for eg. (640,480)
  •  channel: specify the type of image. grayscale or color. We pass 3 for color.
  •  dtype(optional): datatype of pixel values. by default np.float64
  •  order(optional): row wise or column wise. by default 'C'           
Line 4: This is the code which actually draws a line on the black surface we made in previous line.
             The syntax is:


cv2.line(img, (start_co-ordinate), (end_co-ordinate), (color), thickness)
             
  •    img is the image that we just made using np.zeros. This specifies that we want to draw on          that image
  •    start_co-ordinate is the starting point of the line for eg. (0,0) i.e the top left of the screen
  •    end_co-ordinate is the end point of the line for eg. (480,640). Remember that 480 is the              column size and 640 is the row size. This is in contrast with what we wrote in np.zeros().
  •    color defines the color of the line you want to draw. For eg. (255,0,0) i.e. BLUE color line
  •    thickness defines the thickness of the line we want to draw. For eg. 2      
Line 5: Display the image using cv.imshow() method.

Line 6: To hold the screen infinitely we pass the argument to waitKey as 0.

Line 7: Closes all the open windows, if any.

OUTPUT:


As you can see, we are now able to draw a line using simple operations.

That's all for this tutorial, and in next tutorial we are going to learn how to draw a circle. 

Any queries, please ask in comments section below.

Friday 8 July 2016

TUT6: Recording a Video using Python-OpenCV


In this tutorial we will see how to record a video from a camera. We can use laptop camera to do this. Here is the code:


import cv2                                                             #Line1 

cap=cv2.VideoCapture(0)                                                #Line2

#Specifying codec for video
fourcc = cv2.VideoWriter_fourcc(*'XVID')                               #Line3
                          
output = cv2.VideoWriter('PyVideo.avi', fourcc, 25.0, (640,480))       #Line4

#displaying and saving the video
while(1):                                                              #Line5
    ret,frame=cap.read()                                               #Line6
    if ret==True:                                                      #Line7
        output.write(frame)                                            #Line8

        cv2.imshow('frame',frame)                                      #Line9

        if cv2.waitKey(40) == 27:                                      #Line10
            break                                                      #Line11

cap.release()                                                          #Line12
cv2.destroyAllWindows()                                                #Line13


Lets understand whats happening in the code above:
NOTE: Read Line 3 and Line 4 carefully

Line 1: Import necessary libraries

Line 2 : Initialize VideoCapture object cap. We pass 0 as argument to initialize laptop camera. Try numbers greater than or equal to 1 to initialize external camera

Line 3 : This is the most important step as in this step we are providing the info about the codec of video we are going to make. It can be 'XVID', 'MJPG', 'DIVX'  and so on. We have defined it as 'XVID'. The function we use for this is cv2.VideoWriter_fourcc(*'<type of file>') where you can replace <type of file> with supported Codecs of Videos in OpenCV.

Line 4 : Now we need to specify what will the output i.e. captured video will look like. For this will create a VideoWriter object. This object takes as input the filename(eg. movie.avi) , the FOURCC code, fps(frames per second) i.e the speed of video(eg. 20), and the resolution of the video(eg. (320,160)).

Line 5 : While loop starts

Line 6 : Capturing a frame from camera and saving in frame.

Line 7 : As we discussed in one of the previous tutorials, ret is a boolean variable which contains True if frame is captured else False. This makes sense as we will only save a frame if it is available.

Line 8 : From this line onwards we start saving the video. As the name suggest, it write onto the file mentioned in "output" object.

Line 9 : Display the frame so that you can see whats been recorded. If you omit this line, you can still record video although you wont be able to see what is being recorded.

Line 10-11 : As discussed in previous tutorials, waitKey(40) will hold the whatever is on the screen for 40 millisecond and check whether "ESC"(27 is ASCII for ESC key) key is pressed. If the key is pressed we come out of loop(due to break) and the recording stops too.

Line 12-13 : Release the camera and close all windows using these two lines.

Output:


As you can see, I am playing a file which was created after I run the program. 

So, that's it for this tutorial. Hope to see you again in my next tutorial which is going to be really interesting so do visit and like my facebook page to stay connected.

Any queries,  please ask in comments section below.
ThankYou

Saturday 2 July 2016

TUT5: Playing video file using Python-OpenCV

In this tutorial, you will learn to write a code in Python-OpenCV which can run a video file.
Let' see how to do this. Here is the code:


import cv2                                      #line1
cap=cv2.VideoCapture('chammakchallo.avi')       #line2
while(1):                                       #line3
    ret,frame = cap.read()                      #line4
    cv2.imshow('frame',frame)                   #line5
    if cv2.waitKey(25) == 27:                   #line6
        break                                   #line7
cap.release()                                   #line8
cv2.destroyAllWindows()                         #line9

Lets understand the code line by line:

Line1: OpenCV library imported first of all.

Line2: VideoCapture object 'cap' initialised with file name of the video as the argument of                              VideoCapture() function. Remember to provide the full path to video file if the video is not in              the same folder as the program.

Line3: while loop starts.

Line4: frame is captured from the camera and saved in frame variable.

Line5: cv2.imshow() used to display the frame on window named 'frame'.

Line6: cv.waitkey(25) holds the screen i.e. 'the frame' for for 25 milliseconds and also checks if ESC               key is pressed(27 is ASCII for 'ESC key'). If ESC key is pressed then break is encoutered and 
            we are out of loop.

Line7: break is a jump statement which when encountered bring program execution to the first line                 after the loop. In this case, its cap.release which is executed as it is the first line after the loop.

Line8: cap.release() release the VideoCapture object. 

Line9: cv2.destroyAllWindows() kills the active windows if any.


Output:



As you can see the video is playing after running the code. Note that you wont be able to hear the audio because OpenCV is a vision library and not an audio library. Its use is to manipulate the images,videos and not the sound. This tutorial just teaches you the basic things that you need to know about OpenCV and this feature is one of them.

That's it for this tutorial. See you in the next one where we are going to capture and save a video using a laptop camera. 

Any queries please ask in comments.