UIImage
のすべての黒いピクセルをカウントする必要があります。私はObjective-Cで書かれていますが、動作するコードを見つけました。私は迅速にそれを変換しようとしましたが、私は多くのエラーを取得し、私はそれらを修正する方法を見つけることができません。Swift 2.2 - UIImageでの黒ピクセルのカウント
スウィフトを使用してこれを行う最善の方法は何ですか?
の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;
}
あなたは画素ごとに仕事の信じられないほどの量を行っています。より効率的な方法が必要です。例えば1回の呼び出しで画像のRGBデータを配列に読み込み、それをスキャンします。 –
@NicolasMiari私は同意します。そのため、私は下に警告がありました。最近似たようなことをしなければならなかったが、非常に小さい画像では、パフォーマンスが低下する可能性があった。しかし、私はより速く何かを見たいです。 – CodeBender
UIImageが未加工データにアクセスする必要があるAPIはどれも覚えていませんが、CGImageRefがより適しているとベットしています... –