1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】CIFilterで肌色を保ちながら画像の彩度を調整する

Posted at

はじめに

CIFilterに肌色を保ちながら彩度を調整できるといった便利なものがあったので使ってみました

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-10-24 at 20.48.47.gif

実装

import SwiftUI

struct ContentView: View {
    private let image = UIImage(named: "sample1")!

    @State private var uiImage: UIImage?
    
    @State private var amount: CGFloat = 0

    var body: some View {
        ScrollView {
            VStack {
                if let uiImage {
                    Image(uiImage: uiImage)
                        .resizable()
                        .scaledToFit()
                } else {
                    Image(uiImage: image)
                        .resizable()
                        .scaledToFit()
                }

                HStack(spacing: 15) {
                    Button {
                        applyVibranceFilter()
                    } label: {
                        Text("適用")
                    }

                    Button {
                        uiImage = nil
                        amount = 0
                    } label: {
                        Text("リセット")
                    }
                }
                
                VStack {
                    Text("sharpness: \(amount)")
                    Slider(value: $amount, in: -1...1)
                }
            }
            .padding(.horizontal, 20)
        }
    }

    func applyVibranceFilter() {
        let context = CIContext()
        let inputImage = CIImage(image: image)!

        guard let filter = CIFilter(name: "CIVibrance", parameters: [
            kCIInputImageKey: inputImage,
            kCIInputAmountKey: amount
        ]) else { return }
        guard let outputImage = filter.outputImage else { return }
        guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return }
        self.uiImage = UIImage(cgImage: cgImage)
    }
}

おわり

人を認識しているのか、それとも肌の色を認識してるのか気になりますね
複雑そうなフィルターなのにも関わらず実行は結構早いです

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?