You seem to be lacking the context of your X server.
The easiest way to make this work is to login graphically, then open a terminal, then start your application. This means, not opening a session for another user, e.g. root.
If you want to run the program as another user or from remote, you need other solutions. Please specify what you are doing. It is a common problem (it is about authorization) with common solutions depending on your use-case! It is not a OpenCV-related problem.