6
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 5 years have passed since last update.

UIImageの画像が黒っぽいか白っぽいかどうか判別するExtension

Last updated at Posted at 2018-01-05

やりたいこと

画像が黒っぽい画像か白っぽい画像かを判定する

実装

1.CGImageのextensionを作成

以下のswiftファイルをプロジェクトに追加する。閾値や明るさの定義は好みで修正していただければと思います。

CGImage+.swift
//
//  CGImage+.swift
//
//  Created by Hiromasa Suzuki on 1/5/17.
//  Copyright (c) 2017 Hiromasa Suzuki. All rights reserved.
//
import UIKit

extension CGImage {
    var isDark: Bool {
        get {
            guard let imageData = self.dataProvider?.data else { return false }

            // ピクセルレベルで画像の色を取得
            guard let ptr = CFDataGetBytePtr(imageData) else { return false }

            // CFDataの長さを返す
            let length = CFDataGetLength(imageData)

            // 閾値(各人で調整)
            let threshold = Int(Double(self.width * self.height) * 0.45)
            var darkPixels = 0

            // 閾値のループ
            for i in stride(from: 0, to: length, by: 4) {
                let r = ptr[i]
                let g = ptr[i + 1]
                let b = ptr[i + 2]

                // 明るさ(各人で調整)
                let luminance = (0.299 * Double(r) + 0.587 * Double(g) + 0.114 * Double(b))
                if luminance < 150 {
                    darkPixels += 1

                    // 閾値を超えたら黒っぽい画像とする
                    if darkPixels > threshold {
                        return true
                    }
                }
            }
            // 最後まで閾値を超えなかったら、白っぽい画像とする
            return false
        }
    }
}

こちらにGist格納してます。
https://gist.github.com/suzuhiroruri/aa83814042bb04120d91c03991f47c89

2.CGImageのextensionを使用する

// 適当にUIImageのインストタンスを生成(適宜変える)
let image:UIImage = UIImage(named:"sample.jpg")!

// extensionを使い、Boolで返却値を取得
guard let isDark = image.cgImage?.isDark else {
  return
}

// 黒っぽいか白っぽいか出力
if isDark {
  print("黒っぽい")
}else{
  print("白っぽい")
}
6
1
1

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
6
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?