Error initializing Nvidia encoder - cv::cudacodec::createVideoWriter

I’m working on using my RTX4070 GPU to decode and encode 4K video stream in openCV.

The decode works fine, but the program won’t initialize the cudacodec::createVideoWriter and throws an error:

Open CUDA Writer
terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.9.0-dev) /home/sd/opencv/opencv_contrib-4.x/modules/cudacodec/src/video_writer.cpp:249: error: (-217:Gpu API call) in function 'Init'
> Error initializing Nvidia Encoder. Refer to Nvidia's GPU Support Matrix to confirm your GPU supports hardware encoding, codec and surface format and check the encoder documentation to verify your choice of encoding paramaters are supported.OpenCV(4.9.0-dev) /home/sd/opencv/opencv_contrib-4.x/modules/cudacodec/src/NvEncoder.cpp:49: error: (-217:Gpu API call) Current Driver Version does not support this NvEncodeAPI version, please upgrade driver [Code = 15] in function 'LoadNvEncApi'
Aborted (core dumped)

The error says my Current Driver Version does not support this NvEncodeAPI version.

Here is my ‘nvidia-smi’.
sd@ASUS:~$ nvidia-smi

Wed May  1 15:06:36 2024       
| NVIDIA-SMI 535.171.04             Driver Version: 535.171.04   CUDA Version: 12.2     |
| GPU  Name                 Persistence-M | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |         Memory-Usage | GPU-Util  Compute M. |
|                                         |                      |               MIG M. |
|   0  NVIDIA GeForce RTX 4070        Off | 00000000:01:00.0 Off |                  N/A |
|  0%   45C    P8              13W / 200W |      8MiB / 12282MiB |      0%      Default |
|                                         |                      |                  N/A |

Here is my code snippet to init:
d_writer = cv::cudacodec::createVideoWriter(outputFilename, frame.size(), cv::cudacodec::Codec::H264, fps, cv::cudacodec::ColorFormat::BGR, 0, stream);

What else may I need to share with you that you can help me?

The encoder is more particular about the driver version than the decoder. Check the release notes

If you are using version 12.2 then you need

Linux: Driver version 550.54.14 or higher

If you can’t upgrade the driver then I would build with an earlier verison of the Nvidia Video Codec SDK which is compatible with your driver version.

THANK YOU for all your help. This problem is solved.