fixing bug 3777

Fixing bug 3777
Remake of https://github.com/Itseez/opencv/pull/2945