Writing this answer specially for MacOS users.
First to install opencv use:
brew install opencv
or brew install opencv@x (x = 2,4)
We need to have the path of opencv.pc in the PKG_CONFIG_PATH to avoid this error. When you install opencv with brew it says something like this on console
For pkg-config to find opencv@2 you may need to set:
export PKG_CONFIG_PATH="/opt/homebrew/opt/opencv@2/lib/pkgconfig"
As the error suggest the reason is that opencv is not in the PKG_CONFIG_PATH variable. First check what is inside the variable using:
echo $PKG_CONFIG_PATH
To include the location of opencv.pc to the PKG_CONFIG_PATH use this
echo 'export PKG_CONFIG_PATH="/opt/homebrew/opt/opencv/lib/pkgconfig:$PKG_CONFIG_PATH"' >> ~/.zshrc