chA*_*Ami 37 java android opencv image-processing
我正在尝试
使用opencv java api 实现以下问题的示例代码
.要findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);在java中实现,我使用了这种语法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 ++接口相同的向量来实现它.任何建议或示例代码都非常感谢.
Vik*_*pov 38
MatOfPoint2f与MatOfPoint的区别仅在于元素的类型(分别为32位浮点数和32位int).的可行的选择(虽然性能上的损失)是制造MatOfPoint2f实例并设置它的元素(在循环中)等于源MatOfPoint的元素.
有
public void fromArray(Point... lp);
public Point[] toArray();
Run Code Online (Sandbox Code Playgroud)
两个类中的方法.
所以你可以做到
/// Source variable
MatOfPoint SrcMtx;
/// New variable
MatOfPoint2f NewMtx = new MatOfPoint2f( SrcMtx.toArray() );
Run Code Online (Sandbox Code Playgroud)
esk*_*mo9 34
我意识到这个问题已经得到了很好的解答,但是为将来发现它的人添加一个替代方案 -
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 20
虽然这个问题已经得到解答,但我相信接受的答案并不是最好的.将矩阵转换为数组然后返回会带来相当大的性能损失,包括时间和内存.
相反,OpenCV已经有一个功能正是这样做:convertTo.
MatOfPoint src;
// initialize src
MatOfPoint2f dst = new MatOfPoint2f();
src.convertTo(dst, CvType.CV_32F);
Run Code Online (Sandbox Code Playgroud)
我发现这个速度更快,对内存更友好.
要将MatOfPoint2f转换为MatOfPoint,请改用CvType.CV_32S.