カメラ入力をリアルタイムで表示し、中央のピクセルのカラー値を取得するプログラムがあります。私はcaptureOutput:メソッドを使用してAVCaptureSession出力(CVPixelBufferとして読み取られる)からCMSampleBufferを取得し、次のコードを使用してピクセルのrgb値を取得します。
// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0);
// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
unsigned char* pixel = (unsigned char *)CVPixelBufferGetBaseAddress(imageBuffer);
NSLog(@"Middle pixel: %hhu", pixel[((width*height)*4)/2]);
int red = pixel[(((width*height)*4)/2)+2];
int green = pixel[(((width*height)*4)/2)+1];
int blue = pixel[((width*height)*4)/2];
int alpha = 1;
UIColor *color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha)];
その式((width * height)* 4)/ 2で中央のピクセルが得られますが、画像の上部の中央のピクセルが得られます。画面中央のピクセルにアクセスするには、どの式を使用する必要があるのでしょうか。これらのピクセルバッファの内部構造を本当に知らないので、私はちょっと立ち往生しています。
将来的には、真ん中の4つのピクセルを取得して平均化し、より正確な色の読み取りを行いたいと思いますが、今のところ、これらがどのように機能するかを理解したいと思います。