Install OpenCV-Python with FFMPEG to Anaconda

I have summarized my now fully working solution OpenCV-Python – How to install OpenCV-Python package to Anaconda (Windows). Nevertheless I’ve

To use OpenCV fully with Anaconda (and Spyder IDE), we need to:

  1. Download the OpenCV package from the official OpenCV site
  2. Copy and paste the cv2.pyd to the Anaconda site-packages directory.
  3. Set user environmental variables so that Anaconda knows where to find the FFMPEG utility.
  4. Do some testing to confirm OpenCV and FFMPEG are now working.

Prerequisite

Install Anaconda

Anaconda is essentially a nicely packaged Python IDE that is shipped with tons of useful packages, such as NumPy, Pandas, IPython Notebook, etc. It seems to be recommended everywhere in the scientific community. Check out Anaconda to get it installed.

Install OpenCV-Python to Anaconda

Cautious Note: I originally tried out installing the binstar.org opencv package, as suggested. That method however does not include the FFMPEG codec – i.e. you may be able to use OpenCV but you won’t be able to process videos.

The following instruction works for me is inspired by this OpenCV YouTube video. So far I have got it working on both my Desktop and Laptop. Both 64-bit machines and Windows 8.1.

Download OpenCV Package

Firstly, go to the official OpenCV site to download the complete OpenCV package. Pick a version you like (2.x or 3.x). I am on Python 2.x and OpenCV 3.x – mainly because this is how the OpenCV-Python Tutorials are setup/based on.

In my case, I’ve extracted the package (essentially a folder) straight to my C drive. (C:\opencv).

Copy and Paste the cv2.pyd file

The Anaconda Site-packages directory (e.g. C:\Users\Johnny\Anaconda\Lib\site-packages in my case) contains the Python packages that you may import. Our goal is to copy and paste the cv2.pyd file to this directory (so that we can use the import cv2 in our Python codes.).

To do this, copy the cv2.pyd file…

From this OpenCV directory (the beginning part might be slightly different on your machine):

# Python 2.7 and 32-bit machine: 
C:\opencv\build\python\2.7\x84

# Python 2.7 and 64-bit machine: 
C:\opencv\build\python\2.7\x64

To this Anaconda directory (the beginning part might be slightly different on your machine):

C:\Users\Johnny\Anaconda\Lib\site-packages

After performing this step we shall now be able to use import cv2 in Python code. BUT, we still need to do a little bit more work to get FFMPEG (video codec) to work (to enable us to do things like processing videos.)

Set Enviromental Variables

Right-click on “My Computer” (or “This PC” on Windows 8.1) -> left-click Properties -> left-click “Advanced” tab -> left-click “Environment Variables…” button.

Add a new User Variable to point to the OpenCV (either x86 for 32-bit system or x64 for 64-bit system.) I am currently on a 64-bit machine.

| 32-bit or 64 bit machine? | Variable     | Value                                |
|---------------------------|--------------|--------------------------------------|
| 32-bit                    | `OPENCV_DIR` | `C:\opencv\build\x86\vc12`           |
| 64-bit                    | `OPENCV_DIR` | `C:\opencv\build\x64\vc12`           |

Append %OPENCV_DIR%\bin to the User Variable PATH.

For example, my PATH user variable looks like this…

Before:

C:\Users\Johnny\Anaconda;C:\Users\Johnny\Anaconda\Scripts

After:

C:\Users\Johnny\Anaconda;C:\Users\Johnny\Anaconda\Scripts;%OPENCV_DIR%\bin

This is it we are done! FFMPEG is ready to be used!

Test to confirm

We need to test whether we can now do these in Anaconda (via Spyder IDE):

  • Import OpenCV package
  • Use the FFMPEG utility (to read/write/process videos)
Test 1: Can we import OpenCV?

To confrim that Anaconda is now able to import the OpenCV-Python package (namely, cv2), issue these in the IPython Console:

import cv2
print cv2.__version__

If the package cv2 is imported ok with no errors, and the cv2 version is printed out, then we are all good! Here is a snapshot:

import-cv2-ok-in-anaconda-python-2.png http://mathalope.co.uk/wp-content/uploads/2015/07/import-cv2-ok-in-anaconda-python-2.png

Test 2: Can we Use the FFMPEG codec?

Place a sample input_video.mp4 video file in a directory. We want to test whether we can:

  • read this .mp4 video file, and
  • write out a new video file (can be .avi or .mp4 etc.)

To do this we need to have a test python code, call it test.py. Place it in the same directory as the sample input_video.mp4 file.

