You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取透明图片中非透明区域的UIBezierPath?

问题:从透明图片提取UIBezierPath失败的排查

我有一张如下形状的透明图片,想提取它的UIBezierPath。我能手动在UIView里绘制六边形,但没法获取目标形状的路径。

示例形状
原始图片

手动绘制六边形的Swift代码

class FreeShapeView: UIView {
    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        context?.clear(rect)
      
        context?.setAllowsAntialiasing(true)
        context?.setShouldAntialias(true)
        context?.setLineJoin(CGLineJoin.round)
        
        let edge: CGFloat = 5.9/2

        let path: UIBezierPath = UIBezierPath()
        
        path.move(to: CGPoint(x: rect.width/2, y: edge))
        path.addLine(to: CGPoint(x: rect.width - edge, y: rect.height/3))
        path.addLine(to: CGPoint(x: rect.width - edge, y: rect.height/3*2))
        path.addLine(to: CGPoint(x: rect.width/2, y: rect.height - edge))
        path.addLine(to: CGPoint(x: edge, y: rect.height/3*2))
        path.addLine(to: CGPoint(x: edge, y: rect.height/3))
        
        path.close()
        context?.addPath(path.cgPath)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        backgroundColor = .clear
    }
}

我写的OpenCV Objective-C提取代码

+ (UIBezierPath *)removeTransparentAreaAndFindContours:(UIImage *)image {
    // Convert UIImage to cv::Mat
   
    cv::Mat cvImage = [self cvMatFromUIImage:image];


    // Convert image to grayscale
    cv::Mat grayscaleImage;
    cv::cvtColor(cvImage, grayscaleImage, cv::COLOR_RGBA2GRAY);

    // Apply threshold to create binary image
    cv::Mat binaryImage;
    cv::threshold(grayscaleImage, binaryImage, 1, 255, cv::THRESH_BINARY);

    // Find contours
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours(binaryImage, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    // Create a UIBezierPath from the contours
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    for (size_t i = 0; i < contours.size(); i++) {
        const std::vector<cv::Point> &contour = contours[i];
        for (size_t j = 0; j < contour.size(); j++) {
            const cv::Point &point = contour[j];
            CGPoint cgPoint = CGPointMake(point.x, point.y);
            if (j == 0) {
                [bezierPath moveToPoint:cgPoint];
            } else {
                [bezierPath addLineToPoint:cgPoint];
            }
        }
        [bezierPath closePath];
    }

    return bezierPath;
}

+ (cv::Mat)cvMatFromUIImage:(UIImage *)image {
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;
    cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per channel, 4 channels (RGBA)

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data, cols, rows, 8, cvMat.step[0], colorSpace, kCGImageAlphaNoneSkipLast | kCGBitmapByteOrderDefault);
    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
    CGContextRelease(contextRef);

    return cvMat;
}

提取得到的路径结果

Element 1: Type = MoveToPoint, Points = (0.0, 0.0) (6.9370081173396e-310, 0.0) 
Element 2: Type = AddLineToPoint, Points = (0.0, 794.0) (6.9370081173396e-310, 0.0) 
Element 3: Type = AddLineToPoint, Points = (619.0, 794.0) (6.9370081173396e-310, 0.0) 
Element 4: Type = AddLineToPoint, Points = (620.0, 795.0) (6.9370081173396e-310, 0.0) 
Element 5: Type = AddLineToPoint, Points = (620.0, 1270.0) (6.9370081173396e-310, 0.0) 
Element 6: Type = AddLineToPoint, Points = (1998.0, 1270.0) (6.9370081173396e-310, 0.0) 
Element 7: Type = AddLineToPoint, Points = (1998.0, 0.0) (6.9370081173396e-310, 0.0) 
Element 8: Type = CloseSubpath, Points = (1998.0, 0.0) (6.9370081173396e-310, 0.0) 

测试绘制代码

path = UIBezierPath()
        
path.move(to: CGPoint(x: 0.0, y: 0.0))
path.addLine(to: CGPoint(x:0.0 , y:794.0 ))
path.addLine(to: CGPoint(x:619.0 , y:794.0 ))
path.addLine(to: CGPoint(x: 620.0, y: 795.0 ))
path.addLine(to: CGPoint(x:620.0 , y:1270.0 ))
path.addLine(to: CGPoint(x: 1998.0, y:1270.0 ))
path.addLine(to: CGPoint(x:1998.0 , y: 0.0))
        
path.close()
context?.addPath(path.cgPath)

测试绘制结果

测试绘制结果


问题原因及修复方案

1. 坐标系翻转错误

CGImage的Y轴方向与OpenCV相反,直接绘制会导致轮廓点的Y坐标反向,提取的路径自然不对。需要在转换图像时翻转上下文修正坐标系。

2. 二值图生成逻辑错误

用灰度图判断透明区域不准确,应该直接提取Alpha通道——透明区域Alpha为0,非透明区域Alpha为255,以此生成二值图才能精准区分目标形状和背景。

3. 未筛选有效轮廓

findContours会返回图像中所有轮廓,包括背景边缘,必须筛选出面积最大的轮廓(即目标形状)来生成路径。

修复后的完整代码

+ (UIBezierPath *)removeTransparentAreaAndFindContours:(UIImage *)image {
    cv::Mat cvImage = [self cvMatFromUIImage:image];

    // 提取Alpha通道生成二值图
    cv::Mat alphaChannel;
    cv::extractChannel(cvImage, alphaChannel, 3);
    cv::Mat binaryImage;
    cv::threshold(alphaChannel, binaryImage, 0, 255, cv::THRESH_BINARY);

    // 查找轮廓
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours(binaryImage, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    if (contours.empty()) {
        return [UIBezierPath bezierPath];
    }

    // 筛选面积最大的轮廓
    size_t maxContourIndex = 0;
    double maxArea = cv::contourArea(contours[0]);
    for (size_t i = 1; i < contours.size(); i++) {
        double area = cv::contourArea(contours[i]);
        if (area > maxArea) {
            maxArea = area;
            maxContourIndex = i;
        }
    }

    // 生成UIBezierPath
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    const std::vector<cv::Point> &targetContour = contours[maxContourIndex];
    for (size_t j = 0; j < targetContour.size(); j++) {
        CGPoint cgPoint = CGPointMake(targetContour[j].x, targetContour[j].y);
        if (j == 0) {
            [bezierPath moveToPoint:cgPoint];
        } else {
            [bezierPath addLineToPoint:cgPoint];
        }
    }
    [bezierPath closePath];

    return bezierPath;
}

+ (cv::Mat)cvMatFromUIImage:(UIImage *)image {
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;
    cv::Mat cvMat(rows, cols, CV_8UC4);

    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data, cols, rows, 8, cvMat.step[0], colorSpace, kCGImageAlphaNoneSkipLast | kCGBitmapByteOrderDefault);
    // 翻转上下文修正Y轴方向
    CGContextTranslateCTM(contextRef, 0, rows);
    CGContextScaleCTM(contextRef, 1.0, -1.0);
    
    CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), image.CGImage);
    CGContextRelease(contextRef);

    return cvMat;
}

内容的提问来源于stack exchange,提问作者Erhan Demirci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 04:24:51