Solves issue 3258

Hi,
this a pull request to solve issue 3258. I [already submited it once](https://github.com/Itseez/opencv/pull/1438), but due to time restrictions I could not solve all requests and it ended up closed by @vpisarev.

I think I have addressed all issues everyone has mentioned previously and I think it can be pulled this time. Please, take a look at it.