Compiling OpenCV with MinGW-GCC and Developing in VSCode on Windows

0. Introduction

OpenCV (Open Source Computer Vision Library: http://opencv.org) is an open-source library that contains hundreds of computer vision algorithms. It is essentially a C++ API, rather than the C-based OpenCV 1.x API (the C API has been deprecated since the release of OpenCV 2.4 and has not been tested with C compilers). Since OpenCV’s official compilation support for the Visual Studio IDE on Windows is quite comprehensive, using GCC can be more troublesome. Therefore, this article explores how to compile OpenCV with MinGW-GCC on Windows and reference it for development in VSCode.Note: When developing with OpenCV on Windows, I still strongly recommend using Visual Studio. Using GCC with an editor for OpenCV compilation and development is overly cumbersome and does not provide a better experience than installing the bulky Visual Studio and then using OpenCV.

The platform and tools I used: Win11, MinGW-GCC (15.2.0), CMake (4.1.0), VSCode

1. Download OpenCV Source Code and Compile with GCC

① Environment preparation and dependency installation: Open the MSYS2 UCRT64 terminal, update the system, and install the necessary development tools and dependencies:

# Update the system
pacman -Syu
# If prompted to close the terminal, close it and reopen MSYS2 UCRT64, then run again:
pacman -Su
# Install the compilation toolchain
pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-ninja git
# Install OpenCV core dependencies
pacman -S mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-eigen3 mingw-w64-ucrt-x86_64-openblas
# Install GUI support dependencies (GTK3)
pacman -S mingw-w64-ucrt-x86_64-gtk3
# Install video and image codec libraries
pacman -S mingw-w64-ucrt-x86_64-ffmpeg mingw-w64-ucrt-x86_64-libjpeg-turbo mingw-w64-ucrt-x86_64-libpng mingw-w64-ucrt-x86_64-libtiff mingw-w64-ucrt-x86_64-libwebp mingw-w64-ucrt-x86_64-openjpeg2
# Install Fortran compiler (to resolve CMake configuration errors)
pacman -S mingw-w64-ucrt-x86_64-gcc-fortran
# Install extraction tool (to extract OpenCV source code)
pacman -S umzip

② Download the OpenCV source code by executing the following in the MSYS2 UCRT64 terminal:

# Navigate to home directory
cd ~
# Download OpenCV 4.12.0 source code
wget -O opencv-4.12.0.zip https://codeload.github.com/opencv/opencv/zip/refs/tags/4.12.0
unzip opencv-4.12.0.zip
# Download OpenCV contrib module source code
wget -O opencv_contrib-4.12.0.zip https://codeload.github.com/opencv/opencv_contrib/zip/refs/tags/4.12.0
unzip opencv_contrib-4.12.0.zip

③ Compile and install OpenCV:

# Create build directory and enter it:
mkdir -p ~/build-opencv-ucrt
cd ~/build-opencv-ucrt
# Run CMake for configuration:
cmake -G "Ninja" \
  -DCMAKE_BUILD_TYPE=RELEASE \
  -DCMAKE_INSTALL_PREFIX=/ucrt64 \
  -DBUILD_SHARED_LIBS=ON \
  -DOPENCV_EXTRA_MODULES_PATH=/home/$(whoami)/opencv_contrib-4.12.0/modules \
  -DWITH_GTK=ON \
  -DWITH_FFMPEG=ON \
  -DBUILD_EXAMPLES=OFF \
  -DBUILD_opencv_apps=OFF \
  ~/opencv-4.12.0
# This process takes a long time
# Start compilation (adjust -j parameter based on CPU core count):
ninja -j$(nproc)
# Or specify the number of cores, e.g.:
ninja -j8
# This process takes a long time
# Install to system directory:
ninja install
# Verify installation:
# Check library files
ls /ucrt64/x64/mingw/lib/libopencv*
# Check header files
ls /ucrt64/include/opencv2/
# Check version
cat /ucrt64/include/opencv2/core/version.hpp | grep "CV_VERSION_"

2. Create VS Code Project and Configuration

① Create project directory structure:

helloopencv/
├── .vscode/
│   ├── tasks.json
│   └── launch.json
├── src/
│   └── main.cpp
└── test_image.jpg (test image)

② Input test code in <span>src/main.cpp</span>:

#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
    cv::Mat image = cv::imread("test_image.jpg"); // Read image from project root directory
    if(image.empty()) {
        std::cout << "Could not open or find the image!" << std::endl;
        return -1;
    }
    cv::namedWindow("Hello OpenCV", cv::WINDOW_AUTOSIZE);
    cv::imshow("Hello OpenCV", image);
    cv::waitKey(0);
    cv::destroyAllWindows();
    std::cout << "OpenCV test completed successfully!" << std::endl;
    return 0;
}

③ Configure <span>tasks.json</span> (for compilation):

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "Build Hello OpenCV (UCRT64)",
            "command": "D:/msys64/ucrt64/bin/g++.exe", // Modify according to your MSYS2 installation path
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "-std=c++17",
                "${workspaceFolder}/src/main.cpp",
                "-o", "${workspaceFolder}/build/helloopencv.exe",
                "-LD:/msys64/ucrt64/x64/mingw/lib", // Modify according to your MSYS2 installation path
                "-lopencv_core4120",
                "-lopencv_highgui4120",
                "-lopencv_imgcodecs4120",
                "-lopencv_imgproc4120",
                "-lopencv_videoio4120"
            ],
            "options": {
                "cwd": "${workspaceFolder}" // Set working directory to project root
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": ["$gcc"]
        }
    ]
}

④ Configure <span>launch.json</span> (for debugging):

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch Hello OpenCV",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/helloopencv.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}", // Set working directory to project root
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "D:/msys64/ucrt64/bin/gdb.exe", // Modify according to your MSYS2 installation path
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "Build Hello OpenCV (UCRT64)" // Compile before debugging
        }
    ]
}

⑤ Copy the relevant DLL files:<span>libopencv_core4120.dll</span>, <span>libopencv_highgui4120.dll</span>, <span>libopencv_imgcodecs4120.dll</span>, <span>libopencv_imgproc4120.dll</span>, <span>libopencv_videoio4120.dll</span> from <span>D:\msys64\ucrt64\x64\mingw\bin</span> (the directory of dynamic link libraries) to <span>D:\projects\helloopencv\build</span> (the build folder under the project directory, where the <span>.exe</span> file is generated), otherwise, an error will occur during debugging (because the required DLL files cannot be found). (Be sure to modify these two directories according to your MSYS2 installation path and project location.)⑥ After that, press <span>F5</span>, select <span>(gdb) Launch Hello OpenCV</span>, and you can start compiling and debugging.

3. Conclusion

Now we have successfully compiled OpenCV with MinGW-GCC on Windows and referenced it for development in VSCode. Readers can follow my WeChat public account:Jiang Lan’s Code Space, where I will periodically share my thoughts and life insights. Thank you~

Leave a Comment