gpt4 book ai didi

opencv - 将 cv::Mat 转换为 MTLTexture

转载 作者:太空宇宙 更新时间:2023-11-03 21:05:41 24 4
gpt4 key购买 nike

我当前项目的一个中间步骤需要将 opencv 的 cv::Mat 转换为 MTLTexture,即 Metal 的纹理容器。我需要将 Floats 存储在 Mat 中作为纹理中的 Floats;我的项目无法承受精度损失。

这是我对这种转换的尝试。

- (id<MTLTexture>)texForMat:(cv::Mat)image context:(MBEContext *)context
{

id<MTLTexture> texture;
int width = image.cols;
int height = image.rows;
Float32 *rawData = (Float32 *)calloc(height * width * 4,sizeof(float));
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * width;
float r, g, b,a;


for(int i = 0; i < height; i++)
{
Float32* imageData = (Float32*)(image.data + image.step * i);
for(int j = 0; j < width; j++)
{
r = (Float32)(imageData[4 * j]);
g = (Float32)(imageData[4 * j + 1]);
b = (Float32)(imageData[4 * j + 2]);
a = (Float32)(imageData[4 * j + 3]);

rawData[image.step * (i) + (4 * j)] = r;
rawData[image.step * (i) + (4 * j + 1)] = g;
rawData[image.step * (i) + (4 * j + 2)] = b;
rawData[image.step * (i) + (4 * j + 3)] = a;
}
}


MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float
width:width
height:height
mipmapped:NO];
texture = [context.device newTextureWithDescriptor:textureDescriptor];
MTLRegion region = MTLRegionMake2D(0, 0, width, height);
[texture replaceRegion:region mipmapLevel:0 withBytes:rawData bytesPerRow:bytesPerRow];

free(rawData);
return texture;
}

但是好像不行。它每次从 Mat 读取零,并抛出 EXC_BAD_ACCESS。我需要 MTLPixelFormatRGBA16Float 中的 MTLTexture 来保持精度。

感谢您考虑这个问题。

最佳答案

这里的一个问题是您使用 Float32 加载原始数据,但您的纹理是 RGBA16Float,因此数据将被破坏(16Float 是 Fl​​oat32 大小的一半)。这不应该导致您的崩溃,但这是您必须处理的问题。

此外,正如“chappjc”指出的那样,您在写出数据时使用了“image.step”,但该缓冲区应该是连续的,并且永远不会有一个不仅仅是 (width * bytesPerPixel) 的步骤。

关于opencv - 将 cv::Mat 转换为 MTLTexture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652327/

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