-
Notifications
You must be signed in to change notification settings - Fork 1
/
tempp.swift
759 lines (682 loc) · 27.6 KB
/
tempp.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import SwiftUI
import AVKit
import AVFoundation
import Vision
import CoreML
struct MainVideoView: View {
@ObservedObject var mediaModel = MediaModel()
@State private var player = AVPlayer()
@State private var playerView = AVPlayerView()
@State private var detectedObjects: [VNRecognizedObjectObservation] = []
@State private var detectedFaces: [VNFaceObservation] = []
@State private var detectedHumans: [VNHumanObservation] = []
@State private var detectedHands: [VNHumanHandPoseObservation] = []
@State private var detectedBodyPoses: [VNHumanBodyPoseObservation] = []
@State private var imageSize: CGSize = .zero
@State private var videoSize: CGSize = .zero
@State private var objectDetectionEnabled = true
@State private var faceDetectionEnabled = true
@State private var humanDetectionEnabled = false
@State private var handDetectionEnabled = false
@State private var bodyPoseDetectionEnabled = false
@State private var maxRequestsMode = false
@State private var framePerFrameMode = false
@State private var loopMode = false
@State private var playBackward = false
@State private var autoPauseOnNewDetection = false
@State private var showBoundingBoxes = true
@State private var savePath: URL?
@State private var totalObjectsDetected = 0
@State private var totalFacesDetected = 0
@State private var totalHumansDetected = 0
@State private var totalHandsDetected = 0
@State private var totalBodyPosesDetected = 0
@State private var droppedFrames = 0
@State private var corruptedFrames = 0
@State private var detectionFPS: Double = 0.0
@State private var selectedSize: CGSize = CGSize(width: 1280, height: 720)
@State private var videoOutput: AVPlayerItemVideoOutput?
@State private var saveJsonLog = false
@State private var saveLabels = false
@State private var saveFrames = false
var body: some View {
NavigationView {
videoGallery
videoPreview
}
.tabItem {
Label("MainVideoView", systemImage: "video")
}
.onAppear {
if let savedPath = UserDefaults.standard.url(forKey: "savePath") {
if checkAccessToPath(url: savedPath) {
savePath = savedPath
} else {
selectSavePath()
}
}
}
}
whitePointAdjustFilter?.setValue(CIColor(red: CGFloat(Float(whitePoint)), green: CGFloat(Float(whitePoint)), blue: CGFloat(Float(whitePoint))), forKey: kCIInputColorKey)
private var videoGallery: some View {
VStack {
Button("Add Video") {
mediaModel.addVideos()
}
.padding()
List {
ForEach(Array(mediaModel.videos.enumerated()), id: \.element) { index, url in
Button(action: {
mediaModel.selectedVideoURL = url
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
setupVideoOutput(for: playerItem)
player.replaceCurrentItem(with: playerItem)
playerView.player = player
startFrameExtraction()
}) {
Text("\(index + 1)/\(mediaModel.videos.count) - \(url.lastPathComponent)")
}
.contextMenu {
Button(action: {
if player.timeControlStatus == .playing {
player.pause()
} else {
player.play()
}
}) {
Text(player.timeControlStatus == .playing ? "Pause" : "Play")
}
Button(action: {
if let currentPixelBuffer = mediaModel.currentPixelBuffer {
let ciImage = CIImage(cvPixelBuffer: currentPixelBuffer)
let context = CIContext()
if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {
let nsImage = NSImage(cgImage: cgImage, size: NSSize(width: ciImage.extent.width, height: ciImage.extent.height))
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects([nsImage])
}
}
}) {
Text("Copy Frame")
}
Button(action: {
if let currentPixelBuffer = mediaModel.currentPixelBuffer {
saveCurrentFrame(fileName: getSaveURL(fileName: "current_frame.jpg").path)
}
}) {
Text("Save Frame")
}
Button(action: {
openInNewWindow(url: url)
}) {
Text("Open in New Window")
}
Button(action: {
NSWorkspace.shared.activateFileViewerSelecting([url])
}) {
Text("Show in Finder")
}
Button(action: {
if let savePath = savePath {
let resultsFolder = savePath.appendingPathComponent(url.lastPathComponent)
NSWorkspace.shared.activateFileViewerSelecting([resultsFolder])
}
}) {
Text("Show Results Folder in Finder")
}
Button(action: {
mediaModel.videos.removeAll { $0 == url }
}) {
Text("Delete from List")
}
}
}
.onMove(perform: move)
}
.onDrop(of: ["public.file-url"], isTargeted: nil, perform: addVideoFromDrop)
.padding()
Button("Clear All") {
mediaModel.clearVideos()
player.replaceCurrentItem(with: nil)
}
.padding()
HStack {
Text("Select Placeholder Size:")
Menu("Select Size") {
Button("640x640") { selectedSize = CGSize(width: 640, height: 640) }
Button("1024x576") { selectedSize = CGSize(width: 1024, height: 576) }
Button("576x1024") { selectedSize = CGSize(width: 576, height: 1024) }
Button("1280x720") { selectedSize = CGSize(width: 1280, height: 720) }
}
}
.padding()
}
.frame(minWidth: 200)
}
private var videoPreview: some View {
ScrollView {
HStack {
Text("File: \(mediaModel.selectedVideoURL?.lastPathComponent ?? "N/A")")
Text("Model: IO_cashtrack.mlmodel")
}
HStack {
Text("Time: \(player.currentTime().asTimeString() ?? "00:00:00")")
Text("Frame: \(getCurrentFrameNumber())")
Text("Total Frames: \(player.currentItem?.asset.totalNumberOfFrames ?? 0)")
Text("Dropped Frames: \(droppedFrames)")
Text("Corrupted Frames: \(corruptedFrames)")
}
HStack {
Text("Current Resolution: \(videoSize.width, specifier: "%.0f")x\(videoSize.height, specifier: "%.0f")")
Text("Detection FPS: \(detectionFPS, specifier: "%.2f")")
Text("Video FPS: \(getVideoFrameRate(), specifier: "%.2f")")
Text("Total Objects Detected: \(totalObjectsDetected)")
Text("Total Faces Detected: \(totalFacesDetected)")
Text("Total Humans Detected: \(totalHumansDetected)")
Text("Total Hands Detected: \(totalHandsDetected)")
Text("Total Body Poses Detected: \(totalBodyPosesDetected)")
}
if mediaModel.selectedVideoURL != nil {
VStack {
VideoPlayerViewMain(player: player, detections: $detectedObjects)
.frame(width: selectedSize.width, height: selectedSize.height)
.background(Color.black)
.clipped()
.modifier(BoundingBoxModifier(observations: detectedObjects, color: .red, scale: 1.0))
.modifier(BoundingBoxModifier(observations: detectedFaces.map { VNDetectedObjectObservation(boundingBox: $0.boundingBox) }, color: .blue, scale: 2.0))
.modifier(BoundingBoxModifier(observations: detectedHumans.map { VNDetectedObjectObservation(boundingBox: $0.boundingBox) }, color: .green, scale: 1.0))
.modifier(HandJointModifier(hands: detectedHands, color: .yellow))
.modifier(BodyPoseJointModifier(bodyPoses: detectedBodyPoses, color: .purple))
}
} else {
VStack {
Rectangle()
.stroke(Color.gray, lineWidth: 2)
.frame(width: selectedSize.width, height: selectedSize.height)
.background(Color.black)
.overlay(
Text("Load a video to start")
.foregroundColor(.white)
)
.padding()
}
.padding()
}
VStack {
HStack {
Toggle("Enable Object Detection", isOn: $objectDetectionEnabled)
Toggle("Enable Face Detection", isOn: $faceDetectionEnabled)
Toggle("Enable Human Detection", isOn: $humanDetectionEnabled)
Toggle("Enable Hand Detection", isOn: $handDetectionEnabled)
Toggle("Enable Body Pose Detection", isOn: $bodyPoseDetectionEnabled)
Toggle("Save Labels", isOn: $saveLabels)
Toggle("Save Frames", isOn: $saveFrames)
Toggle("Save JSON Log", isOn: $saveJsonLog)
Toggle("Auto Pause on New Detection", isOn: $autoPauseOnNewDetection)
}
HStack {
Button("Select Save Path") {
selectSavePath()
}
if let savePath = savePath {
Text("Save Path: \(savePath.path)")
}
}
HStack {
Toggle("Max Requests Mode", isOn: $maxRequestsMode)
Toggle("Frame Per Frame Mode", isOn: $framePerFrameMode)
Toggle("Loop", isOn: $loopMode)
Toggle("Play Backward", isOn: $playBackward)
Toggle("Show Bounding Boxes", isOn: $showBoundingBoxes)
}
HStack {
Button("Play") {
player.play()
if framePerFrameMode {
startFramePerFrameMode()
}
if loopMode {
player.actionAtItemEnd = .none
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main) { _ in
player.seek(to: .zero)
player.play()
}
}
if playBackward {
startPlayBackwardMode()
}
}
Button("Pause") {
player.pause()
stopFramePerFrameMode()
stopPlayBackwardMode()
}
Button("Background Run") {
runPredictionsWithoutPlaying()
}
}
}
}
}
private func getVideoFrameRate() -> Float {
return player.currentItem?.asset.tracks.first?.nominalFrameRate ?? 0
}
private func getCurrentFrameNumber() -> Int {
guard let currentItem = player.currentItem else { return 0 }
let currentTime = currentItem.currentTime()
let frameRate = getVideoFrameRate()
return Int(CMTimeGetSeconds(currentTime) * Double(frameRate))
}
private func runModel(on pixelBuffer: CVPixelBuffer) {
let model = try! VNCoreMLModel(for: IO_cashtrack().model)
let request = VNCoreMLRequest(model: model) { request, error in
let start = CFAbsoluteTimeGetCurrent()
if let results = request.results as? [VNRecognizedObjectObservation] {
DispatchQueue.main.async {
self.detectedObjects = results
self.totalObjectsDetected += results.count
if saveLabels || saveFrames {
Task {
await processAndSaveDetections(results, at: player.currentItem?.currentTime())
}
}
if autoPauseOnNewDetection && !results.isEmpty {
player.pause()
}
let end = CFAbsoluteTimeGetCurrent()
self.detectionFPS = 1.0 / (end - start)
}
}
}
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([request])
}
private func runFaceDetection(on pixelBuffer: CVPixelBuffer) {
let faceRequest = VNDetectFaceRectanglesRequest { request, error in
if let results = request.results as? [VNFaceObservation] {
DispatchQueue.main.async {
self.detectedFaces = results
self.totalFacesDetected += results.count
if saveLabels || saveFrames {
Task {
await processAndSaveFaces(results, at: player.currentItem?.currentTime())
}
}
}
}
}
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([faceRequest])
}
private func runHumanDetection(on pixelBuffer: CVPixelBuffer) {
let humanRequest = VNDetectHumanRectanglesRequest { request, error in
if let results = request.results as? [VNHumanObservation] {
DispatchQueue.main.async {
self.detectedHumans = results
self.totalHumansDetected += results.count
if saveLabels || saveFrames {
Task {
await processAndSaveHumans(results, at: player.currentItem?.currentTime())
}
}
}
}
}
humanRequest.upperBodyOnly = true
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([humanRequest])
}
private func runHandDetection(on pixelBuffer: CVPixelBuffer) {
let handRequest = VNDetectHumanHandPoseRequest { request, error in
if let results = request.results as? [VNHumanHandPoseObservation] {
DispatchQueue.main.async {
self.detectedHands = results
self.totalHandsDetected += results.count
if saveLabels || saveFrames {
Task {
await processAndSaveHands(results, at: player.currentItem?.currentTime())
}
}
}
}
}
handRequest.maximumHandCount = handDetectionEnabled ? 10 : 0
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([handRequest])
}
private func runBodyPoseDetection(on pixelBuffer: CVPixelBuffer) {
let bodyPoseRequest = VNDetectHumanBodyPoseRequest { request, error in
if let results = request.results as? [VNHumanBodyPoseObservation] {
DispatchQueue.main.async {
self.detectedBodyPoses = results
self.totalBodyPosesDetected += results.count
if saveLabels || saveFrames {
Task {
await processAndSaveBodyPoses(results, at: player.currentItem?.currentTime())
}
}
}
}
}
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
try? handler.perform([bodyPoseRequest])
}
private func startFrameExtraction() {
let interval = CMTime(value: 1, timescale: 40)
player.addPeriodicTimeObserver(forInterval: interval, queue: .main) { time in
if let videoOutput = self.videoOutput,
videoOutput.hasNewPixelBuffer(forItemTime: time) {
var presentationTime = CMTime()
if let pixelBuffer = videoOutput.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: &presentationTime) {
mediaModel.currentFrame = pixelBuffer
mediaModel.currentPixelBuffer = pixelBuffer
if objectDetectionEnabled {
runModel(on: pixelBuffer)
}
if faceDetectionEnabled {
runFaceDetection(on: pixelBuffer)
}
if humanDetectionEnabled {
runHumanDetection(on: pixelBuffer)
}
if handDetectionEnabled {
runHandDetection(on: pixelBuffer)
}
if bodyPoseDetectionEnabled {
runBodyPoseDetection(on: pixelBuffer)
}
}
}
}
}
private func saveCurrentFrame(fileName: String) {
guard let pixelBuffer = mediaModel.currentPixelBuffer else { return }
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
let context = CIContext()
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return }
let nsImage = NSImage(cgImage: cgImage, size: .zero)
guard let tiffData = nsImage.tiffRepresentation,
let bitmap = NSBitmapImageRep(data: tiffData),
let jpegData = bitmap.representation(using: .jpeg, properties: [:]) else { return }
do {
try jpegData.write(to: URL(fileURLWithPath: fileName))
} catch {
print("Error saving frame: \(error)")
}
}
private func setupVideoOutput(for playerItem: AVPlayerItem) {
let pixelBufferAttributes: [String: Any] = [
kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA
]
let videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: pixelBufferAttributes)
playerItem.add(videoOutput)
self.videoOutput = videoOutput
}
private func getSaveURL(fileName: String) -> URL {
let savePanel = NSSavePanel()
savePanel.nameFieldStringValue = fileName
savePanel.canCreateDirectories = true
savePanel.allowedContentTypes = [.movie]
if savePanel.runModal() == .OK {
return savePanel.url ?? URL(fileURLWithPath: "/dev/null")
}
return URL(fileURLWithPath: "/dev/null")
}
private func selectSavePath() {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.allowsMultipleSelection = false
if panel.runModal() == .OK {
savePath = panel.url
UserDefaults.standard.set(savePath, forKey: "savePath")
}
}
private func createFolderIfNotExists(at url: URL) {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: url.path) {
do {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Error creating folder: \(error)")
}
}
}
private func logDetections(detections: [Detection], frameNumber: Int, folderURL: URL) {
let logFileName = folderURL.appendingPathComponent("log_\(mediaModel.selectedVideoURL?.lastPathComponent ?? "video").json")
var log = DetectionLog(videoURL: mediaModel.selectedVideoURL?.absoluteString ?? "", creationDate: Date().description, frames: [])
if let data = try? Data(contentsOf: logFileName), let existingLog = try? JSONDecoder().decode(DetectionLog.self, from: data) {
log = existingLog
}
let frameLog = FrameLog(frameNumber: frameNumber, detections: detections.isEmpty ? nil : detections)
log.frames.append(frameLog)
do {
let data = try JSONEncoder().encode(log)
try data.write(to: logFileName)
} catch {
print("Error saving log: \(error)")
}
}
private func logFaceDetections(detections: [FaceDetection], frameNumber: Int, folderURL: URL) {
let logFileName = folderURL.appendingPathComponent("log_faces_\(mediaModel.selectedVideoURL?.lastPathComponent ?? "video").json")
var log = FaceDetectionLog(videoURL: mediaModel.selectedVideoURL?.absoluteString ?? "", creationDate: Date().description, frames: [])
if let data = try? Data(contentsOf: logFileName), let existingLog = try? JSONDecoder().decode(FaceDetectionLog.self, from: data) {
log = existingLog
}
let frameLog = FaceFrameLog(frameNumber: frameNumber, detections: detections.isEmpty ? nil : detections)
log.frames.append(frameLog)
do {
let data = try JSONEncoder().encode(log)
try data.write(to: logFileName)
} catch {
print("Error saving log: \(error)")
}
}
private func logHumanDetections(detections: [HumanDetection], frameNumber: Int, folderURL: URL) {
let logFileName = folderURL.appendingPathComponent("log_humans_\(mediaModel.selectedVideoURL?.lastPathComponent ?? "video").json")
var log = HumanDetectionLog(videoURL: mediaModel.selectedVideoURL?.absoluteString ?? "", creationDate: Date().description, frames: [])
if let data = try? Data(contentsOf: logFileName), let existingLog = try? JSONDecoder().decode(HumanDetectionLog.self, from: data) {
log = existingLog
}
let frameLog = HumanFrameLog(frameNumber: frameNumber, detections: detections.isEmpty ? nil : detections)
log.frames.append(frameLog)
do {
let data = try JSONEncoder().encode(log)
try data.write(to: logFileName)
} catch {
print("Error saving log: \(error)")
}
}
private func logHandDetections(detections: [HandDetection], frameNumber: Int, folderURL: URL) {
let logFileName = folderURL.appendingPathComponent("log_hands_\(mediaModel.selectedVideoURL?.lastPathComponent ?? "video").json")
var log = HandDetectionLog(videoURL: mediaModel.selectedVideoURL?.absoluteString ?? "", creationDate: Date().description, frames: [])
if let data = try? Data(contentsOf: logFileName), let existingLog = try? JSONDecoder().decode(HandDetectionLog.self, from: data) {
log = existingLog
}
let frameLog = HandFrameLog(frameNumber: frameNumber, detections: detections.isEmpty ? nil : detections)
log.frames.append(frameLog)
do {
let data = try JSONEncoder().encode(log)
try data.write(to: logFileName)
} catch {
print("Error saving log: \(error)")
}
}
private func logBodyPoseDetections(detections: [BodyPoseDetection], frameNumber: Int, folderURL: URL) {
let logFileName = folderURL.appendingPathComponent("log_body_poses_\(mediaModel.selectedVideoURL?.lastPathComponent ?? "video").json")
var log = BodyPoseDetectionLog(videoURL: mediaModel.selectedVideoURL?.absoluteString ?? "", creationDate: Date().description, frames: [])
if let data = try? Data(contentsOf: logFileName), let existingLog = try? JSONDecoder().decode(BodyPoseDetectionLog.self, from: data) {
log = existingLog
}
let frameLog = BodyPoseFrameLog(frameNumber: frameNumber, detections: detections.isEmpty ? nil : detections)
log.frames.append(frameLog)
do {
let data = try JSONEncoder().encode(log)
try data.write(to: logFileName)
} catch {
print("Error saving log: \(error)")
}
}
private func runPredictionsWithoutPlaying() {
guard let playerItem = player.currentItem else { return }
let duration = playerItem.duration
let frameRate = getVideoFrameRate()
let totalFrames = Int(CMTimeGetSeconds(duration) * Double(frameRate))
var currentFrame = 0
var currentTime = CMTime.zero
while currentFrame < totalFrames {
let interval = CMTime(value: 1, timescale: Int32(frameRate))
currentTime = CMTimeMultiplyByFloat64(interval, multiplier: Float64(currentFrame))
if let videoOutput = videoOutput, videoOutput.hasNewPixelBuffer(forItemTime: currentTime) {
var presentationTime = CMTime()
if let pixelBuffer = videoOutput.copyPixelBuffer(forItemTime: currentTime, itemTimeForDisplay: &presentationTime) {
runModel(on: pixelBuffer)
if faceDetectionEnabled {
runFaceDetection(on: pixelBuffer)
}
if humanDetectionEnabled {
runHumanDetection(on: pixelBuffer)
}
if handDetectionEnabled {
runHandDetection(on: pixelBuffer)
}
if bodyPoseDetectionEnabled {
runBodyPoseDetection(on: pixelBuffer)
}
}
}
currentFrame += 1
}
}
private func checkAccessToPath(url: URL) -> Bool {
var bookmarkDataIsStale: Bool = false
do {
_ = try URL(resolvingBookmarkData: url.bookmarkData(), options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &bookmarkDataIsStale)
return !bookmarkDataIsStale
} catch {
return false
}
}
private func move(from source: IndexSet, to destination: Int) {
mediaModel.videos.move(fromOffsets: source, toOffset: destination)
}
private func addVideoFromDrop(providers: [NSItemProvider]) -> Bool {
for provider in providers {
if provider.hasItemConformingToTypeIdentifier("public.file-url") {
provider.loadItem(forTypeIdentifier: "public.file-url", options: nil) { (item, error) in
guard let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) else { return }
DispatchQueue.main.async {
self.mediaModel.videos.append(url)
}
}
return true
}
}
return false
}
private func openInNewWindow(url: URL) {
let newWindow = NSWindow(
contentRect: NSMakeRect(0, 0, 800, 600),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered, defer: false)
newWindow.title = "Video Player"
let newWindowController = NSWindowController(window: newWindow)
newWindowController.showWindow(self)
let mainVideoView = MainVideoView()
let contentView = NSHostingView(rootView: mainVideoView)
newWindow.contentView = contentView
mainVideoView.mediaModel.videos = [url]
mainVideoView.mediaModel.selectedVideoURL = url
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
mainVideoView.setupVideoOutput(for: playerItem)
mainVideoView.player.replaceCurrentItem(with: playerItem)
mainVideoView.playerView.player = mainVideoView.player
mainVideoView.startFrameExtraction()
}
}
struct BoundingBoxModifier: ViewModifier {
let observations: [VNDetectedObjectObservation]
let color: NSColor
let scale: CGFloat
func body(content: Content) -> some View {
content.overlay(
ForEach(observations, id: \.self) { observation in
drawBoundingBox(for: observation, scale: scale, color: color)
}
)
}
private func drawBoundingBox(for observation: VNDetectedObjectObservation, scale: CGFloat, color: NSColor) -> some View {
let boundingBox = observation.boundingBox
let normalizedRect = CGRect(
x: boundingBox.origin.x - boundingBox.size.width * (scale - 1) / 2,
y: boundingBox.origin.y - boundingBox.size.height * (scale - 1) / 2,
width: boundingBox.width * scale,
height: boundingBox.height * scale
)
return Rectangle()
.stroke(Color(color), lineWidth: 2)
.frame(width: normalizedRect.width, height: normalizedRect.height)
.position(x: normalizedRect.midX, y: normalizedRect.midY)
}
}
struct HandJointModifier: ViewModifier {
let hands: [VNHumanHandPoseObservation]
let color: NSColor
func body(content: Content) -> some View {
content.overlay(
ForEach(hands, id: \.self) { hand in
ForEach(hand.availableJointNames, id: \.self) { jointName in
if let point = try? hand.recognizedPoint(jointName).location {
drawHandJoint(at: point, color: color)
}
}
}
)
}
private func drawHandJoint(at point: CGPoint, color: NSColor) -> some View {
Circle()
.fill(Color(color))
.frame(width: 5, height: 5)
.position(x: point.x, y: 1 - point.y)
}
}
struct BodyPoseJointModifier: ViewModifier {
let bodyPoses: [VNHumanBodyPoseObservation]
let color: NSColor
func body(content: Content) -> some View {
content.overlay(
ForEach(bodyPoses, id: \.self) { bodyPose in
ForEach(bodyPose.availableJointNames, id: \.self) { jointName in
if let point = try? bodyPose.recognizedPoint(jointName).location {
drawBodyPoseJoint(at: point, color: color)
}
}
}
)
}
private func drawBodyPoseJoint(at point: CGPoint, color: NSColor) -> some View {
Circle()
.fill(Color(color))
.frame(width: 5, height: 5)
.position(x: point.x, y: 1 - point.y)
}
}
import sys
import coremltools as ct
import coremltools.proto.FeatureTypes_pb2 as ft
def update_multiarray_to_float32(feature):
if feature.type.HasField("multiArrayType"):
feature.type.multiArrayType.dataType = ft.ArrayFeatureType.FLOAT32
if len(sys.argv) != 3:
print("USAGE: %s <input_mlmodel> <output_mlmodel>" % sys.argv[0])
sys.exit(1)
input_model_path = sys.argv[1]
output_model_path = sys.argv[2]
spec = ct.utils.load_spec(input_model_path)
for feature in spec.description.input:
update_multiarray_to_float32(feature)
for feature in spec.description.output:
update_multiarray_to_float32(feature)
ct.utils.save_spec(spec, output_model_path)