0

I am trying to convert RGB value to YUV value in Swift. Support The RGB value is (185, 206, 201). Code for conversion:

let yExp  = simd_float3(0.299, 0.587, 0.114)
let cbExp = simd_float3(-0.16874, -0.33126, 0.5)
let crExp = simd_float3(0.5, -0.41869, -0.08131)

let red   = Float(185)
let green = Float(206)
let blue  = Float(201)
let pixel = simd_float3(red, green, blue)

let y  = simd_dot(yExp, pixel)
let cr = simd_dot(crExp, pixel) + 128.0
let cb = simd_dot(cbExp, pixel) + 128.0

cr is 129.043549 in Swift. However, the result is 129.043533 when I use C# or Java.

How can I get the same result as C# and Java in Swift?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
jj200789
  • 41
  • 1
  • 4
  • I really doubt the floating point operations differ between languages... – Cristik Jan 30 '19 at 08:32
  • Perhaps a Swift "Float" is a Java "double", not a Java "float". A Java `float` only has 6 to 9 significant decimal digits precision, so the value 129.043549 exceeds that precision and is rounded to 129.043533. Try again in Java using `double`. – Andreas Jan 30 '19 at 08:46
  • 3
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Gereon Jan 30 '19 at 09:25
  • @Andreas A Swift `Float` is 32 bits : `print(MemoryLayout.size)` is 4 bytes – ielyamani Jan 30 '19 at 09:32

1 Answers1

0

Thanks guys. I found the solution, but it may not be the perfect one.

let yExp  = simd_double3(0.299, 0.587, 0.114)
let cbExp = simd_double3(-0.16874, -0.33126, 0.5)
let crExp = simd_double3(0.5, -0.41869, -0.08131)

let red   = Double(185)
let green = Double(206)
let blue  = Double(201)
let pixel = simd_double3(red, green, blue)

let y  = Float(simd_dot(yExp, pixel))
let cr = Float(simd_dot(crExp, pixel) + 128.0)
let cb = Float(simd_dot(cbExp, pixel) + 128.0)

cr will be 129.04353 when it is converted from double to float.

jj200789
  • 41
  • 1
  • 4