gpt4 book ai didi

ios - UIImage 和寻找中心像素的平均 UIColor

转载 作者:行者123 更新时间:2023-11-28 22:31:22 24 4
gpt4 key购买 nike

我正在尝试获取 UIImage 中心 16 个像素的平均 UIColor,但是生成的颜色永远不会接近正确。我在这里做错了什么?点参数是正确的,我已经验证过了。我还有另一种方法,它使用同样的点返回中心像素的 UIColor,效果很好。

+ (UIColor*)getAverageColorForImage:(UIImage *)image atLocation:(CGPoint)point
{
int radialSize = 2;

int xStartPoint = point.x - radialSize;
int yStartPoint = point.y - radialSize;
int xEndPoint = point.x + radialSize;
int yEndPoint = point.y + radialSize;

CGImageRef rawImageRef = [image CGImage];

CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef));
const UInt8 *rawPixelData = CFDataGetBytePtr(data);

NSUInteger bytesPerRow = CGImageGetBytesPerRow(rawImageRef);
NSUInteger stride = CGImageGetBitsPerPixel(rawImageRef) / 8;

unsigned int red = 0;
unsigned int green = 0;
unsigned int blue = 0;

for(int row = yStartPoint; row < yEndPoint; row++)
{
const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;

for(int column = xStartPoint; column < xEndPoint; column++)
{
red += rowPtr[0];
green += rowPtr[1];
blue += rowPtr[2];

rowPtr += stride;
}
}

CFRelease(data);

CGFloat f = 1.0f / (255.0f * (yEndPoint - yStartPoint) * (xEndPoint - xStartPoint));
return [UIColor colorWithRed:f * red green:f * green blue:f * blue alpha:1.0f];
}

最佳答案

您只是迭代从 startPointendPoint 的像素。也许使用

for(int row = yStartPoint; row <= yEndPoint; row++)
// ...
for(int column = xStartPoint; column <= xEndPoint; column++)

会修好吗?

此外,您还必须调整您的 rowPtr 以从您的 xStartPoint 开始:

const UInt8 *rowPtr = rawPixelData + bytesPerRow * row + stride * xStartPoint;

否则你将从每行 x = 0 开始。

你的平均值应该这样计算:

int numberOfPixels = (yEndPoint - yStartPoint) * (xEndPoint - xStartPoint);

red /= numberOfPixels;
green /= numberOfPixels;
blue /= numberOfPixels;

return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0f];

关于ios - UIImage 和寻找中心像素的平均 UIColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354526/

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