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?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
c-an
  • 3,543
  • 5
  • 35
  • 82
  • 1
    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
  • [mre] is required. -- you misunderstand. `contourArea` always returns the same value for the same contour... however, it will return **negative** values if the contour is a **hole** (reversed order of points) – Christoph Rackwitz Sep 15 '22 at 21:00

0 Answers0