SylvainRX of Public
2/12/2017 - 5:52 PM

Extract a parallelogram area from a picture to remap it in a rectangle.No Description

Extract a parallelogram area from a picture to remap it in a rectangle.No Description

Mat * extractImageSelection(Mat &src, Point2i paramUpperLeft, Point2i paramUpperRight, Point2i paramLowerLeft)
{
    //get Src image informations
    int localWidth = src.cols;
    int localHeight = src.rows;
    
    //compute dest image information
    int localDestWidth =  (int) sqrt(pow(paramUpperRight.x - paramUpperLeft.x, 2) + pow(paramUpperRight.y - paramUpperLeft.y, 2));
    int localDestHeight = (int) sqrt(pow(paramLowerLeft.x  - paramUpperLeft.x, 2) + pow(paramLowerLeft.y  - paramUpperLeft.y, 2));
    
    //create a new image to contain the selection from the source image
    Mat * localDestImage = new Mat(localDestHeight, localDestWidth, src.type());
    
    //compute slection's upper side steep for x in function of y and left side steep for y in function of x
    double localDeltaX = (double) (paramUpperRight.y - paramUpperLeft.y) / (paramUpperRight.x - paramUpperLeft.x);
    double localDeltaY = (double) (paramLowerLeft.x  - paramUpperLeft.x) / (paramLowerLeft.y  - paramUpperLeft.y);
    
    //compute x and y increments ratio between dest and source
    double localXRatio = (double) 1 / sqrt(pow(localDeltaX, 2) + 1);
    double localYRatio = (double) 1 / sqrt(pow(localDeltaY, 2) + 1);
    
    //position conversion from dest points to source points
    for (int localDestY = 0; localDestY < localDestHeight; localDestY++) {
        for (int localDestX = 0; localDestX < localDestWidth; localDestX++) {
            
            int localXSrc = paramUpperLeft.x + localDestY * localYRatio * localDeltaY + localDestX * localXRatio;
            int localYSrc = paramUpperLeft.y + localDestX * localXRatio * localDeltaX + localDestY * localYRatio;
            
            if (localXSrc < 0 || localYSrc < 0 || localXSrc >= localWidth || localYSrc >= localHeight)
                continue;
            
            uchar* localSrcPixel = &src.ptr<uchar>(localYSrc)[localXSrc];
            uchar* localDestPixel = &localDestImage->ptr<uchar>(localDestY)[localDestX];
            
            *localDestPixel = *localSrcPixel;
        }
    }
    
    return localDestImage;
}