0

I got this error to compare two contourAreas in openCV project.

java.lang.IllegalArgumentException: Comparison method violates its general contract!

And I've tried:

        Collections.sort(contours) { o1, o2 ->
            val area1 = Imgproc.contourArea(o1)
            val area2 = Imgproc.contourArea(o2)
            (area2 - area1).toInt()
        }
        contours.sortWith(Comparator { o1, o2 ->
            val area1 = Imgproc.contourArea(o1)
            val area2 = Imgproc.contourArea(o2)
            (area2 - area1).toInt()
        })

And I thought those above are dubious so I tried:

        contours.sortWith(Comparator { o1, o2 ->
            val area1 = Imgproc.contourArea(o1)
            val area2 = Imgproc.contourArea(o2)
            val res = (area2 - area1)

            if (res > 0) {
                return@Comparator 1
            } else if(res < 0){
                return@Comparator -1
            }
            return@Comparator 0
        })

But none of them worked properly and my app crushed. How can I solve this problem?

c-an
  • 2,613
  • 2
  • 21
  • 55
  • Does this answer your question? ["Comparison method violates its general contract!"](https://stackoverflow.com/questions/8327514/comparison-method-violates-its-general-contract) – Pawel Mar 30 '20 at 01:20
  • From my zero knowledge of OpenCV, that comparator _looks_ transitive...does `Imgproc.contourArea` not always return the same value for the same object? – Ryan M Mar 30 '20 at 04:05
  • It uses camera, so, yeah, it changes in every single frame. – c-an Mar 30 '20 at 05:38

0 Answers0