微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 使用vImageHistogramCalculation计算图像的直方图

我正在尝试使用v ImagevImageHistogramCalculation_ARGBFFFF来计算图像的直方图,但是我得到了类型为kvImageNullPointerargument的vImage_Error(错误代码为-21772).

这是我的代码

- (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);
}

我怀疑它与我的直方图参数有关,根据文档,它应该是“指向四个直方图数组的指针”.我是否正确宣布了?

谢谢.

解决方法

麻烦的是你没有分配空间来保存计算的直方图.如果你只在本地使用直方图,你可以将它们放在堆栈上[注意我使用的是8个而不是4个,以使示例更清晰]:

// 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,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,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.

希望这可以帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