2vi*_*on2 5 iphone opencv image-processing objective-c ios
我使用以下代码在人脸检测代码中从图像裁剪出人脸。但是我没有得到正确的人脸图像,而是得到了一部分图像而不是脸部图像。我的代码有什么问题?
_faceCascade.detectMultiScale(mat, faces, 1.1, 2, kHaarOptions, cv::Size(40, 40));
Run Code Online (Sandbox Code Playgroud)
并且在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);
Run Code Online (Sandbox Code Playgroud)
正在获取的正确坐标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);
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用opencv facedetect在实时视频流中检测人脸。我可以得到脸周围的绿色矩形。但是我无法使用人脸参数裁剪人脸。我也尝试设置faceroi来检测眼睛,即使失败了。为了缩小问题的范围,问题可能出在为图像设置ROI吗?
13年11月2日更新:
我的裁剪如下,但是ROI设置不正确,图像裁剪不佳:
我在上面的帖子中找到了问题(感谢@Jameo指出这是由于旋转问题。)我已经如下旋转了图像。
UIImage *rotateImage = [[UIImage alloc] initWithCGImage: image.CGImage
scale: 1.0
orientation: UIImageOrientationRight];
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码裁剪图像:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
图像被裁剪,但没有实际坐标。
我的观察: 1)我使用FaceRect裁剪图像,该图像由Affinetransform返回。这将是坐标错误的原因还是由于代码中的错误?2)在设置仿射变换之前,我无法为图像设置ROI,这是什么原因,这是设置ROI的过程吗?
faceRect = CGRectApplyAffineTransform(faceRect, t);
Run Code Online (Sandbox Code Playgroud)
但是仍然无法正确进行裁剪。区别如下所示:
完整图片:

裁剪图像

那这个呢?
- (UIImage *) getSubImageFrom:(UIImage *)imageToCrop WithRect:(CGRect)rect {
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
Run Code Online (Sandbox Code Playgroud)