像我这样的类似问题已经发布,但仍然有一些部分不适合我当前的问题。我用Xcode 和Objective C ++一起使用openCV。
我想要做的是在照片中围绕人眼创建一些边界框和圆圈。我使用了以下代码,但这不起作用:
-(void)detectEye {
cv::Mat src_gray;
int thresh = 100;
RNG rng(12345);
NSString *path = @"/Users/NazarMedeiros/Desktop/image.jpg";
cv::Mat src = cv::imread("/Users/NazarMedeiros/Downloads/face.jpg");
if (src.empty())
return;
cv::cvtColor(src, src_gray, CV_BGR2GRAY );
cv::blur(src_gray, src_gray, cv::Size(3,3) );
cv::Mat threshold_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<Vec4i> hierarchy;
/// Detect edges using Threshold
cv::threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
/// Find contours
cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
/// Approximate contours to polygons + get bounding rects and circles
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
std::vector<cv::Rect> boundRect( contours.size() );
std::vector<Point2f>center( contours.size() );
std::vector<float>radius( contours.size() );
for(int i = 0; i < contours.size(); i++ ) {
cv::approxPolyDP(cv::Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i]) );
cv::minEnclosingCircle( (cv::Mat)contours_poly[i], center[i], radius[i] );
}
/// Draw polygonal contour + bonding rects + circles
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
for(int i = 0; i < contours.size(); i++ ) {
cv::Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
cv::drawContours( drawing, contours_poly, i, color, 1, 8, std::vector<Vec4i>(), 0, cv::Point() );
cv::circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 );
}
imwrite([path UTF8String], src);}
} imwrite函数不保存我的图像..
有人可以帮帮我吗? 最好的祝福, Nazar Medeiros
答案 0 :(得分:2)
尝试转换&#34;绘图&#34;到UIImage
- (UIImage *)UIImageFromCVMat:(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);
// Creating CGImage from cv::Mat
CGImageRef imageRef = CGImageCreate(cvMat.cols, //width
cvMat.rows, //height
8, //bits per component
8 * cvMat.elemSize(), //bits per pixel
cvMat.step[0], //bytesPerRow
colorSpace, //colorspace
kCGImageAlphaNone|kCGBitmapByteOrderDefault,// bitmap info
provider, //CGDataProviderRef
NULL, //decode
false, //should interpolate
kCGRenderingIntentDefault //intent
);
// Getting UIImage from CGImage
UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return finalImage;
}