• Stars
    star
    523
  • Rank 84,663 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This project demonstrates how to do pixel operations in swift.

Swift Image Processing

This project contains swift playgrounds that demonstrate how to do pixel operations in swift.

  • Swift4 : checkout master branch
  • Swift3.x : checkout syntax/swift3.x branch
  • Swift2.x : checkout syntax/swift2.x branch

Thanks to RGBAImage

Convert UIImage to RGBA Image

RGBAImage has pixels flat memory. You can access pixels with index directly.

Contrast

This is example for pixel operation

let rgba = RGBAImage(image: UIImage(named: "monet")!)!


var totalR = 0
var totalG = 0
var totalB = 0

rgba.process { (pixel) -> Pixel in
    totalR += Int(pixel.R)
    totalG += Int(pixel.G)
    totalB += Int(pixel.B)
    return pixel
}

let pixelCount = rgba.width * rgba.height
let avgR = totalR / pixelCount
let avgG = totalG / pixelCount
let avgB = totalB / pixelCount



func contrast(_ image: RGBAImage) -> RGBAImage {
    
    image.process { (pixel) -> Pixel in
        var pixel = pixel
        let deltaR = Int(pixel.R) - avgR
        let deltaG = Int(pixel.G) - avgG
        let deltaB = Int(pixel.B) - avgB
        pixel.R = UInt8(max(min(255, avgR + 3 * deltaR), 0)) //clamp
        pixel.G = UInt8(max(min(255, avgG + 3 * deltaG), 0))
        pixel.B = UInt8(max(min(255, avgB + 3 * deltaB), 0))
        
        return pixel
    }
    return image
}

let newImage = contrast(rgba).toUIImage()

Grab color space

Grab Red component

func grabR(_ image: RGBAImage) -> RGBAImage {
    var outImage = image
    outImage.process { (pixel) -> Pixel in
        var pixel = pixel
        pixel.R = pixel.R
        pixel.G = 0
        pixel.B = 0
        return pixel
    }
    return outImage
}

Grab Green component

func grabG(_ image: RGBAImage) -> RGBAImage {
    var outImage = image
    outImage.process { (pixel) -> Pixel in
        var pixel = pixel
        pixel.R = 0
        pixel.G = pixel.G
        pixel.B = 0
        return pixel
    }
    return outImage
}

Grab Blue component

func grabB(_ image: RGBAImage) -> RGBAImage {
    var outImage = image
    outImage.process { (pixel) -> Pixel in
        var pixel = pixel
        pixel.R = 0
        pixel.G = 0
        pixel.B = pixel.B
        return pixel
    }
    return outImage
}

Compose RGB Color components

public static func composite(_ rgbaImageList: RGBAImage...) -> RGBAImage {
        let result : RGBAImage = RGBAImage(width:rgbaImageList[0].width, height: rgbaImageList[0].height)
        for y in 0..<result.height {
            for x in 0..<result.width {
                
                let index = y * result.width + x
                var pixel = result.pixels[index]
                
                for rgba in rgbaImageList {
                    let rgbaPixel = rgba.pixels[index]
                    pixel.Rf = pixel.Rf + rgbaPixel.Rf
                    pixel.Gf = pixel.Gf + rgbaPixel.Gf
                    pixel.Bf = pixel.Bf + rgbaPixel.Bf
                }
                
                result.pixels[index] = pixel
            }
        }
        return result
    }

RGB to Gray

public static func gray5(_ image: RGBAImage) -> RGBAImage {
        var outImage = image
        outImage.process { (pixel) -> Pixel in
            var pixel = pixel
            let result = sqrt(pow(pixel.Rf, 2) + pow(pixel.Rf, 2) + pow(pixel.Rf, 2))/sqrt(3.0)
            pixel.Rf = result
            pixel.Gf = result
            pixel.Bf = result
            return pixel
        }
        return outImage
}
let rgba5 = RGBAImage(image: UIImage(named: "monet")!)!
gray5(rgba5).toUIImage()

Refactoring Split Color Space

