Skip to content

Instantly share code, notes, and snippets.

@LiberiFatali
Last active February 19, 2025 12:12
Show Gist options
  • Save LiberiFatali/592eefa60f9356529ca12c6bcc753226 to your computer and use it in GitHub Desktop.
Save LiberiFatali/592eefa60f9356529ca12c6bcc753226 to your computer and use it in GitHub Desktop.
Build OpenCV from source

Install pkg-config

sudo apt install pkg-config

This is VERY important, since we want this build of opencv-python to make use of the libraries we have already installed. Portability is no issue here. pkg-config generates .pc files that CMake will look into. Without this, CMake will not know where FFMPEG libraries are or if they are installed.

Compile opencv

1. get source

git clone --depth 1 --branch [version] https://github.com/opencv/opencv.git For example: 4.11.0 for version

2. review and change build configurations

mkdir build && cd build cmake-gui ..

Important config:

  • OPENCV_ENABLE_NONFREE (True)
  • OPENCV_GENERATE_PKGCONFIG (True)
  • PYTHON3_PACKAGES_PATH (for example: /usr/local/lib/python3.10/dist-packages)

3. start compiling

make -j[number_of_cpus] for example: make -j8

Install system wide (or user only without sudo)

sudo make install

Test

  1. python or python3, then import cv2; print(cv2.__version__)
  2. H265 codec
import cv2
dest = cv2.VideoWriter("test_dummy_hev1.mp4", cv2.VideoWriter_fourcc(*"hev1"), 25, (1920,1080))
  1. Sample video
import cv2
import numpy as np

# Video settings
output_file = "test_dummy_hev1.mp4"
fourcc = cv2.VideoWriter_fourcc(*"hev1")  # HEVC encoding
fps = 25
frame_size = (1920, 1080)
duration = 5  # seconds
total_frames = fps * duration

# Initialize VideoWriter
video_writer = cv2.VideoWriter(output_file, fourcc, fps, frame_size)

for i in range(total_frames):
    # Create a blank image (black frame)
    frame = np.zeros((frame_size[1], frame_size[0], 3), dtype=np.uint8)

    # Draw a moving rectangle
    start_x = (i * 20) % frame_size[0]  # Moving across the screen
    cv2.rectangle(frame, (start_x, 400), (start_x + 200, 700), (0, 255, 0), -1)

    # Overlay text
    text = f"Frame {i+1}/{total_frames}"
    cv2.putText(frame, text, (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 4, cv2.LINE_AA)

    # Write frame to video
    video_writer.write(frame)

# Release the video writer
video_writer.release()
print(f"Video saved as {output_file}")

What’s the difference between ‘hvc1’ and ‘hev1’ HEVC codec tags for MP4? https://community.bitmovin.com/t/whats-the-difference-between-hvc1-and-hev1-hevc-codec-tags-for-fmp4/101/2

  • hvc1 parameter sets are stored out-of-band in the sample entry (i.e. below the Sample Description Box ( stsd ) box)
  • hev1 parameter sets are stored out-of-band in the sample entry and/or in-band in the samples (i.e. SPS/PPS/VPS NAL units in the bitstream/ mdat box)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment