iOSでのビジュアライズ方法です。
UIImageに直接描画します。
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関連の情報を発信しています。