Shift image content with OpenCV

后端 未结 9 1196
-上瘾入骨i
-上瘾入骨i 2020-12-08 04:36

Starting from an image, I would like to shift its content upward of 10 pixels, without changing size and filling in black the sub image (width x 10px) on the bo

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 05:16

    Here is a function I wrote, based on Zaw Lin's answer, to do frame/image shift in any direction by any amount of pixel rows or columns:

    enum Direction{
        ShiftUp=1, ShiftRight, ShiftDown, ShiftLeft
       };
    
    cv::Mat shiftFrame(cv::Mat frame, int pixels, Direction direction)
    {
        //create a same sized temporary Mat with all the pixels flagged as invalid (-1)
        cv::Mat temp = cv::Mat::zeros(frame.size(), frame.type());
    
        switch (direction)
        {
        case(ShiftUp) :
            frame(cv::Rect(0, pixels, frame.cols, frame.rows - pixels)).copyTo(temp(cv::Rect(0, 0, temp.cols, temp.rows - pixels)));
            break;
        case(ShiftRight) :
            frame(cv::Rect(0, 0, frame.cols - pixels, frame.rows)).copyTo(temp(cv::Rect(pixels, 0, frame.cols - pixels, frame.rows)));
            break;
        case(ShiftDown) :
            frame(cv::Rect(0, 0, frame.cols, frame.rows - pixels)).copyTo(temp(cv::Rect(0, pixels, frame.cols, frame.rows - pixels)));
            break;
        case(ShiftLeft) :
            frame(cv::Rect(pixels, 0, frame.cols - pixels, frame.rows)).copyTo(temp(cv::Rect(0, 0, frame.cols - pixels, frame.rows)));
            break;
        default:
            std::cout << "Shift direction is not set properly" << std::endl;
        }
    
        return temp;
    }
    

提交回复
热议问题