注:元の質問でもスケーリングが要求されていることに気づきませんでした。とにかく、単に CMSampleBuffer をトリミングする必要がある人のために、ここに解決策があります。
バッファは単なるピクセルの配列であるため、実際には vImage を使用せずにバッファを直接処理できます。コードは Swift で書かれていますが、Objective-C に相当するものを見つけるのは簡単だと思います。
まず、CMSampleBuffer が BGRA 形式であることを確認します。そうでない場合、使用するプリセットはおそらく YUV であり、後で使用される行ごとのバイト数が台無しになります。
dataOutput = AVCaptureVideoDataOutput()
dataOutput.videoSettings = [
String(kCVPixelBufferPixelFormatTypeKey):
NSNumber(value: kCVPixelFormatType_32BGRA)
]
次に、サンプル バッファーを取得すると、次のようになります。
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
CVPixelBufferLockBaseAddress(imageBuffer, .readOnly)
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let cropWidth = 640
let cropHeight = 640
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(data: baseAddress, width: cropWidth, height: cropHeight, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
// now the cropped image is inside the context.
// you can convert it back to CVPixelBuffer
// using CVPixelBufferCreateWithBytes if you want.
CVPixelBufferUnlockBaseAddress(imageBuffer, .readOnly)
// create image
let cgImage: CGImage = context!.makeImage()!
let image = UIImage(cgImage: cgImage)
特定の位置からトリミングする場合は、次のコードを追加します。
// calculate start position
let bytesPerPixel = 4
let startPoint = [ "x": 10, "y": 10 ]
let startAddress = baseAddress + startPoint["y"]! * bytesPerRow + startPoint["x"]! * bytesPerPixel
を に変更baseAddress
しCGContext()
ますstartAddress
。元の画像の幅と高さを超えないようにしてください。