Skip to content

Instantly share code, notes, and snippets.

@a-maumau
Last active January 1, 2023 14:19
Show Gist options
  • Save a-maumau/93bde376a441548488e367d4f5b1413d to your computer and use it in GitHub Desktop.
Save a-maumau/93bde376a441548488e367d4f5b1413d to your computer and use it in GitHub Desktop.
Use OpenCV on macOS with C++

update 2023/1/1 (check on macOS Monterey, Homebrew 3.6.16)

basically, this is a copy of https://gist.github.com/nkcr/6f5c6db4dccd3b32e8ba

followings are done on macOS Catalina

Install opencv with brew

brew install opencv
# Be sure to have pkg-config, otherwise install it
brew install pkg-config

Set pkg-config path

# be sure to have pkg-config var set correctly
# in your shell config file, add following if it was not included
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig/

it seems the default path of pkgconfig is looking /usr/lib/pkgconfig which may not writable.

Copy opencv.pc

it seems installing from brew will make some version specific folder and .pc file /usr/local/Cellar/opencv/{some_version}/lib/pkgconfig/opencv{version}.pc.

in my case, it was /usr/local/Cellar/opencv/4.5.4_3/lib/pkgconfig/opencv4.pc.

updated

in some version (newer) of brew, it will install in /opt/homebrew/Cellar/opencv.
so the .pc will be in /opt/homebrew/Cellar/opencv/4.7.0/lib/pkgconfig/opencv4.pc


you need to copy or simlink this .pc file into PKG_CONFIG_PATH which you set in the previous section.

in the following code, I will show a example on my environment (version of opencv).

# change the name of opencv4.pc to opencv.pc for convenient.
# this opencv4.pc should depends on what ver. of opencv you have installed.

# copy
cp /usr/local/Cellar/opencv/4.5.4_3/lib/pkgconfig/opencv4.pc /usr/local/lib/pkgconfig/opencv.pc
# or
# simlink
ln -s  /usr/local/Cellar/opencv/4.5.4_3/lib/pkgconfig/opencv4.pc /usr/local/lib/pkgconfig/opencv.pc

Compile

# in my environment I need to set standard to c++11
g++ --std=c++11 `pkg-config --libs --cflags opencv` my_opencv.cpp

NOTE: if you just copy the opencv"4".pc, you need to use opencv4.pc in the pkg-config args

actually, I wrote almost same thing in the past... com'on it is 2021, this kind of things should be gone. https://gist.github.com/a-maumau/767e74995158773b99df379fde202bae

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment