如何在opencv java api中将MatOfPoint转换为MatOfPoint2f

时间:2012-06-30 11:08:49

标签: java android image-processing opencv

我正在尝试实现以下示例代码 question 通过使用opencv java api。要在java中实现findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);,我使用了这种语法Imgproc.findContours(gray, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

所以现在轮廓应该是List<MatOfPoint> contours = new ArrayList<MatOfPoint>();而不是vector<vector<cv::Point> > contours;

然后我需要实现这个approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);。在java api中,Imgproc.approxPolyDP接受参数为approxPolyDP(MatOfPoint2f curve, MatOfPoint2f approxCurve, double epsilon, boolean closed)。我如何将MatOfPoint转换为MatOfPoint2f?

或者有没有办法使用与c ++接口相同的向量来实现它。任何建议或示例代码都非常感谢。

3 个答案:

答案 0 :(得分:36)

MatOfPoint2f与MatOfPoint的区别仅在于元素的类型(分别为32位浮点数和32位int)。可行选项(虽然性能下降)是创建MatOfPoint2f实例并将其元素(在循环中)设置为等于源MatOfPoint的元素。

 public void fromArray(Point... lp);
 public Point[] toArray();

两个类中的方法。

所以你可以做到

 /// Source variable
 MatOfPoint SrcMtx;

 /// New variable
 MatOfPoint2f  NewMtx = new MatOfPoint2f( SrcMtx.toArray() );

答案 1 :(得分:33)

我意识到这个问题已经得到了很好的回答,但为将来发现它的人添加了一个替代方案 -

Imgproc.findContours(gray, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

for(int i=0;i<contours.size();i++){
    //Convert contours(i) from MatOfPoint to MatOfPoint2f
    contours.get(i).convertTo(mMOP2f1, CvType.CV_32FC2);
    //Processing on mMOP2f1 which is in type MatOfPoint2f
    Imgproc.approxPolyDP(mMOP2f1, mMOP2f2, approxDistance, true); 
    //Convert back to MatOfPoint and put the new values back into the contours list
    mMOP2f2.convertTo(contours.get(i), CvType.CV_32S);
}

答案 2 :(得分:17)

虽然这个问题已经得到解答,但我相信接受的答案并不是最好的。将矩阵转换为数组然后返回会带来相当大的性能损失,包括时间和内存。

相反,OpenCV已经有一个完全符合这个功能的函数:convertTo。

MatOfPoint src;
// initialize src
MatOfPoint2f dst = new MatOfPoint2f();
src.convertTo(dst, CvType.CV_32F);

我发现这个速度更快,对内存更友好。

要将MatOfPoint2f转换为MatOfPoint,请改用CvType.CV_32S。

相关问题