public static func splitRGB(_ rgba: RGBAImage) -> (ByteImage, ByteImage, ByteImage) {
    let R = ByteImage(width: rgba.width, height: rgba.height)
    let G = ByteImage(width: rgba.width, height: rgba.height)
    let B = ByteImage(width: rgba.width, height: rgba.height)
    
    rgba.enumerate { (index, pixel) -> Void in
        
        R.pixels[index] = pixel.R.toBytePixel()
        G.pixels[index] = pixel.G.toBytePixel()
        B.pixels[index] = pixel.B.toBytePixel()
    }
    
    return (R, G, B)
}

ByteImage has only one color component.

Images ADD, SUB, MUL, DIV

public static func op(_ functor : (Double, Double) -> Double, rgbaImage1: RGBAImage, rgbaImage2: RGBAImage) -> RGBAImage {
    let result : RGBAImage = RGBAImage(width:rgbaImage1.width, height: rgbaImage1.height)
    for y in 0..<result.height {
        for x in 0..<result.width {
            
            let index = y * result.width + x
            var pixel = result.pixels[index]
            
            let rgba1Pixel = rgbaImage1.pixels[index]
            let rgba2Pixel = rgbaImage2.pixels[index]
            
            
            pixel.Rf = functor(rgba1Pixel.Rf, rgba2Pixel.Rf)
            pixel.Gf = functor(rgba1Pixel.Gf, rgba2Pixel.Gf)
            pixel.Bf = functor(rgba1Pixel.Bf, rgba2Pixel.Bf)
            
            result.pixels[index] = pixel
        }
    }
    return result   
}

public static func add(rgba1: RGBAImage, _ rgba2: RGBAImage) -> RGBAImage {
    return op((+), rgbaImage1: rgba1, rgbaImage2: rgba2)
}

Blending

public static func blending(_ img1: RGBAImage, _ img2: RGBAImage, alpha: Double) -> RGBAImage {
    let result : RGBAImage = RGBAImage(width:img1.width, height: img1.height)
    for y in 0..<result.height {
        for x in 0..<result.width {
            
            let index = y * result.width + x
            var pixel = result.pixels[index]
            
            let pixel1 = img1.pixels[index]
            let pixel2 = img2.pixels[index]
            
            
            pixel.Rf = alpha * pixel1.Rf + (1.0 - alpha) * pixel2.Rf
            pixel.Gf = alpha * pixel1.Gf + (1.0 - alpha) * pixel2.Gf
            pixel.Bf = alpha * pixel1.Bf + (1.0 - alpha) * pixel2.Bf
            
            result.pixels[index] = pixel
        }
    }
    return result
}

Brightness

public static func brightness(_ img1: RGBAImage, contrast: Double, brightness: Double) -> RGBAImage {
    let result : RGBAImage = RGBAImage(width:img1.width, height: img1.height)
    for y in 0..<result.height {
        for x in 0..<result.width {
            
            let index = y * result.width + x
            var pixel = result.pixels[index]
            
            let pixel1 = img1.pixels[index]
            
            pixel.Rf = pixel1.Rf * contrast + brightness
            pixel.Gf = pixel1.Gf * contrast + brightness
            pixel.Bf = pixel1.Bf * contrast + brightness
            
            result.pixels[index] = pixel
        }
    }
    return result
}

Convolution

public static func convolution(_ image: ByteImage, mask: Array2D<Double>) -> ByteImage {
    var image = image
    let height = image.height
    let width  = image.width
    
    let maskHeight = mask.rowCount()
    let maskWidth  = mask.colCount()
    
    for y in 0..<height - maskHeight + (maskHeight-1)/2 {
        for x in 0..<width - maskWidth + (maskWidth-1)/2 {
            var v = 0.0
            if (y+maskHeight > height) || (x+maskWidth) > width {
                continue
            }
            
            for my in 0..<maskHeight {
                for mx in 0..<maskWidth {
                    let tmp = mask[my, mx]
                    v = v + (image.pixel(x+mx, y+my)!.Cf * tmp)
                }
            }
            
            v = clamp(v, lower: 0.0, upper: 1.0)
            print(v)
            let pixel = BytePixel(value: v)
            let xx = x+(maskWidth-1)/2
            let yy = y+(maskHeight-1)/2
            image.setPixel(xx, yy, pixel)
        }
    }
    return image
}

Sharpening

let m1 = Array2D(cols:3, rows:3,
    [ 0.0/5.0, -1.0/5.0, 0.0/5.0,
     -1.0/5.0,  9.0/5.0,-1.0/5.0,
      0.0/5.0, -1.0/5.0, 0.0/5.0])
ImageProcess.convolution(R.clone(), mask: m1).toUIImage()

Bluring

let m2 = Array2D(cols: 3, rows: 3,
    [
         1.0/9.0, 1.0/9.0, 1.0/9.0,
         1.0/9.0, 1.0/9.0, 1.0/9.0,
         1.0/9.0, 1.0/9.0, 1.0/9.0,
    ]
)
ImageProcess.convolution(R.clone(), mask: m2).toUIImage()

MIT License

The MIT License

Copyright ยฉ 2015 Sungcheol Kim, https://github.com/skyfe79/SwiftImageProcessing

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

AndroidGradientImageView

AndroidGradientImageView is a simple imageview which overlays gradient on its content.
Java
218
star
2

LearningOpenGLES2

Learning OpenGL ES 2 in Swift
Swift
201
star
3

FAImageView

FAImageView is a Frame Animation ImageView for Android.
Java
187
star
4

LearningOpenGLES2-Android

Learning OpenGL ES 2 in Java for Android
Java
185
star
5

AndroidChannel

AndroidChannel is helper library for thread communication between mainthread and workerthread
Java
81
star
6

AndroidOperationQueue

AndroidOperationQueue is a tiny serial operation queue for Android.
Java
50
star
7

AnimateGradientView

AnimateGradientView is android library to make gradient flow or rotate infinitely
Java
47
star
8

FragmentNavigationController

FragmentNavigationController is a convenient utility library to navigate fragments on Android.
Java
35
star
9

AndroidGLKit

AndroidGLKit provides OpenGL ES 2.0 boilerplate codes for Android.
Java
22
star
10

HashGirl

HashGirl is a simple library to make a linkable string for Android.
Java
20
star
11

RxGitSearch

RxGitSearch is iOS demo app searching github repositories. It uses some Rx techniques to achieve flexible, auto ui update, no dependencies and others.
Swift
19
star
12

KeyboardEditText

KeyboardEditText provides keyboard's shown and hidden event listener for you.
Java
18
star
13

hugo-with-github-issues

hugo-with-github-issues
JavaScript
10
star
14

SGL

Software 3D Graphics Rendering Library
C++
9
star
15

UsingSwiftAndCpp

It demonstrated how to use swift and c++ on same project space.
Swift
6
star
16

VideoSplashView

VideoSplashView is a simple video view for making Splash Scene that contains video.
Swift
5
star
17

GLUT-Tutorial

glut tutorial
C++
4
star
18

Awesome

My Awesome from the starred repos ๐Ÿ˜‹
4
star
19

RxPlayground

Learn RxSwift
Swift
3
star
20

OpenGL-ES-Tutorials

Objective-C
3
star
21

OpenGLTutorial

OpenGL Tutorial
C++
3
star
22

SwiftTypeEraserWrapper

TypeEraserWrapper ์— ๋Œ€ํ•œ ๋ธ”๋กœ๊ทธ ๊ธ€ ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.
Swift
3
star
23

AndroidCameraInfo

print camera infos to textview
Java
2
star
24

AVFoundation

about AVFoundation
Objective-C
2
star
25

github-actions-starter-kit

Github Actions starter kit to create actions in javascript
JavaScript
2
star
26

LearningCoreGraphics

Learning Core Graphics in Swift
Swift
1
star
27

HelloFFmpeg

FFmpeg & SDL with XCode
C
1
star
28

blog.contents

My Blog Contents
HTML
1
star
29

TIL

Today I learned
Objective-C
1
star
30

AndroidKommon

Collection of Android utility extentions in Kotlin
Java
1
star
31

iOSToolkit

iOS ๊ฐœ๋ฐœ์— ํ•„์š”ํ•œ ์œ ํ‹ธ๋ฆฌํ‹ฐ ๋ฐ ํ™•์žฅ์„ ๋ชจ์•„ ๋†“๋Š”๋‹ค
Objective-C
1
star
32

AndroidActivity

AndroidActivity provides lifecycle callback methods from the aspect of view. If you use these callback methods, you don't have to use ViewTreeObserver.
Java
1
star
33

awesome-readme-generator

Generate Awesome Readme.md from your Github starred repos ;)
JavaScript
1
star