OpenCV-Python
lastmod 2025-05-26created 2016-04-2557 edits
The Python interface of OpenCV.
How to install
For reference, the default location where cv2 is installed is ${CMAKE_INSTALL_PREFIX}/lib/python2.7/site-packages/cv2.so.
Use the PIP (Unofficial)
| WARNING |
| This is an unofficial opencv-python package. |
With pip, you can install it simply as follows.
There are four different packages and you should select only one of them. Do not install multiple different packages in the same enviroment.
- Packages for standard desktop environments
- (Windows, macOS, almost any GNU/Linux distribution)
- run
pip install opencv-pythonif you need only main modules - run
pip install opencv-contrib-pythonif you need both main and contrib modules
- run
- Packages for server (headless) environments
- These packages do not contain any GUI functionality. They are smaller and suitable for more restricted environments.
- run
pip install opencv-python-headlessif you need only main modules - run
pip install opencv-contrib-python-headlessif you need both main and contrib modules
- run
Ubuntu
virtualenv install
When using virtualenv on MacOSX, you need to redefine the Python paths as follows.
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=ON \
-DCMAKE_INSTALL_PREFIX=/usr/local \
-DPYTHON2_PACKAGES_PATH=/Users/your/.pyenv/versions/your-pyenv-2.7.11/lib/python2.7/site-packages \
-DPYTHON2_LIBRARY=/Users/your/.pyenv/versions/your-pyenv-2.7.11/bin \
-DPYTHON2_INCLUDE_DIR=/Users/your/.pyenv/versions/your-pyenv-2.7.11/include/python2.7 \
..
## PYTHON2_LIBRARY 의 경우, Python library path를 지정해야 한다.
Printing build information
Video Read Write
- Getting Started with Videos
- How to Capture and Display Camera Video with Python on Jetson TX2 (OpenCV with GStreamer and python)
- Real-time panorama and image stitching with OpenCV
- Faster video file FPS with cv2.VideoCapture and OpenCV
#-*- coding:utf-8 -*-
import cv2
import sys
from numpy import array, float32
def main(input_file: str, output_file: str, headless=True):
cap = cv2.VideoCapture(input_file)
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
input_size = width, height
print("Input: ", input_file)
print("Input fps: ", fps)
print("Input size: ", input_size)
print("Input frames: ", frames)
resize_size = 1920, 1080
print("Resize size: ", resize_size)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(output_file, fourcc, fps, resize_size)
print("Output: ", output_file)
print("Output fps: ", fps)
print("Output size: ", resize_size)
try:
i = 0
while True:
# print(f"{i}/{frames}")
i += 1
ret, image = cap.read()
if not ret:
break
if image.shape[0:2] != resize_size:
image = cv2.resize(image, dsize=resize_size)
writer.write(image)
if not headless:
cv2.imshow("Preview", image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
cap.release()
writer.release()
if not headless:
cv2.destroyAllWindows()
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], True)
Capture Video from Camera
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
To pass options to FFmpeg, use the OPENCV_FFMPEG_CAPTURE_OPTIONS environment variable:
import cv2
import numpy as np
import os
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
vcap = cv2.VideoCapture("rtsp://192.168.1.2:5554/camera", cv2.CAP_FFMPEG)
while(1):
ret, frame = vcap.read()
if ret == False:
print("Frame is empty")
break;
else:
cv2.imshow('VIDEO', frame)
cv2.waitKey(1)
Playing Video from file
import numpy as np
import cv2
cap = cv2.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Saving a Video
FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org. It is platform dependent. Following codecs works fine for me.
- In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)
- In Windows: DIVX (More to be tested and added)
- In OSX : (I don’t have access to OSX. Can some one fill this?)
FourCC code is passed as cv2.VideoWriter_fourcc('M','J','P','G') or cv2.VideoWriter_fourcc(*'MJPG) for MJPG.
Below code capture from a Camera, flip every frame in vertical direction and saves it.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Crop Image
import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
Rotation Image
# 이미지의 크기를 잡고 이미지의 중심을 계산합니다.
(h, w) = cv2_image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# 이미지의 중심을 중심으로 이미지를 45도 회전합니다.
M = cv2.getRotationMatrix2D((cX, cY), 45, 1.0)
rotated_45 = cv2.warpAffine(cv2_image, M, (w, h))
Rotation Image
- Stackoverflow - OpenCV Python : rotate image without cropping sides
- Stackoverflow - Rotate an image without cropping in OpenCV in C++
- opencv-python.readthedocs.io - Geometric transformations of images
import cv2
def rotate_image(mat, angle):
"""
Rotates an image (angle in degrees) and expands image to avoid cropping
"""
height, width = mat.shape[:2] # image shape has 3 dimensions
image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape
rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)
# rotation calculates the cos and sin, taking absolutes of those.
abs_cos = abs(rotation_mat[0,0])
abs_sin = abs(rotation_mat[0,1])
# find the new width and height bounds
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
# subtract old image center (bringing image back to origo) and adding the new image center coordinates
rotation_mat[0, 2] += bound_w/2 - image_center[0]
rotation_mat[1, 2] += bound_h/2 - image_center[1]
# rotate image with the new bounds and translated rotation matrix
rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))
return rotated_mat
Troubleshooting
Merged into the OpenCV:Troubleshooting page.
See also
Favorite site
- OpenCV-Python Tutorials’s documentation!
- [Recommended] Install OpenCV 3.0 and Python 2.7+ on OSX
- Install opencv MacOSX Mavericks
- Install OpenCV 3 on Yosemite ( OSX 10.10.x )