LoginSignup
0
0

More than 3 years have passed since last update.

Desktop : OpenCV Merge Two Images In Any Shape

Posted at
Goal

Test OpenCV merge two image with ROI.

OpenCV_MergeTwoImgAnyShape.java
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class OpenCV_MergeTwoImgAnyShape {

    public static void main( String[] args )
    {
        try{
            System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
            //大圖(母圖)
            Mat source = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\ncku.jpg",Imgcodecs.CV_LOAD_IMAGE_COLOR);

            //小圖(子圖)
            Mat source1 = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\jelly_studio_logo.jpg",Imgcodecs.CV_LOAD_IMAGE_COLOR);
            Mat destination=source.clone();


            // to make the white region transparent
            Mat mask2=new Mat();
            Mat dst=new Mat();


            Imgproc.cvtColor(source1,mask2,Imgproc.COLOR_BGR2GRAY);
            Imgproc.threshold(mask2,mask2,230,255, Imgproc.THRESH_BINARY_INV);
            List<Mat> planes = new ArrayList<Mat>() ;
            List<Mat> result = new ArrayList<Mat>() ;
            Mat result1=new Mat();
            Mat result2=new Mat();
            Mat result3=new Mat();


            Core.split(source1, planes);

            Core.bitwise_and(planes.get(0), mask2, result1);
            Core.bitwise_and(planes.get(1), mask2, result2);
            Core.bitwise_and(planes.get(2), mask2, result3);

            result.add(result1);
            result.add(result2);
            result.add(result3);
            Core.merge(result, dst);
            //以上白色變透明


            //再把小圖copy到大圖
            Rect roi=new Rect(50,50,90,62);//不能比原圖大,及小
            Mat destinationROI = source.submat( roi );
            dst.copyTo( destinationROI , dst);


            Imgcodecs.imwrite("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\merge3.jpg", source);
        }catch (Exception e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}
Result

merge3.jpg

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0