Мне нужно подсчитать все черные пиксели в UIImage
. Я нашел код, который мог бы работать, но он написан в Objective-C. Я попытался преобразовать его в swift, но у меня много ошибок, и я не могу найти способ их исправить.Swift 2.2 - Count Black Pixels в UIImage
Каков наилучший способ сделать это с помощью Swift?
Objective-C:
/**
* Structure to keep one pixel in RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA format
*/
struct pixel {
unsigned char r, g, b, a;
};
/**
* Process the image and return the number of pure red pixels in it.
*/
- (NSUInteger) processImage: (UIImage*) image
{
NSUInteger numberOfRedPixels = 0;
// Allocate a buffer big enough to hold all the pixels
struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
if (pixels != nil)
{
// Create a new bitmap
CGContextRef context = CGBitmapContextCreate(
(void*) pixels,
image.size.width,
image.size.height,
8,
image.size.width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast
);
if (context != NULL)
{
// Draw the image in the bitmap
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);
// Now that we have the image drawn in our own buffer, we can loop over the pixels to
// process it. This simple case simply counts all pixels that have a pure red component.
// There are probably more efficient and interesting ways to do this. But the important
// part is that the pixels buffer can be read directly.
NSUInteger numberOfPixels = image.size.width * image.size.height;
while (numberOfPixels > 0) {
if (pixels->r == 255) {
numberOfRedPixels++;
}
pixels++;
numberOfPixels--;
}
CGContextRelease(context);
}
free(pixels);
}
return numberOfRedPixels;
}
Вы делаете невероятное количество работы для каждого пикселя. Должен быть более эффективный способ; например прочитайте данные RGB изображения в массив с одним вызовом, а затем сканируйте это ... –
@NicolasMiari Я согласен, поэтому у меня было предостережение внизу. Я должен был сделать что-то подобное недавно, но на очень маленьких изображениях, поэтому я мог позволить себе поразить производительность. Тем не менее, мне бы хотелось увидеть что-то быстрее. – CodeBender
Я не помню, какие API-интерфейсы UIImage имеют доступ к необработанным данным, но я уверен, что CGImageRef лучше подходит ... –