Created
September 19, 2025 14:10
-
-
Save imaizume/37910cf3cc1cedb602e4f74d55704ab3 to your computer and use it in GitHub Desktop.
iOSDC Japan 2025 発表関連のコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // Request.swift | |
| // VisionFrameworkDemo | |
| // | |
| // Created by tomohiro-imaizumi on 2025/09/19. | |
| // | |
| import CoreGraphics | |
| import Vision | |
| /// iOS17までの書き方 | |
| func performLegacyDetectionRequest( | |
| cgImage: CGImage, | |
| orientation: CGImagePropertyOrientation | |
| ) async throws -> [CGRect] { | |
| let request = VNDetectFaceRectanglesRequest() | |
| request.preferBackgroundProcessing = true | |
| // シミュレーターではCPUを使用 | |
| #if targetEnvironment(simulator) | |
| if #available(iOS 17.0, *) { | |
| let allDevices = MLComputeDevice.allComputeDevices | |
| for device in allDevices { | |
| if device.description.contains("MLCPUComputeDevice") { | |
| request.setComputeDevice(.some(device), for: .main) | |
| break | |
| } | |
| } | |
| } else { | |
| request.usesCPUOnly = true | |
| } | |
| #endif | |
| let handler = VNImageRequestHandler( | |
| cgImage: cgImage, | |
| orientation: orientation | |
| ) | |
| return try await withTaskCancellationHandler { | |
| try Task.checkCancellation() | |
| return try await withCheckedThrowingContinuation { continuation in | |
| do { | |
| try handler.perform([request]) | |
| continuation.resume( | |
| returning: (request.results ?? []).map { | |
| VNImageRectForNormalizedRect($0.boundingBox, Int(cgImage.width), Int(cgImage.height)) | |
| } | |
| ) | |
| } catch { | |
| continuation.resume(throwing: error) | |
| } | |
| } | |
| } onCancel: { | |
| request.cancel() | |
| } | |
| } | |
| /// iOS18以降での書き方 | |
| @available(iOS 18.0, *) | |
| func performDetectionRequest( | |
| cgImage: CGImage, | |
| orientation: CGImagePropertyOrientation | |
| ) async throws -> [CGRect] { | |
| let request = DetectFaceRectanglesRequest() | |
| let size: CGSize = .init(width: Int(cgImage.width), height: Int(cgImage.height)) | |
| return try await request | |
| .perform(on: cgImage, orientation: orientation) | |
| .map { | |
| $0.boundingBox.toImageCoordinates(size, origin: .upperLeft) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment