gpt4 book ai didi

iphone - iOS 中的 Opencv 内存管理(带 ARC 的 Objective-c)

转载 作者:可可西里 更新时间:2023-11-01 05:42:20 26 4
gpt4 key购买 nike

这可能是个愚蠢的问题,但是在 iOS 中编程时 ARC(自动引用计数)是否与 Open CV 交互?

我问这个是因为我最近才开始使用 Open CV。在带有 ARC 的 iOS 上,不必担心对象,因为我只需要确保没有指针指向它们,这样它们就可以被释放。

Open CV好像也有类似的清理功能:

http://opencv.willowgarage.com/documentation/cpp/memory_management.html

When using the new interface, the most of memory deallocation and even memory allocation operations are done automatically when needed.

首先,这是否意味着我不必释放那些对象?

其次,我在同一个 .mm 文件中同时使用 OpenCV 和 Objective C。假设这些对象不会相互混淆是否安全?

例如,这会给我一个来自 cv Mat 的 UIImage:

+ (UIImage *)imageWithCVMat:(const cv::Mat&)cvMat
{
return [[UIImage alloc] initWithCVMat:cvMat];
}

使用这个:

- (id)initWithCVMat:(const cv::Mat&)cvMat
{
NSData *data = [NSData dataWithBytes:cvMat.data length:cvMat.elemSize() * cvMat.total()];

CGColorSpaceRef colorSpace;

if (cvMat.elemSize() == 1)
{
colorSpace = CGColorSpaceCreateDeviceGray();
}
else
{
colorSpace = CGColorSpaceCreateDeviceRGB();
}

CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);

CGImageRef imageRef = CGImageCreate(cvMat.cols, // Width
cvMat.rows, // Height
8, // Bits per component
8 * cvMat.elemSize(), // Bits per pixel
cvMat.step[0], // Bytes per row
colorSpace, // Colorspace
kCGImageAlphaNone | kCGBitmapByteOrderDefault, // Bitmap info flags
provider, // CGDataProviderRef
NULL, // Decode
false, // Should interpolate
kCGRenderingIntentDefault); // Intent

self = [self initWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);

return self;
}

*方法取自 Robin Summerhill

提前感谢您的任何建议。

最佳答案

First, does this means I don't have to release those objects?

是的,直到您使用 new 运算符创建它们。看这段代码:

{
cv::Mat image(640,480); // allocate image
//.. do something with it
self.myImage = [UIImage imageWithCVMat:image];
}
// Out of scope - image is deallocated automatically.
// But self.myImage is still accessible since it contains a copy of image.

Second, I am using both OpenCV and Objective C in the same .mm file. Is it safe to assume that the objects won't be messing with each other?

在您的 initWithCVMat 函数中,图像数据被复制到 NSData 对象,该对象用于初始化 UIImage 的新实例。

对你来说这意味着:
1) UIImage 类的实例将负责释放图像数据。如果您使用 ARC - 它会自动完成;否则你必须调用[UIImage release]
2)不用担心 cv::Mat - 它会在销毁时自动释放内存。

关于iphone - iOS 中的 Opencv 内存管理(带 ARC 的 Objective-c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9697934/

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