swiftacceleratevimage

Array of pixel values for vImage PixelBuffer produces black bar in image


In the code shown below, I'm generating an array of RGB pixel values for the vImage.PixelBuffer and creating an image from that buffer. But the generated image contains a black bar. Any ideas on what is causing the black bar?

import Accelerate

let width = 200
let height = 200

var pixelValues = [UInt8](repeating: 0, count: width * height * 3)

for i in 0..<pixelValues.count {
    pixelValues[i] = .random(in: 0...255)
}

let buffer = vImage.PixelBuffer(
    pixelValues: pixelValues,
    size: .init(width: width, height: height),
    pixelFormat: vImage.Interleaved8x3.self
)

let format = vImage_CGImageFormat(
    bitsPerComponent: 8,
    bitsPerPixel: 8 * 3,
    colorSpace: CGColorSpaceCreateDeviceRGB(),
    bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue)
)!

let image = buffer.makeCGImage(cgImageFormat: format)!

pixels image


Solution

  • I believe the CGImageAlphaInfo enum value you are using says to skip over the unused alpha byte, but since you don't have an alpha byte, you should use CGImageAlphaInfo.none.rawValue instead:

    Change:

    bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue)
    

    To:

    bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
    

    Doing this gives the expected result.