java - javacv 上的轮廓数量不正确?

标签 java opencv

我编写了简单的代码来检索图像中的轮廓数并获取图像中的轮廓数。但它总是给出错误的答案。请有人解释一下吗?

 import com.googlecode.javacpp.Loader;
 import com.googlecode.javacv.CanvasFrame;
 import static com.googlecode.javacpp.Loader.*;
 import static com.googlecode.javacv.cpp.opencv_core.*;
 import static com.googlecode.javacv.cpp.opencv_imgproc.*;
 import static com.googlecode.javacv.cpp.opencv_highgui.*;
 import java.io.File;
 import javax.swing.JFileChooser;

 public class TestBeam {
     public static void main(String[] args) {
         CvMemStorage storage=CvMemStorage.create();
         CvSeq squares = new CvContour();
         squares = cvCreateSeq(0, sizeof(CvContour.class), sizeof(CvSeq.class), storage);
         JFileChooser f=new JFileChooser();
         int result=f.showOpenDialog(f);//show dialog box to choose files
             File myfile=null;
             String path="";
         if(result==0){
             myfile=f.getSelectedFile();//selected file taken to myfile
             path=myfile.getAbsolutePath();//get the path of the file
         }
         IplImage src = cvLoadImage(path);//hear path is actual path to image
         IplImage grayImage    = IplImage.create(src.width(), src.height(), IPL_DEPTH_8U, 1);
         cvCvtColor(src, grayImage, CV_RGB2GRAY);
         cvThreshold(grayImage, grayImage, 127, 255, CV_THRESH_BINARY);
         CvSeq cvSeq=new CvSeq();
         CvMemStorage memory=CvMemStorage.create();
         cvFindContours(grayImage, memory, cvSeq, Loader.sizeof(CvContour.class), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
         System.out.println(cvSeq.elem_size());
         CanvasFrame cnvs=new CanvasFrame("Beam");
         cnvs.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
         cnvs.showImage(src);
         //cvShowImage("Final ", src);
         
     }
 } 

这是我使用的示例图片

enter image description here

但是代码总是返回输出 8。有人可以解释一下吗?

最佳答案

cvSeq.elem_size() 将以字节为单位返回序列元素的大小,而不是轮廓的数量。这就是每次输出都是 8 的原因。 请参阅以下链接以获取更多信息。 http://opencv.willowgarage.com/documentation/dynamic_structures.html#cvseq

要查找轮廓的数量,您可以使用以下代码段

int i = 0;
while(cvSeq != null){
i = i + 1;
cvSeq = cvSeq.h_next();
}
System.out.println(i);

使用您提供的参数,CV_RETR_EXTERNAL 将仅提供作为图像边界的外部轮廓(前提是您没有反转图像)。您可以使用 CV_RETR_LIST 获取所有轮廓。有关参数的更多信息,请访问以下链接。 http://opencv.willowgarage.com/documentation/structural_analysis_and_shape_descriptors.html#findcontours

关于java - javacv 上的轮廓数量不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11394030/

相关文章:

java - 必须单击 "Submit"按钮两次才能提交表单

opencv - 如何在指定距离内沿边缘填充颜色

opencv - 将灰度图像复制到类型 Mat_<Vec2f> 的第一个 channel

c++ - 计算梯度方向

java - 是否可以将 CockroachDB 与 Java 事务 API (JTA) 一起使用?

java - oracle XMLType 在数据库中不起作用

Java游戏编程: Smooth Jumping

java - 如果无法解析 import 语句会怎样?

c++ - Qt with opencv异常处理报错

opencv - 为什么 OpenCV Contrib Repo 3.0.0 不支持这么多 FeatureDetector 和 DescriptorExtractor?