Home > Back-end >  Shift image in OpenCV
Shift image in OpenCV

Time:11-20

I want to shift an image upward of 10 pixels without changing the size of the image. I know there was a very similar question about this but there is no information on the web on how to do it using Java. OpenCV Documentation also doesn't say anything about this.

Original image:

enter image description here

Shifted image should look like this:

enter image description here

I tried doing it with matrix using warpAffine() function but I don't know how to get it working and I only messed around with random values but it's only transposing the image and maybe I can't find the right function for this.

        var imagePhoto = Imgcodecs.imread("images/ZAD1/myPhoto.jpg");
        
        Point[] srcTri = new Point[3];
        srcTri[0] = new Point(0, 0);
        srcTri[1] = new Point(imagePhoto.cols() - 1, 0);
        srcTri[2] = new Point(0, imagePhoto.rows() - 1);
        Point[] dstTri = new Point[3];
        dstTri[0] = new Point(0, imagePhoto.rows()*0);
        dstTri[1] = new Point(imagePhoto.cols()*0.5, imagePhoto.rows()*0.25);
        dstTri[2] = new Point(imagePhoto.cols()*0.15, imagePhoto.rows()*0.7);
        
        Mat warpMat = Imgproc.getAffineTransform( new MatOfPoint2f(srcTri), new MatOfPoint2f(dstTri) );
        
        Mat warpDst = Mat.zeros(imagePhoto.rows(), imagePhoto.cols(), imagePhoto.type() );
        Imgproc.warpAffine(imagePhoto, warpDst, warpMat, warpDst.size() );
        
        Imgcodecs.imwrite("images/ZAD1/shiftedMyPhoto.jpg", warpDst);
    
        HighGui.imshow("image", warpDst); 
        HighGui.waitKey();

CodePudding user response:

You'll need to construct the warp mat manually to achieve this instead of using getAffineTransform. Try using warpAffine with the following Mat (untested):

Mat warpMat = new Mat( 2, 3, CvType.CV_64FC1 );
int row = 0, col = 0;
warpMat.put(row ,col, 1, 0, offsetx, 0, 1, offsety);

Sources:

Shift image content with OpenCV

declare Mat in OpenCV java

  • Related