fixing bug #3345

Please see http://code.opencv.org/issues/3345

This is the second try to fix this bug, thanks to @apavlenko's comment on the previous PR.
https://github.com/Itseez/opencv/pull/2088

Please let me know if you have any concern with this change.