使用 ROI 连接不同大小的图像

Join different sized images with ROI

在第一次接触 Java OpenCV(3.3.1,windows 8 x64)时,我正在尝试将两个不同大小的图像与 ROI 动态连接起来。这是我的一些代码:

Mat _mat = Utils.imageFileToMat(new File("angelina_jolie.jpg")); //Angelina's face
Mat grayMat = new Mat();
Imgproc.cvtColor(_mat, grayMat, Imgproc.COLOR_BGR2GRAY);
Rect rect = new Rect(new Point(168, 104), new Point(254, 190)); //Angelina's eye ROI
Mat truncated = _mat.submat(rect); //Angelina's eye mat

Mat merge = _mat.clone();
truncated.copyTo(merge);

//show _mat
//show truncated
//show merge

我想看的是安吉丽娜朱莉的灰度眼光。

我看到的只是断言或截断的图像(只是眼睛)。

我尝试了 copyTo(mat, mask)setOf 和很多东西,但总能得到新的断言。

我是否应该将截断的大小更改为垫子的大小以匹配大小?我怎样才能以编程方式做到这一点?

Mat::copyTo 文档:

The method copies the matrix data to another matrix. Before copying the data, the method invokes :

m.create(this->size(),this->type());

so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices.

When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.

@param m Destination matrix. If it does not have a proper size or type before the operation, it is reallocated.

由于您的 src 和 dst 图像没有相同的大小和通道,因此目标图像被重新分配并用零初始化。为避免这种情况,请确保两个图像具有相同的尺寸和通道数。

Imgproc.cvtColor(grayMat, grayMat, Imgproc.COLOR_GRAY2BGR);

现在创建一个蒙版:

Mat mask = new Mat(_mat.size(), CvType.CV_8UC1, new Scalar(0));
Imgproc.rectangle(mask, new Point(168, 104), new Point(254, 190),new Scalar(255));
// copy gray to _mat based on mask
Mat merge = _mat.clone();
grayMat.copyTo(merge,mask);