swift2 Swift 2.2 -计算UIImage中的黑色像素

oyxsuwqo  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(248)

我需要在UIImage中计算所有的黑色像素。我已经找到了一个代码,可以工作,但它是在Objective-C中编写的。我试图在swift中转换它,但我得到了很多错误,我无法找到修复它们的方法。
使用Swift执行此操作的最佳方法是什么?
简单图像x1c 0d1x
目标C:

/**
 * Structure to keep one pixel in RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA format
 */

struct pixel {
    unsigned char r, g, b, a;
};

/**
 * Process the image and return the number of pure red pixels in it.
 */

- (NSUInteger) processImage: (UIImage*) image
{
    NSUInteger numberOfRedPixels = 0;

    // Allocate a buffer big enough to hold all the pixels

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
    if (pixels != nil)
    {
        // Create a new bitmap

        CGContextRef context = CGBitmapContextCreate(
            (void*) pixels,
            image.size.width,
            image.size.height,
            8,
            image.size.width * 4,
            CGImageGetColorSpace(image.CGImage),
            kCGImageAlphaPremultipliedLast
        );

        if (context != NULL)
        {
            // Draw the image in the bitmap

            CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);

            // Now that we have the image drawn in our own buffer, we can loop over the pixels to
            // process it. This simple case simply counts all pixels that have a pure red component.

            // There are probably more efficient and interesting ways to do this. But the important
            // part is that the pixels buffer can be read directly.

            NSUInteger numberOfPixels = image.size.width * image.size.height;

            while (numberOfPixels > 0) {
                if (pixels->r == 255) {
                    numberOfRedPixels++;
                }
                pixels++;
                numberOfPixels--;
            }

            CGContextRelease(context);
        }

        free(pixels);
    }

    return numberOfRedPixels;
}
8cdiaqws

8cdiaqws1#

使用Accelerate的vImageHistogramCalculation获取图像中不同通道的直方图要快得多:

let img: CGImage = CIImage(image: image!)!.cgImage!

let imgProvider: CGDataProvider = img.dataProvider!
let imgBitmapData: CFData = imgProvider.data!
var imgBuffer = vImage_Buffer(data: UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(imgBitmapData)), height: vImagePixelCount(img.height), width: vImagePixelCount(img.width), rowBytes: img.bytesPerRow)

let alpha = [UInt](repeating: 0, count: 256)
let red = [UInt](repeating: 0, count: 256)
let green = [UInt](repeating: 0, count: 256)
let blue = [UInt](repeating: 0, count: 256)

let alphaPtr = UnsafeMutablePointer<vImagePixelCount>(mutating: alpha) as UnsafeMutablePointer<vImagePixelCount>?
let redPtr = UnsafeMutablePointer<vImagePixelCount>(mutating: red) as UnsafeMutablePointer<vImagePixelCount>?
let greenPtr = UnsafeMutablePointer<vImagePixelCount>(mutating: green) as UnsafeMutablePointer<vImagePixelCount>?
let bluePtr = UnsafeMutablePointer<vImagePixelCount>(mutating: blue) as UnsafeMutablePointer<vImagePixelCount>?

let rgba = [redPtr, greenPtr, bluePtr, alphaPtr]

let histogram = UnsafeMutablePointer<UnsafeMutablePointer<vImagePixelCount>?>(mutating: rgba)
let error = vImageHistogramCalculation_ARGB8888(&imgBuffer, histogram, UInt32(kvImageNoFlags))

运行后,alpharedgreenblue现在是图像中颜色的直方图。如果redgreenblue都只有第0个点的颜色数,而alpha只有最后一个点的颜色数,则图像为黑色。
如果您甚至不想检查多个数组,则可以使用vImageMatrixMultiply合并不同的通道:

let readableMatrix: [[Int16]] = [
    [3,     0,     0,    0]
    [0,     1,     1,    1],
    [0,     0,     0,    0],
    [0,     0,     0,    0]
]

var matrix: [Int16] = [Int16](repeating: 0, count: 16)

for i in 0...3 {
    for j in 0...3 {
        matrix[(3 - j) * 4 + (3 - i)] = readableMatrix[i][j]
    }
}
vImageMatrixMultiply_ARGB8888(&imgBuffer, &imgBuffer, matrix, 3, nil, nil, UInt32(kvImageNoFlags))

如果你在直方图之前插入这个,你的imgBuffer将被修改为平均每个像素的RGB,并将平均值写入B通道。因此,你可以只检查blue直方图,而不是所有三个。
(btw,我找到的对vImageMatrixMultiply最好的描述是在源代码中,比如在https://github.com/phracker/MacOSX-SDK/blob/2d 31 dd 8bdd 670293 b59869335 d9 f1 f80 ca 2075 e0/MacOSX10.7.sdk/System/Library/Frameworks/Accelerate.framework/版本/A/Frameworks/vImage.框架/版本/A/头/转换。

kupeojn6

kupeojn62#

我现在遇到了一个类似的问题,我需要确定一个图像是否是100%黑色的。下面的代码将返回它在图像中找到的纯黑色像素的数量。
但是,如果要提高阈值,则可以更改比较值,并允许它允许更大范围的可能颜色。

import UIKit

extension UIImage {
    var blackPixelCount: Int {
        var count = 0
        for x in 0..<Int(size.width) {
            for y in 0..<Int(size.height) {
                count = count + (isPixelBlack(CGPoint(x: CGFloat(x), y: CGFloat(y))) ? 1 : 0)
            }
        }

        return count
    }

    private func isPixelBlack(_ point: CGPoint) -> Bool {
        let pixelData = cgImage?.dataProvider?.data
        let pointerData: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

        let pixelInfo = Int(((size.width * point.y) + point.x)) * 4

        let maxValue: CGFloat = 255.0
        let compare: CGFloat = 0.01

        if (CGFloat(pointerData[pixelInfo]) / maxValue) > compare { return false }
        if (CGFloat(pointerData[pixelInfo + 1]) / maxValue) > compare { return false }
        if (CGFloat(pointerData[pixelInfo + 2]) / maxValue) > compare { return false }

        return true
    }
}

您可以使用以下命令调用此函数:

let count = image.blackPixelCount

一个警告是,这是一个非常缓慢的过程,即使是在小图像。

相关问题