This is what test.py may look like (I’ve listed out both newer and older version codes here – do let us know which one works / not work for you!):

(Newer verison…)

import cv2
cap = cv2.VideoCapture("input_video.mp4")
print cap.isOpened()   # True = read video successfully. False - fail to read video.

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter("output_video.avi", fourcc, 20.0, (640, 360))
print out.isOpened()  # True = write out video successfully. False - fail to write out video.

cap.release()
out.release()

(or the older version…)

import cv2
cv2.VideoCapture("input_video.mp4")
print cv2.isOpened()   # True = read video successfully. False - fail to read video.

fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter("output_video.avi",fourcc, 20.0, (640,360))
print out.isOpened()  # True = write out video successfully. False - fail to write out video.

cap.release()
out.release()

This test is VERY IMPORTANT. If you’d like to process video files, you’d need to ensure that Anaconda / Spyder IDE can use the FFMPEG (video codec). It took me days to have got it working. But I hope it would take you much less time! 🙂

Note: one more very important tip when using the Anaconda Spyder IDE. Make sure you check the Current Working Directory (CWD)!!!

Conclusion

To use OpenCV fully with Anaconda (and Spyder IDE), we need to:

  1. Download the OpenCV package from the official OpenCV site
  2. Copy and paste the cv2.pyd to the Anaconda site-packages directory.
  3. Set user environmental variables so that Anaconda knows where to find the FFMPEG utility.
  4. Do some testing to confirm OpenCV and FFMPEG are now working.

Good luck!

Advertisements

NASA’s 10 rules for developing safety-critical code

1: Restrict all code to very simple control flow constructs. Do not use GOTO statements, setjmp or longjmp constructs, or direct or indirect recursion.

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

3: Do not use dynamic memory allocation after initialization.

4: No function should be longer than what can be printed on a single sheet of paper (in a standard reference format with one line per statement and one line per declaration.) Typically, this means no more than about 60 lines of code per function.

5: The assertion density of the code should average a minimum of two assertions per function. Assertions must always be side effect-free and should be defined as Boolean tests.

6: Data objects must be declared at the smallest possible level of scope.

7: Each calling function must check non-void function return values, and the validity of parameters must be checked inside each function.

8: Preprocessor use must be limited to the inclusion of header files and simple macro definitions. Token pasting, variable argument lists (ellipses), and recursive macro calls are not allowed.

9: The use of pointers should be restricted. Specifically, no more than one level of dereferencing is allowed. Pointer dereference operations may not be hidden in macro definitions or inside typedef declarations. Function pointers are not permitted.

10: All code must be compiled, from the first day of development, with all compiler warnings enabled at the compiler’s most pedantic setting. All code must compile with these setting without any warnings. All code must be checked daily with at least one—but preferably more than one—state-of-the-art static source code analyzer, and should pass the analyses with zero warnings.

What’s the value of life?

A little boy went to his old grandpa and asked, “What’s the value of life?”

The grandpa gave him one stone and said, “Find out the value of this stone, but don’t sell it.”

The boy took the stone to an Orange Seller and asked him what its cost would be.

The Orange Seller saw the shiny stone and said, “You can take 12 oranges and give me the stone.”

The boy apologized and said that the grandpa has asked him not to sell it.

He went ahead and found a vegetable seller.

“What could be the value of this stone?” he asked the vegetable seller.

The seller saw the shiny stone and said, “Take one sack of potatoes and give me the stone.”

The boy again apologized and said he can’t sell it.

Further ahead, he went into a jewellery shop and asked the value of the stone.

The jeweler saw the stone under a lens and said, “I’ll give you 1 million for this stone.”

When the boy shook his head, the jeweler said, “Alright, alright, take 2 24karat gold necklaces, but give me the stone.”

The boy explained that he can’t sell the stone.

Further ahead, the boy saw a precious stone’s shop and asked the seller the value of this stone.

When the precious stone’s seller saw the big ruby, he lay down a red cloth and put the ruby on it.

Then he walked in circles around the ruby and bent down and touched his head in front of the ruby. “From where did you bring this priceless ruby from?” he asked.

“Even if I sell the whole world, and my life, I won’t
be able to purchase this priceless stone.”

Stunned and confused, the boy returned to the grandpa and told him what had happened.

“Now tell me what is the value of life, grandpa?”

Grandpa said,

“The answers you got from the Orange Seller, the Vegetable Seller, the Jeweler & the Precious Stone’s Seller explain the value of our life…

You may be a precious stone, even priceless, but, people will value you based on their intellectual status, their level of information, their belief in you, their motive behind entertaining you, their ambition, their risk taking ability & ultimately their calibre.

