Showing posts with label camera opening in opencv. Show all posts
Showing posts with label camera opening in opencv. Show all posts

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

Thursday, 30 June 2016

TUT4: Capture a picture with your laptop camera

This tutorial is all about how to capture an image using built in laptop camera. We will write a simple and clean code to perform this task.

NOTE: Before you go through this tutorial, please make sure you have read the previous tutorial on how to start camera using Python and OpenCV otherwise you might find this tutorial a bit difficult to understand.

  • Today, you will learn a new keyword cv2.write() that will be used to capture the image.
  • After this tutorial, you will be able to click your pictures with your own self made Python code. :)
Let's see how to do this:

1) Import necessary libraries:
    
    import cv2
    import numpy as np

2) Initialise the camera object
    
    cap = cv2.VideoCapture(0)

3) while(True):                                                      #line1  
            ret, frame = cap.read()                             #line2
            cv2.imshow('cam', frame)                          #line3
            if cv2.waitKey(1) == ord('c'):                  #line4
                    cv2.imwrite('mypic.jpg', frame)          #line5
            elif cv2.waitKey(1) == 27:                           #line6
                    break                                                  #line7

     You must be familar with #line1, #line2, #line3. If not please visit the previous tutorial.
In #line4 and #line5, we are checking for a key press 'c'. If the user presses the 'c' key on their keyboard then the current frame will be saved as a picture named "mypic.jpg" in the same folder where program is saved. The function imwrite() is used for this operation which simply takes two arguments i.e. filename and frame that you need to save.
In #line6, we see a new keyword "elif". In C or Java, we write this as "else if". Python makes it shorter by a word and makes it "elif" so its same as "else if". The condition that is checked in elif is whether "ESC" key is pressed or not(27 is ASCII for ESC key). If the "ESC" key is pressed and hold for about a second, break is encountered and we come out of loop.
One more thing worth noticing in #line6 is the use of "ord('c')". In simple words, "ord('c')" returns back the ASCII value of the character passed to it. Here 'c' is passed to it so we get 99(ASCII for 'c') as return value which is then checked with waitKey(1). If 'c' is pressed and hold for about a second, imwrite() function creates a new image file and saves the frame in that file.

4) Release the camera object and destroy all windows.

     cap.release()
     cv2.destroyAllWindows()


*************************************************
Here's the summed up code:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(True):
     ret, frame = cap.read()

     cv2.imshow('cam',frame)

     if(cv2.waitKey(1) == ord('c')):
           cv2.imwrite('mypic.jpg', frame)
     elif(cv2.waitKey(1) == 27):
           break

cap.release()
cv2.destroyAllWindows()

*************************************************
OUTPUT:



In the output GIF, when I hold and pressed 'c' for about a second, the picture named mypic.jpg appears in the folder where program in stored.

So that's it for this tutorial. In the next tutorial, we will see how to play a video file using your own code written in Python and OpenCV.

Any queries, please ask in comments.
Thank you




Monday, 27 June 2016

TUT3: Starting laptop Camera using OpenCV and Python

Does your laptop has a Camera? Ever wondered how it starts. What's the type of code that works behind when you start your laptop camera. If not, this tutorial is for you.

We will be using some new terms today like cv2.VideoCapture(0) , cap.read() etc.

So lets see how to start the camera on laptop:

1) import cv2
    import numpy as np

2) cap = cv2.VideoCapture(0)

    Here 'cap' is a VideoCapture object. It has an argument. This argument can be either device index       or the name of a video file. Since here we are concerned with camera device so we pass device           index. I am passing '0' as the argument since the built-in webcam is mostly accessed by passing '0'.     If your system has external webcam then you can access it by typing index > '0' i.e. '1' or bigger.         Remember, this line of code will be used as it is in all the camera or video related programs.

3) Attention!! We are going to see how to use while loop in python:

    while(True):                                            #line 1
           ret, frame = cap.read()                     #line 2
           cv2.imshow('cam', frame)               #line 3
           if cv2.waitKey == 27:                     #line 4
                   break                                       #line 5
 
    cap.realease()
    cv2.destroyAllWindows()

   Remember there are no curly braces in python.  Scope is implemented using the Colon and indentation. Colon defines that following indented lines are within the while loop.
   As you can see #line 2, #line 3 and #line 4 do not start from beginning of line. There is a tab space before each of them. This indentation means they are inside of while loop and one iteration of this loop executes these lines once. Hence we need to take care of indentation. Similarly #line 5 is inside the if condition.

NOTE: When you are writing python code in IDLE(An IDE for python), the editor will automatically indent the lines once you type #line 1 and press Enter.

cap.read() will read the frame from the camera and store it in 'frame'. 'ret' will store true or false value depending on whether the frame was read or not.  cv2.imshow('cam', frame) will show the frame on to the window named 'cam'.

"if cv2.waitKey(1) == 27" holds the window for 1 millisecond and then check if the "ESC" key is pressed("27 is ASCII for ESC"). If the "ESC" key is pressed then 'break' is encountered and we are out of loop. This will also close the camera as cap.release() is executed next.

After you have written the code press CTRL+S to save the code to a desired location. Remember to save the file using .py extension. After this, press F5 to run the code while your code is open in IDLE.

**********************************************************
Here is the summed up code:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):
     ret, frame = cap.read()
     cv2.imshow('video', frame)
     if cv2.waitKey(1) == 27:
           break

cap.release()  
cv2.destroyAllWindows()
**********************************************************

OUTPUT:
 


So i hope that you have learned how to start your camera using Python and OpenCV.
That's it for this tutorial. In the next tutorial, we will see how to capture an image using in-built laptop camera. 
Any queries please ask in comments.
See you in next tutorial.