gpt4 book ai didi

objective-c - Objective C 垂直遍历图像中的像素

转载 作者:搜寻专家 更新时间:2023-10-30 20:20:51 25 4
gpt4 key购买 nike

我现在有点困惑,第一次在堆栈溢出上发帖。我是 Objective-C 的新手,但从我的同事那里学到了很多东西。我想要做的是遍历一个 bmContext,在每个垂直循环之后水平移动 1 个像素。下面是一些代码:

NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;
NSUInteger bytesPerColumn = height * bytesPerPixel;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

const size_t bitmapByteCount = bytesPerRow * height;

struct Color {
UInt8 r;
UInt8 g;
UInt8 b;
};

for (size_t i = 0; i < bytesPerRow; i += 4) //shift 1 pixel
{
for (size_t j = 0; j < bitmapByteCount; j += bytesPerRow) //check every pixel in column
{
struct Color thisColor = {data[j + i + 1], data[j + i + 2], data[j + i + 3]};
}
}

在 java 中它看起来像这样,但我对 java 版本不感兴趣,它只是为了强调我真正的问题。我只关心 Objective-C 代码。

for (int x = 0; x = image.getWidth(); x++)
{
for (int y = 0; y = image.getHeight(); y++)
{
int rgb = image.getRGB(x, y);
//do something with pixel
}
}

我真的是水平移动一个单位,然后检查所有垂直像素,然后再次水平移动吗?我以为我是,但我的结果似乎有点不对劲。在 java 和 c# 中实现任务相当简单,如果有人知道在 Objective C 中执行此操作的更简单方法,请告诉我。提前致谢!

最佳答案

您获取像素的方式似乎不对。

如果我没理解错的话,您只想逐列遍历图像中的每个像素。正确的?这应该有效:

for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
{
int pixel = j * CGBitmapContextGetWidth(bmContext) + i;
struct Color thisColor = {data[pixel + 1], data[pixel + 2], data[pixel + 3]};
}
}

关于objective-c - Objective C 垂直遍历图像中的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549654/

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