Hacker News new | ask | show | jobs
by oefrha 728 days ago
Huh, I've been copying background-removed subjects out of Preview and didn't realize there's a VisionKit API. Looks like it's quite easy to use too, I put together a quick and dirty script in a couple minutes and it worked wonderfully:

  import AppKit
  import VisionKit
  
  @main
  struct Script {
    static func main() async {
      let image = NSImage(contentsOfFile: "input.heic")!
      let view = ImageAnalysisOverlayView()
      let analyzer = ImageAnalyzer()
      let configuration = ImageAnalyzer.Configuration(.visualLookUp)
      let analysis = try! await analyzer.analyze(image, orientation: .up, configuration: configuration)
      view.analysis = analysis
      let subjects = await view.subjects
      for (index, subject) in subjects.enumerated() {
        let subjectImage = try! await subject.image
        let pngData = NSBitmapImageRep(data: subjectImage.tiffRepresentation!)!.representation(
          using: .png, properties: [:])
        try! pngData?.write(to: URL(fileURLWithPath: "subject-\(index).png"))
        print("subject-\(index).png")
      }
    }
  }