SciProgCentre / kmath

Kotlin mathematics extensions library
656 stars 55 forks source link

Add functions to compute Union & Intersection Area of two rectangles #484

Open AlexandreBrown opened 2 years ago

AlexandreBrown commented 2 years ago

Feature Request

Use Case

Proposal

altavir commented 2 years ago

Thanks a lot for the request. It seems like a good addition to kmath-geometry package. We need to implement shapse first though. If you have any understanding how shape API should look like, it would be welcome.

altavir commented 2 years ago

And a clarification question. In object detection you probably search for intersection of rectangles alongside axis. Is it always this way or do we need also include rotations?

AlexandreBrown commented 2 years ago

@altavir That's correct, you can expect the rectangles to always be in the same orientation.

You can think of it like an N x N grid where each cell might have a rectangle that might or might not be larger than the grid cell.

So my use case doesn't need rotation.

altavir commented 2 years ago

Here is the code you can use for now for that purpose: https://pl.kotl.in/5_rip0Gfi

import kotlin.math.min
import kotlin.math.max

infix fun ClosedRange<Double>.intersect(other: ClosedRange<Double>): ClosedFloatingPointRange<Double>? {
    val left = max(start, other.start)
    val right = min(endInclusive, other.endInclusive)
    return if(left<=right){
        left..right
    } else {
        null
    }
}

data class Rectangle(val x : ClosedFloatingPointRange<Double>, val y: ClosedFloatingPointRange<Double>)

val Rectangle.surface get() = (x.endInclusive - x.start)*(y.endInclusive - y.start)

infix fun Rectangle.intersect(other: Rectangle): Rectangle?{
    val xIntersect = x.intersect(other.x) ?: return null
    val yIntersect = x.intersect(other.x) ?: return null
    return Rectangle(xIntersect, yIntersect)
}

fun main(){
    val res = Rectangle(0.0..1.0, 0.0..1.0) intersect Rectangle(0.5..1.5, 0.5..1.5)
    println(res?.surface)
}

We will deffinitely look further into geometry package for more complex cases.