java - 将不同尺寸的图像与 ROI 连接起来

标签 java opencv opencv3.3

第一次接触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.

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

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);

关于java - 将不同尺寸的图像与 ROI 连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189379/

相关文章:

java.lang.IllegalArgumentException : No view found for id 0x7f0c0098

java - 为什么模数很大似乎在 Java 中给出了错误的答案

Java AWT-EventQueue-0 错误

python - OpenCV for ARM (Beagleboard) 使用 YUYV 而不是 JPEG 压缩?

python - 在 OpenCV 中更改 channel 顺序会阻止绘制矩形

python-3.x - OpenCV,如何将参数传递给 cv2.TrackerMedianFlow_create 函数?

java - 在netbeans框架中制作JList

python - 如何使用 OpenCV 绘制多色分段圆?

c++ - 为什么 InputOutputArray 在构造函数中采用 const Mat& 引用?