首页 > 代码库 > opecv获取透明图像轮廓
opecv获取透明图像轮廓
获取轮廓
#import <opencv2/opencv.hpp>#import <opencv2/imgcodecs/ios.h>#import <opencv2/imgproc/types_c.h>@implementation OpenCVHelper+(UIImage *)getImageOutLine:(UIImage *)iputimg{ cv::Mat cvImage; UIImageToMat(iputimg, cvImage); cv::Mat gray; // Convert the image to grayscale; cv::cvtColor(cvImage, gray, CV_RGBA2GRAY); // Apply Gaussian filter to remove small edges cv::GaussianBlur(gray, gray, cv::Size(5,5), 1.2,1.2); // Calculate edges with Canny cv::Mat edges; cv::Canny(gray, edges, 0, 60); // Fill image with white color //cvImage.setTo(cv::Scalar(255,255,255,1)); // Change color on edges // cvImage.setTo(cv::Scalar(0,128,255,255),edges); cv::Mat cvOutImage= cv::Mat::zeros(cvImage.size(), cvImage.type()); cvOutImage.setTo(cv::Scalar(255,255,255,0)); cvOutImage.setTo(cv::Scalar(0,139,139,1),edges); return MatToUIImage(cvOutImage);}@end
转化成透明
-(UIImage *)transparentImage:(UIImage *)image{ // Create a pixel buffer in an easy to use format CGImageRef imageRef = [image CGImage]; NSUInteger width = CGImageGetWidth(imageRef); NSUInteger height = CGImageGetHeight(imageRef); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4); NSUInteger bytesPerPixel = 4; NSUInteger bytesPerRow = bytesPerPixel * width; NSUInteger bitsPerComponent = 8; CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); CGContextRelease(context); //alter the alpha int length = height * width * 4; for (int i=0; i<length; i+=4) { if (m_PixelBuf[i+0] ==255) { m_PixelBuf[i+0] =0; m_PixelBuf[i+1] =0; m_PixelBuf[i+2] =0; m_PixelBuf[i+3] =0; } } //create a new image CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); CGImageRef newImgRef = CGBitmapContextCreateImage(ctx); CGColorSpaceRelease(colorSpace); CGContextRelease(ctx); free(m_PixelBuf); UIImage *finalImage = [UIImage imageWithCGImage:newImgRef]; CGImageRelease(newImgRef); return finalImage;}
opecv获取透明图像轮廓
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。