LoginSignup
3
1

More than 1 year has passed since last update.

物体検出ボックスを可視化する iOSでバウンディングボックスを画像に描画

Posted at

iOSでのビジュアライズ方法です。

UIImageに直接描画します。

IMG_2262.JPG

box、label、confidence、boxのcolorを持つstructで結果をラップしているとします。

struct Detection {
    let box:CGRect
    let confidence:Float
    let label:String?
    let color:UIColor
}

// 検出に使った画像と検出結果のDetctionのコレクションを入力として、ボックスが描画された画像を返します。

func drawDetectionsOnImage(_ detections: [Detection], _ image: UIImage) -> UIImage? {
    let imageSize = image.size
    let scale: CGFloat = 0.0
    UIGraphicsBeginImageContextWithOptions(imageSize, false, scale)

    image.draw(at: CGPoint.zero)
    let ctx = UIGraphicsGetCurrentContext()
    var rects:[CGRect] = []
    for detection in detections {
        rects.append(detection.box)
        if let labelText = detection.label {
        let text = "\(labelText) : \(round(detection.confidence*100))"
            let textRect  = CGRect(x: detection.box.minX + imageSize.width * 0.01, y: detection.box.minY + imageSize.width * 0.01, width: detection.box.width, height: detection.box.height)
                    
        let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
                    
        let textFontAttributes = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: textRect.width * 0.1, weight: .bold),
            NSAttributedString.Key.foregroundColor: detection.color,
            NSAttributedString.Key.paragraphStyle: textStyle
        ]
                    
        text.draw(in: textRect, withAttributes: textFontAttributes)
        ctx?.addRect(detection.box)
        ctx?.setStrokeColor(detection.color.cgColor)
        ctx?.setLineWidth(9.0)
        ctx?.strokePath()
        }
    }

    guard let drawnImage = UIGraphicsGetImageFromCurrentImageContext() else {
        fatalError()
    }

    UIGraphicsEndImageContext()
    return drawnImage
}

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium
GitHub

3
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
3
1