So don’t fear, you will surely find someone who will discern your true value.”

Respect yourself.

Don’t sell yourself cheap.

You are rare, Unique, Original and the only one of ur kind.

Your are a masterpiece because u r  the MASTER’S PIECE.

No one can Replace you.

Have a Great Life

Life to live

Once upon a time there was a person who had a deep desire to succeed more, and wanted to do so many things after making more money and acquiring few more assets.

Months passed, years passed, that person raised the bar of success and got busier and busier in work and asset creation, and forgot to enjoy life and speaking with friends, taking a holiday, a nap in the afternoon, walk in the garden.

Many years later the person reflected the way the life had panned out, only to notice that nothing fun was being done and all the time was spent in running behind success which was meaningless at the end when the person was in a hospital getting a dialysis done to stay alive and live for some more time.

 

Suddenly the person woke up from the bed, and realized it was just a dream, and that the person has full life to live and decide what to do with life.

WHEN TO BE SILENT

1.  Be silent – in the heat of
     anger.

2.  Be silent – when you don’t
     have all the facts.

3.  Be silent – when you
     haven’t verified the story.

4.   Be silent – if your words
     will offend a weaker Person.

5.  Be silent – when it is time
     to listen.

6.  Be silent – when you are
     tempted to make light of
     holy things.

7.  Be silent – when you are
     tempted to joke about  sin.

8.  Be silent – if you would be
     ashamed of your word  later.

9.  Be silent – if your words
     would convey the wrong
     impression.

10. Be silent – if the issue is
      none of your business.

11. Be silent – when you are
      tempted to tell an  outright lie.

12. Be silent – if your words
      will damage someone  else’s reputation.

13. Be silent – if your words
      will damage a friendship.

14. Be silent – when you are
      feeling critical.

15. Be silent – if you can’t 
      say it without screaming.

16. Be silent – if your words
      will be a poor reflection
      of your friends and family.

17. Be silent – if you may  
       have to eat your words
       later.

18. Be silent – if you have
       already said it more
       than one time.

19. Be silent – when you are
      tempted to flatter a
      wicked person.

20. Be silent – when you are
      supposed to be working
      instead.

21. Be silent – when your
       words do not do any
       good to anyone
       including yourself.

“WHOEVER GUARDS HIS MOUTH AND TONGUE KEEPS HIS SOUL FROM TROUBLES”

7 Little Truths

 

Swami Vivekananda’s 7 Little Truths:

1st
Don’t let someone become a priority in your life, when you are just an option in their life. Relationships work best when they are balanced…

2nd
Never explain yourself to anyone. Because the person who likes you doesn’t need it and the person who doesn’t like you won’t believe it…

3rd
When you keep saying you are busy, then you are never free. When you keep saying you have no time, then you will never have time. When you keep saying that you will do it tomorrow, then your tomorrow will never come…

4th
When we wake up in the morning, we have two simple choices. Go back to sleep and dream, or wake up and chase those dreams.
Choice is yours…

5th
We make them cry who care for us.    We cry for those who never care for us. And we care for those who will never cry for us. This is the truth of life, it’s strange but true. Once you realize this, it’s never too late to change…

6th
Don’t make promises when you are in joy. Don’t reply when you are sad.
Don’t take decision when you are angry. Think twice, act once…

7th
Time is like river. You can’t touch the same water twice, because the flow that has passed will never pass again

“Someone Asked Swami Vivekananda:
“What is poison?”
He had given a great answer:
“Everything excess in life, is poison”

Deep Roots in a Shallow Culture

In two independent houses,separated by a compound two people were living, in one a retired person and in the other a techie.
They had planted identical saplings on either sides of the compound.

The techie used to give lot of water and manure to the plants.The retired,just small quantity of water and little manure.
The techies plant grew into lush green,leafy robust plant.

The retired person’s plant was a near normal but much luxuriant than his neighbor’s.

One night there was a heavy rain with gusty wind.

Next morning both came out to see the fate of the plants.

To techie’s surprise his plant had got uprooted where as his neighbor’s was unharmed.
Techie asks the retired as why his plant was uprooted despite such a good care where as the neighbor had hardly cared.

The retired person’s answer should be a lesson for all of us.
“Look young man, you had supplied every thing a plant would need,in abundance and the plant did not have to go in search of it.Your roots did not have go down. I was supplying just enough to keep it alive. For the rest roots had to go down into the ground to fulfil it’s needs. Since your roots were superficial the rain and wind could easily fell it.
Since my roots were pretty deeply grounded they could withstand the onslaught of the nature.
The same applies to your children too.
”