是否有可能从 iOS 中的 UIImage 的特定颜色获取 CGPoint?

Any possibility to get CGPoint from particular color of UIImage in iOS?

考虑以下 images.How 的不规则形状示例,从边框颜色中获取 CGPoint。都是单独的图像。我正在尝试获取边界路径。

以下方法求颜色点大约(Swift 4):

extension UIImage {
    func getPoints(displayP3Red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> [CGPoint] {
        var points = [CGPoint]()

        if let imageData = self.cgImage?.dataProvider?.data {
            let data: UnsafePointer<UInt8>  = CFDataGetBytePtr(imageData)
            let allowDiff:CGFloat = 0.5

            for x in 0 ..< Int(self.size.width) {
                for y in 0 ..< Int(self.size.height) {
                    let pixelInfo: Int = ((Int(self.size.width) * y) + x) * 4

                    let diffRed = CGFloat(data[pixelInfo]) / 255.0 - displayP3Red
                    let diffGreen = CGFloat(data[pixelInfo+1]) / 255.0 - green
                    let diffBlue = CGFloat(data[pixelInfo+2]) / 255.0 - blue
                    let diffAlpha = CGFloat(data[pixelInfo+3]) / 255.0 - alpha

                    if abs(diffRed) < allowDiff
                        && abs(diffGreen) < allowDiff
                        && abs(diffBlue) < allowDiff
                        && abs(diffAlpha) < allowDiff { // compare the color approximately
                        points.append(CGPoint(x: x, y: y))
                    }
                }
            }
        }

        return points
    }
}

像这样使用它:

let image = UIImage(named: "yourImage.png")
let pointsOfColor = image?.getPoints(displayP3Red: 204.0/255.0, green: 33.0/255.0, blue: 50.0/255.0, alpha: 1.0)

发布的图片经过测试:

也许您需要通过获取平均值来减小数组大小,然后计算路径。

-(NSMutableArray *)getPointsfromRGB:(CGFloat)Red :(CGFloat)Green :(CGFloat)Blue andAlpha:(CGFloat)Alpha
{
    NSMutableArray* resultPoint = [NSMutableArray new];

    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);
    CGFloat allowDiff = 0.015;

    for (int x=0; x<self.size.width; x++) {

        for (int y=0; y<self.size.width; y++) {

            int pixelInfo = ((self.size.width  * y) + x ) * 4; // The image is png
            UInt8 red = (data[pixelInfo] / 255.0 ) - Red;
            UInt8 green = (data[(pixelInfo + 1)] / 255.0) - Green;
            UInt8 blue = (data[pixelInfo + 2] / 255.0) - Blue;
            UInt8 alpha = (data[pixelInfo + 3] / 255.0) - Alpha;
            if ((red) < allowDiff && (green) < allowDiff && (blue) < allowDiff && (alpha) < allowDiff) {
                [resultPoint addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
            }

        }

    }

    return resultPoint;
}