J'ai besoin de compter tous les pixels noirs dans UIImage
. J'ai trouvé un code qui pourrait fonctionner mais il est écrit en Objective-C. J'ai essayé de le convertir en rapide mais j'ai beaucoup d'erreurs et je ne peux pas trouver le moyen de les réparer.Swift 2.2 - Compter les pixels noirs dans UIImage
Quelle est la meilleure façon de faire cela en utilisant 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;
}
Vous faites une quantité incroyable de travail pour chaque pixel. Il doit y avoir un moyen plus efficace; par exemple. lire les données RVB de l'image dans un tableau avec un appel, puis numériser que ... –
@NicolasMiari Je suis d'accord, c'est pourquoi j'ai eu la mise en garde au fond. J'ai dû faire quelque chose de similaire récemment, mais sur de très petites images, donc je pouvais me permettre le coup de performance. Cependant, j'aimerais voir quelque chose plus vite. – CodeBender
Je ne me souviens pas de quelles APIs UIImage doit accéder aux données brutes, mais je parie que CGImageRef est mieux adapté ... –