Swift avcapturesessession - Основная проблема с офсезом бокса и лучшие практики ориентации на видеоIOS

Программируем под IOS
Ответить
Anonymous
 Swift avcapturesessession - Основная проблема с офсезом бокса и лучшие практики ориентации на видео

Сообщение Anonymous »

Я работаю над приложением для iOS, которое использует AvcaptureSession, чтобы захватить живой видео -канал с задней камеры. Моя цель состоит в том, чтобы обнаружить животных, использующих vnrecognizeanimalsrequest и отобразить ограничивающие ящики вокруг распознанных объектов.
Однако я сталкиваюсь с несколькими проблемами и имею вопросы о лучших практиках:
overview Code
Здесь соответствующий код на установке. Объекты: < /p>

Код: Выделить всё

import UIKit
import AVFoundation
import Vision

class VideoFeedViewController2: UIViewController {
private let captureSession = AVCaptureSession()
private let videoDataOutput = AVCaptureVideoDataOutput()

private lazy var previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

private var captureDevice: AVCaptureDevice?
private var captureDeviceInput: AVCaptureDeviceInput?
private var boundingBoxLayer: CAShapeLayer?

override func viewDidLoad() {
super.viewDidLoad()

captureSession.sessionPreset = .hd1280x720

addCameraInput()
showCameraFeed()
getCameraFrames()

DispatchQueue.global(qos: .background).async {
self.captureSession.startRunning()
}
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.layer.bounds
updatePreviewLayerOrientation()
}

private func updatePreviewLayerOrientation() {
let currentOrientation = UIDevice.current.orientation

switch currentOrientation {
case .portrait:
previewLayer.connection?.videoOrientation = .portrait
case .landscapeLeft:
previewLayer.connection?.videoOrientation = .landscapeRight
case .landscapeRight:
previewLayer.connection?.videoOrientation = .landscapeLeft
case .portraitUpsideDown:
previewLayer.connection?.videoOrientation = .portraitUpsideDown
default:
break
}
}

private func addCameraInput() {
guard let device = AVCaptureDevice.DiscoverySession(
deviceTypes: [.builtInTrueDepthCamera, .builtInDualCamera, .builtInWideAngleCamera],
mediaType: .video,
position: .back
).devices.first else { fatalError("No camera") }

self.captureDevice = device

let cameraInput = try! AVCaptureDeviceInput(device: device)
captureSession.addInput(cameraInput)
}

private func showCameraFeed() {
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)

previewLayer.frame = view.frame
}

private func getCameraFrames() {
videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "camera-test"))

captureSession.addOutput(videoDataOutput)

guard let captureConnection = videoDataOutput.connection(with: .video) else {
fatalError("No video connection found!")
}
captureConnection.isEnabled = true
captureConnection.isCameraIntrinsicMatrixDeliveryEnabled = true
}

private func detectBoundingBox(pixelBuffer: CVPixelBuffer, _ cmSampleBuffer: CMSampleBuffer) {
let detectionRequest = VNRecognizeAnimalsRequest(completionHandler: detectionCompletionHandler)

let imageResultHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .down, options: [:])
try? imageResultHandler.perform([detectionRequest])

func detectionCompletionHandler(request: VNRequest, error: Error?) {
DispatchQueue.main.async {
self.clearDrawings()

guard
let results = request.results,
let observation = results.first as? VNRecognizedObjectObservation
else {
if let captureDevice = self.captureDevice {
try? captureDevice.lockForConfiguration()
captureDevice.ramp(toVideoZoomFactor: 1.0, withRate: 2.0)
captureDevice.unlockForConfiguration()
}
return
}

if observation.confidence >  0.5 {
self.handleObservation(observation, pixelBuffer, cmSampleBuffer)
}
}
}
}

private func handleObservation(_ observation: VNRecognizedObjectObservation, _ pixelBuffer: CVPixelBuffer, _ cmSampleBuffer: CMSampleBuffer) {
let boundingBox = observation.boundingBox

let size = createBoundingBoxShape(boundingBox)

func createBoundingBoxShape(_ boundingBox: CGRect) -> CGFloat {
let width = previewLayer.bounds.width
let height = previewLayer.bounds.height

let adjustedBoundingBox = CGRect(origin: CGPoint(x: 1 - boundingBox.origin.x, y: boundingBox.origin.y), size: boundingBox.size)
let boundingBoxOnScreen = VNImageRectForNormalizedRect(adjustedBoundingBox, Int(width), Int(height))

let boundingBoxShape = CAShapeLayer()

let boundingBoxPath = CGPath(rect: boundingBoxOnScreen, transform: nil)
boundingBoxShape.path = boundingBoxPath

boundingBoxShape.fillColor = UIColor.clear.cgColor
boundingBoxShape.strokeColor = UIColor.green.cgColor

let boundingBoxWidth = boundingBoxOnScreen.width
let boundingBoxHeight = boundingBoxOnScreen.height
let boundingBoxArea = boundingBoxWidth * boundingBoxHeight

let imageWidth = previewLayer.bounds.width
let imageHeight = previewLayer.bounds.height
let imageArea = imageWidth * imageHeight

let boundingBoxPercentage = (boundingBoxArea / imageArea) * 100

let textLayer = CATextLayer()
textLayer.string = String(format: "%.2f%%", boundingBoxPercentage)
textLayer.fontSize = 24
textLayer.foregroundColor = UIColor.green.cgColor
textLayer.frame = CGRect(x: boundingBoxOnScreen.origin.x, y: boundingBoxOnScreen.origin.y - 20, width: 50, height: 20)

boundingBoxShape.addSublayer(textLayer)

view.layer.addSublayer(boundingBoxShape)
boundingBoxLayer = boundingBoxShape

return boundingBoxPercentage
}
}

private func clearDrawings() {
boundingBoxLayer?.removeFromSuperlayer()
}
}

extension VideoFeedViewController2: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let frame = CMSampleBufferGetImageBuffer(sampleBuffer) else {
debugPrint("No image")
return
}

detectBoundingBox(pixelBuffer: frame, sampleBuffer)
}
}
мои вопросы
  • лучшие практики для avcapturesession Настройка:
    • Есть ли какие -либо лучшие практики или рекомендуемые настройки, чтобы рассмотреть при работе с AvcaptureSession, чтобы обеспечить плавную подачу видео и точную обработку кадра? /> Основной компенсация по сфере окрашивания < /strong>:
    • Ограничительные ящики вокруг обнаруженных объектов правильно расположены на оси Y, но смещены на оси x (сдвинуты вправо). Я вычисляю ограничивающую коробку с использованием метода vnimagerectfornormalizedRect. Есть ли стандартный способ справиться с этим смещением? Тем не менее, приложение также должно адаптироваться к режиму портрета. Каков рекомендуемый подход для обработки видеоориентации с avcaptureSession, чтобы обеспечить обороту ориентации вращение устройства?
>

Подробнее здесь: https://stackoverflow.com/questions/791 ... on-best-pr
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»