我正在拍摄一张图像,通过屏幕上下文加载它,并逐像素地更改它。我有许多不同的滤镜应用于图像,但我需要做的最后一件事是改变色彩平衡(类似于 Photoshop)以使红色更加青色。
下面的代码显示了我如何拍摄图像、获取数据以及逐像素检查 r/g/b 值:
CGImageRef sourceImage = theImage.image.CGImage;
CFDataRef theData;
theData = CGDataProviderCopyData(CGImageGetDataProvider(sourceImage));
UInt8 *pixelData = (UInt8 *) CFDataGetBytePtr(theData);
int dataLength = CFDataGetLength(theData);
int red = 0;
int green = 1;
int blue = 2;
for (int index = 0; index < dataLength; index += 4) {
int r = pixelData[index + red];
int g = pixelData[index + green];
int b = pixelData[index + blue];
// the color balancing would go here...
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
pixelData[index + red] = r;
pixelData[index + green] = g;
pixelData[index + blue] = b;
}
CGContextRef context;
context = CGBitmapContextCreate(pixelData,
CGImageGetWidth(sourceImage),
CGImageGetHeight(sourceImage),
8,
CGImageGetBytesPerRow(sourceImage),
CGImageGetColorSpace(sourceImage),
kCGImageAlphaPremultipliedLast);
CGImageRef newCGImage = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newCGImage];
CGContextRelease(context);
CFRelease(theData);
CGImageRelease(newCGImage);
theImage.image = newImage;
我正在对像素数据执行许多其他操作(设置级别、去饱和),但我需要将红色值转向青色。
在 Photoshop 中,我可以通过以下方式做到这一点:
图像:调整:色彩平衡
并将其设置为-30 0 0
我无法找到解释如何执行此颜色偏移的算法或示例。我尝试从每个红色值中减去 30,或者将硬最大值设置为 255 - 30 (225),但这些似乎会剪切颜色而不改变值......现在,我只是在研究它,但是指向参考的指针会有很大帮助。
(注意:我无法使用 OpenGL 解决方案,因为我必须采用相同的算法并将其转换为 PHP/gd 以用于此应用程序的 Web 服务器版本)
您需要做的是减去红色,然后校正“亮度”以匹配旧颜色,无论您选择何种亮度测量。像这样的东西应该有效:
// First, calculate the current lightness.
float oldL = r * 0.30 + g * 0.59 + b * 0.11;
// Adjust the color components. This changes lightness.
r = r - 30;
if (r < 0) r = 0;
// Now correct the color back to the old lightness.
float newL = r * 0.30 + g * 0.59 + b * 0.11;
if (newL > 0) {
r = r * oldL / newL;
g = g * oldL / newL;
b = b * oldL / newL;
}
请注意,当给出纯红色时,这会表现得有些奇怪(它将保持不变)。奥托,GIMP http://www.gimp.org/(版本 2.6.11)在其色彩平衡工具中做了同样的事情,所以我不太担心它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)