使用vImageHistogramCalculation计算图像的直方图
我想使用vImage的vImageHistogramCalculation_ARGBFFFF
来计算图像的直方图,但我得到一个types为kvImageNullPointerArgument
(错误代码-21772)的vImage_Error。
这是我的代码:
- (void)histogramForImage:(UIImage *)image { //setup inBuffer vImage_Buffer inBuffer; //Get CGImage from UIImage CGImageRef img = image.CGImage; //create vImage_Buffer with data from CGImageRef CGDataProviderRef inProvider = CGImageGetDataProvider(img); CFDataRef inBitmapData = CGDataProviderCopyData(inProvider); //The next three lines set up the inBuffer object inBuffer.width = CGImageGetWidth(img); inBuffer.height = CGImageGetHeight(img); inBuffer.rowBytes = CGImageGetBytesPerRow(img); //This sets the pointer to the data for the inBuffer object inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData); //Prepare the parameters to pass to vImageHistogramCalculation_ARGBFFFF vImagePixelCount *histogram[4] = {0}; unsigned int histogram_entries = 4; Pixel_F minVal = 0; Pixel_F maxVal = 255; vImage_Flags flags = kvImageNoFlags; vImage_Error error = vImageHistogramCalculation_ARGBFFFF(&inBuffer, histogram, histogram_entries, minVal, maxVal, flags); if (error) { NSLog(@"error %ld", error); } //clean up CGDataProviderRelease(inProvider); }
我怀疑这与我的histogram
参数有关,根据文档,它应该是“指向四个直方图数组的指针”。 我是否正确地宣布?
谢谢。
麻烦的是,你没有分配空间来保存计算的直方图。 如果你只是在本地使用直方图,你可以像这样把它们放在堆栈上[请注意,我使用了八个bin,而不是四个,以便使示例更清晰]:
// create an array of four histograms with eight entries each. vImagePixelCount histogram[4][8] = {{0}}; // vImageHistogramCalculation requires an array of pointers to the histograms. vImagePixelCount *histogramPointers[4] = { &histogram[0][0], &histogram[1][0], &histogram[2][0], &histogram[3][0] }; vImage_Error error = vImageHistogramCalculation_ARGBFFFF(&inBuffer, histogramPointers, 8, 0, 255, kvImageNoFlags); // You can now access bin j of the histogram for channel i as histogram[i][j]. // The storage for the histogram will be cleaned up when execution leaves the // current lexical block.
如果你需要直方图在函数的作用域之外,你需要在堆上为它们分配空间:
vImagePixelCount *histogram[4]; unsigned int histogramEntries = 8; histogram[0] = malloc(4*histogramEntries*sizeof histogram[0][0]); if (!histogram[0]) { // handle error however is appropriate } for (int i=1; i<4; ++i) { histogram[i] = &histogram[0][i*histogramEntries]; } vImage_Error error = vImageHistogramCalculation_ARGBFFFF(&inBuffer, histogram, 8, 0, 255, kvImageNoFlags); // You can now access bin j of the histogram for channel i as histogram[i][j]. // Eventually you will need to free(histogram[0]) to release the storage.
希望这可以帮助。