10

I want to seed randn function but I'm not able to do it.

srand(time(NULL));
Mat mymat = Mat::zeroes(1024,1024,CV_32F);
randn(mymat,0,1); 

Should it not give me random mat, named mymat, whose mean = 0, and variance = 1? However, it gives the same mymat in every run.

Here is the link for randn which claims srand to work.

I tried to give different numbers instead of time(NULL), but all have the same output randoms. I have checked the same thing from another machine, it gives the same output with the first machine. So seeding is not working.

Thanks,

smttsp
  • 4,011
  • 3
  • 33
  • 62
  • The link you supplied says you should call `srand()` **for that example implementation**, not that `srand()` will initialise `randn()` *in general*. Unfortunately, it doesn't tell you a guaranteed method to initialise `randn()`. – Toby Speight Oct 10 '17 at 08:17

1 Answers1

19

You can set seed for OpenCV functions using using the following snippet:

cv::theRNG().state = seed;

There is a subtlety for multithreaded programs - OpenCV uses thread-local random number generators so you need (re)set seed from the same thread.

Andrey Kamaev
  • 29,582
  • 6
  • 94
  • 88
  • My code is not multithreaded. Is it enough to use `cv::theRNG().state = time(NULL);` in `main` function? Then could I generate random matrices from other functions? If so, it is not working for `randn`. – smttsp Jan 29 '14 at 13:43
  • 7
    try cv::getTickCount() instead of time(NULL) – berak Jan 29 '14 at 13:48