OpenCV - Getting Started

Submitted by admin on

Using OpenCV 3.0, Python 2.7 Windows

After installing, I tested basic functions:

  • Read/write/display image: awesome - very easy
  • Read a video: no problems
  • Write a video: erros

Writing a video

Setup for write:

cap = cv2.VideoCapture('testdata/testmovie.mp4')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (800,600))

This (MJPEG) is the only codec that worked out of the box. I think it is built-in. Other codecs will require some configuration (see below). Note that the frame size must match the input frame size.

Refer to StackOverflow. question for details.

Other codecs via ffmpeg

OpenCV (pre-built for Windows) has a ffmpeg dll. Set the PATH to see it. (eg. "C:\opencv\sources\3rdparty\ffmpeg"). Then you can use other codecs (eg. DIVX)

Regions of Interest ROI

Since OPenCV for Python uses NumPy, an image is a 2D array in NumPy.

To use regions, it's:

newimage = oldimage[y-start:y-end,x-start:x-end]

With the benefits of using negative for cropping, and nothing for array-size. For example:

cropBottom50Px = oldimage[:-50,:]    # blanks mean "use the existing size, negative means start from the end