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.
Please let me know if you have any concern with this change.