Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Filter every 4th item from array

I'm trying to implement an image algorithm that iterates the byte array of the image.

(I'm trying to replicate this in Swift... https://rosettacode.org/wiki/Percentage_difference_between_images#JavaScript)

However, I need to ignore the alpha byte.

I was trying to be clever about it but got to the point where I can no longer remove the 4th items from the arrays of bytes.

Is there an easy way of doing that?

func compareImages(image1: UIImage, image2: UIImage) -> Double {
    // get data from images
    guard let data1 = UIImageJPEGRepresentation(image1, 1),
        let data2 = UIImageJPEGRepresentation(image2, 1) else {
            return -1
    }

    // zip up byte arrays
    return zip([UInt8](data1), [UInt8](data2))
        // sum the difference of the bytes divided by 255
        .reduce(0.0) { $0 + Double(abs(Int32($1.0) - Int32($1.1))) / 255.0 }
        // divide by the number of rbg bytes
        / Double(image1.size.width * image1.size.height * 3)
}

This would do exactly what I needed if I was able to remove/ignore the 4th bytes from each array?

The other option is to stride the arrays 4 at a time like it does in the Javascript example linked to but I felt I preferred this method. :)

like image 698
Fogmeister Avatar asked Jun 10 '26 09:06

Fogmeister


2 Answers

i think you can remove alpha with this

  1. enumerate to get pair (index, element)
  2. filter to remove alpha
  3. map to convert pair to only element

example code:

var array = [0,1,2,3,4,5,6,7,8,9]

array = array.enumerated().filter { index, element in
    return index % 4 != 3
}.map { index, element in
    return element
}

print(array) // [0,1,2,4,5,6,8,9]
like image 171
Adrian Bobrowski Avatar answered Jun 11 '26 21:06

Adrian Bobrowski


Swift 3:

var array = [0,1,2,3,4,5,6,7,8,9]

array = array.enumerated().flatMap { index, element in
    index % 4 != 3 ? element : nil
}

print(array) // [0,1,2,4,5,6,8,9]
like image 45
jazzgil Avatar answered Jun 11 '26 23:06

jazzgil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!