使用OpenCV人脸检测在iOS中裁剪图像
我使用下面的代码从我的脸部检测代码中的图像裁剪一张脸。 但我没有得到适当的脸部图像,我得到了保存图像的一部分,而不是脸部。 我的代码有什么问题?
_faceCascade.detectMultiScale(mat, faces, 1.1, 2, kHaarOptions, cv::Size(40, 40));
在displayfaces函数里面使用下面的代码进行裁剪:
CGRect cropRect = CGRectMake(faces[i].x, faces[i].y, faces[i].width, faces[i].width); CGImageRef cropped_img = CGImageCreateWithImageInRect(self.storeImage.CGImage, cropRect); UIImage *img = [UIImage imageWithCGImage:cropped_img]; UIImageWriteToSavedPhotosAlbum( img, self, nil,nil);
得到正确的faces[i]
坐标faces[i]
。 但问题只在于裁剪和设定ROI。 有人能帮我解决吗?
我也试着用下面的代码,再次获得相同的图像。 (即,我没有得到实际的脸部图像)
cv :: Mat image_roi; cv::Rect roi(faces[i].x, faces[i].y, faces[i].width, faces[i].height); cv::Mat(testMat, roi).copyTo(image_roi); UIImage *img = [CaptureViewController imageWithCVMat:image_roi ]; UIImageWriteToSavedPhotosAlbum( img, self, nil,nil);
注意:我使用opencv facedetect检测现场videostream中的人脸。 我可以得到脸上的绿色矩形。 但是我不能用脸部参数来裁剪脸部。 我也尝试设置faceroi来检测眼睛,即使是失败。 为了缩小这个问题,问题可能在于为图像设置投资回报率?
更新于11/02/13:
我已经完成裁剪如下,但投资回报率设置不正确,图像不能很好地裁剪:
我发现我的上述post的问题(谢谢@Jameo指出,因为旋转问题。)我已经旋转了图像如下。
UIImage *rotateImage = [[UIImage alloc] initWithCGImage: image.CGImage scale: 1.0 orientation: UIImageOrientationRight];
并使用下面的代码裁剪图像:
// get sub image + (UIImage*) getSubImageFrom: (UIImage*) img WithRect: (CGRect) rect { UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); // translated rectangle for drawing sub image CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, img.size.width, img.size.height); // clip to the bounds of the image context // not strictly necessary as it will get clipped anyway? CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height)); // draw image [img drawInRect:drawRect]; // grab image UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return subImage; }
图像被裁剪,但与实际坐标不一致。
我的观察: 1)用Affinetransform返回的FaceRect裁剪图像。 这是错误的坐标或因为我的代码中的错误? 2)在设置仿射变换之前,我无法为图像设置ROI,原因是什么,这是设置ROI的程序吗?
faceRect = CGRectApplyAffineTransform(faceRect, t);
但仍然没有正确完成裁剪差异如下所示:
全图:
裁剪的图像
那这个呢?
- (UIImage *) getSubImageFrom:(UIImage *)imageToCrop WithRect:(CGRect)rect { CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect); UIImage *cropped = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return cropped; }
试试这个来获得脸部坐标:
CGRect newBounds = CGRectMake(faceFeature.bounds.origin.x, _picture.size.height - faceFeature.bounds.origin.y - largestFace.bounds.size.height, faceFeature.bounds.size.width, faceFeature.bounds.size.height);
然后使用以下命令裁剪图像:
CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, newBounds); UIImage *croppedImage = [UIImage imageWithCGImage:subImage]; UIImageView *newView = [[UIImageView alloc] initWithImage:croppedImage];