如何在iOS中使用MediaPipe检测静态图片
在iOS中使用MediaPipe检测静态图片的正确方法
你当前的代码只创建了输入Packet,但没有将其送入MediaPipe Graph并触发运行,这就是imagePacketWithPixelBuffer看起来“没作用”的原因。以下是完整的实现步骤和修正后的代码:
核心步骤
调整MediaPipe Graph配置:静态图处理不需要循环的视频流,要修改Graph的输入输出节点,关闭自动循环。比如以人脸检测为例,Graph配置要改成:
input_stream: "input_image" output_stream: "output_detections" node { calculator: "FaceDetectionShortRangeCalculator" input_stream: "IMAGE:input_image" output_stream: "DETECTIONS:output_detections" }确保Graph没有配置
LoopbackCalculator这类循环节点,只需要单次处理。正确传递输入并运行Graph:将静态图转为
CVPixelBuffer后,构建输入Packet,送入Graph的输入流,然后触发Graph运行,等待输出结果。解析输出并绘制结果:获取输出的检测结果,将其绘制到原始静态图上展示。
修正后的代码示例
/// 加载静态图片 UIImage *faceImage = [UIImage imageNamed:@"faceImage.jpeg"]; UIImageView *bgView = [[UIImageView alloc] initWithImage:faceImage]; bgView.frame = CGRectMake(0, 0, faceImage.size.width, faceImage.size.height); bgView.center = self.view.center; [self.view insertSubview:bgView aboveSubview:self.liveView]; UIImageView *resultView = [[UIImageView alloc] init]; resultView.frame = CGRectMake(0, CGRectGetMaxY(bgView.frame) + 20, self.view.frame.size.width, 200); [self.view insertSubview:resultView aboveSubview:self.liveView]; // 将UIImage转为CVPixelBuffer(确保格式为BGRA或MediaPipe支持的格式) CVPixelBufferRef buffer = [self pixelBufferFromCGImage:faceImage.CGImage]; // 1. 构建输入Packet,指定图像格式(这里假设是BGRA,根据你的转换方法调整) mediapipe::Packet inputPacket = mediapipe::MakePacket<mediapipe::Image>(buffer).At(mediapipe::Timestamp(0)); // 2. 将输入Packet送入Graph的输入流 MP_RETURN_IF_ERROR(self.mediapipeGraph.AddPacketToInputStream("input_image", inputPacket)); // 3. 触发Graph运行,等待处理完成 MP_RETURN_IF_ERROR(self.mediapipeGraph.WaitUntilIdle()); // 4. 获取输出结果Packet mediapipe::Packet outputPacket; MP_RETURN_IF_ERROR(self.mediapipeGraph.NextPacketOnOutputStream("output_detections", &outputPacket)); // 5. 解析检测结果(以人脸检测为例) std::vector<mediapipe::Detection> detections = outputPacket.Get<std::vector<mediapipe::Detection>>(); // 6. 将检测结果绘制到原始图片上 UIImage *resultImage = [self drawDetectionsOnImage:faceImage withDetections:detections]; resultView.image = resultImage; // 释放资源 CVPixelBufferRelease(buffer);
补充说明
pixelBufferFromCGImage方法要确保输出的CVPixelBuffer是MediaPipe支持的格式(推荐BGRA 8-bit,宽度高度为偶数),否则可能导致处理失败。drawDetectionsOnImage需要自己实现,根据Detection中的边界框信息,用Core Graphics在UIImage上绘制矩形或关键点。- 确保你的MediaPipe Graph已经初始化完成,并且配置了正确的输入输出流名称。
内容的提问来源于stack exchange,提问作者boy lucky
相关产品推荐
相关产品推荐

