用UIImage读取灰度图像素数据为0

发布于 2022-08-26 15:43:45 字数 1231 浏览 14 评论 0

灰度图

上面是我要读取的灰度图,单通道8位。我用了UIImageCGImage来读取这张图的像素数据:

UIImage *heightmap = [UIImage imageNamed:[_terrainFiles valueForKey:HEIGHTMAP]];
    CGImageRef imageRef = [heightmap CGImage];
    _width = CGImageGetWidth(imageRef);
    _height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    _heightData = (unsigned char*)calloc(_width * _height, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 1;
    NSUInteger bytesPerRow = bytesPerPixel * _width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(_heightData, _width, _height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    for (int i = 0; i < _width * _height; i++) {
        if (_heightData[i] != 0) {
            printf("%hhd ", _heightData[i]);
        }
        //printf("\n");
    }

下面我打印了读出来的数据,全是0。为什么是这样?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪花飘飘的天空 2022-09-02 15:43:45

你calloc完_heightData 就去BitmapContextCreate了,肯定是0啊。imageRef压根就没用到- -。

UIImage *heightmap = [UIImage imageNamed:[_terrainFiles valueForKey:HEIGHTMAP]];
CGImageRef imageRef = [heightmap CGImage];
_width = CGImageGetWidth(imageRef);
_height = CGImageGetHeight(imageRef);

CGDataProviderRef provider = CGImageGetDataProvider(cgimage);
NSData* data = (id)CGDataProviderCopyData(provider);

const uint8_t *heightData = [data bytes];
for (int i = 0; i < _width * _height; i++)
{
    if (heightData[i] != 0)
    {
        printf("%hhd ", _heightData[i]);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文