gpt4 book ai didi

iphone - 我如何在 iPhone 中使用 Objective-C 计算 UIImage 中的红色像素?

转载 作者:行者123 更新时间:2023-12-03 19:33:57 25 4
gpt4 key购买 nike

我是iphone软件开发的初学者。我正在开发关于皮肤癌的应用程序,其中我想计算或计算 iPhone 相机捕获的 UIImage 中的红色像素。可以从 UIImage 中计算红色像素吗?

最佳答案

由于这是一个几乎每周都会被问到的问题,我决定制作一个小示例项目来展示如何做到这一点。您可以查看代码:

http://github.com/st3fan/iphone-experiments/tree/master/Miscellaneous/PixelAccess/

重要的一点是下面的代码,它接受一个UIImage,然后计算纯红色像素的数量。这是一个示例,您可以使用它并根据您自己的算法修改它:

/**
* 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;
}

关于如何调用它的简单示例:

- (IBAction) processImage
{
NSUInteger numberOfRedPixels = [self processImage: [UIImage imageNamed: @"DutchFlag.png"]];
label_.text = [NSString stringWithFormat: @"There are %d red pixels in the image", numberOfRedPixels];
}

Github 上的示例项目包含一个完整的工作示例。

关于iphone - 我如何在 iPhone 中使用 Objective-C 计算 UIImage 中的红色像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2342327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com