Accelerate框架详细解析(三) —— 基于Accelerate 和 vImage的SwiftUI程序图像处理(二)

版本记录

版本号 时间
V1.0 2021.03.14 星期日

前言

Accelerate框架进行大规模的数学计算和图像计算,针对高性能进行优化。接下来几篇我们就一起看一下这个框架。感兴趣的可以看上面几篇。
1. Accelerate框架详细解析(一) —— 基本概览(一)
2. Accelerate框架详细解析(二) —— 基于Accelerate 和 vImage的SwiftUI程序图像处理(一)

源码

1. Swift

首先看下工程组织结构

下面就是源码了

1. AppMain.swift
import SwiftUI

@main
struct AppMain: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
2. ContentView.swift
import SwiftUI
import Accelerate

struct ContentView: View {
    @State private var originalImage = UIImage()
    @State private var originalHistogram: HistogramLevels?
    @State private var showImagePicker = false
    @State private var processedImage: UIImage?
    @State private var processedHistogram: HistogramLevels?

    var body: some View {
        ScrollView {
            VStack {
                Button(
                    action: {
                        showImagePicker = true
                    }, label: {
                        Label("Select Photo", systemImage: "photo")
                    })
                    .sheet(
                        isPresented: $showImagePicker,
                        onDismiss: {
                            let imageWrapper = VImageWrapper(uiImage: originalImage)
                            processedImage = nil
                            processedHistogram = nil
                            originalHistogram = imageWrapper.getHistogram(.original)
                        }, content: {
                            ImagePicker(
                                selectedImage: $originalImage,
                                showSheet: $showImagePicker
                            )
                        }
                    )
                ImageView(
                    title: "Original",
                    image: originalImage,
                    histogram: originalHistogram
                )
                HStack {
                    Button("Equalize Histogram") {
                        var imageWrapper = VImageWrapper(uiImage: originalImage)
                        imageWrapper.equalizeHistogram()
                        processedImage = imageWrapper.processedImage
                        processedHistogram = imageWrapper.getHistogram(.processed)
                    }
                    Spacer()
                    Button("Reflect") {
                        var imageWrapper = VImageWrapper(uiImage: originalImage)
                        imageWrapper.reflectImage()
                        processedImage = imageWrapper.processedImage
                        processedHistogram = imageWrapper.getHistogram(.processed)
                    }
                }.disabled(originalImage.cgImage == nil)
                if let image = processedImage {
                    ImageView(
                        title: "Processed",
                        image: image,
                        histogram: processedHistogram
                    ).padding(3)
                }
            }.padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
3. HistogramView.swift
import SwiftUI

struct HistogramLevels {
    var red: [UInt]
    var green: [UInt]
    var blue: [UInt]
    var alpha: [UInt]
}

struct HistogramLine: View {
    var channel: [UInt]
    var color: Color
    var proxy: GeometryProxy
    var maxValue: UInt

    func xForBin(_ bin: Int, proxy: GeometryProxy) -> CGFloat {
        let widthOfBin = proxy.size.width / CGFloat(channel.count)
        return CGFloat(bin) * widthOfBin
    }

    func yForCount(_ count: UInt, proxy: GeometryProxy) -> CGFloat {
        let heightOfLevel = proxy.size.height / CGFloat(maxValue)
        return proxy.size.height - CGFloat(count) * heightOfLevel
    }

    var body: some View {
        Path { path in
            for bin in 0..<channel.count {
                let newPoint = CGPoint(
                    x: xForBin(bin, proxy: proxy),
                    y: yForCount(channel[bin], proxy: proxy)
                )
                if bin == 0 {
                    path.move(to: newPoint)
                } else {
                    path.addLine(to: newPoint)
                }
            }
        }.stroke(color)
    }
}

struct HistogramView: View {
    var histogram: HistogramLevels

    var binCount: Int {
        histogram.red.count
    }

    var body: some View {
        GeometryReader { proxy in
            HistogramLine(
                channel: histogram.red,
                color: Color.red,
                proxy: proxy,
                maxValue: histogram.red.max() ?? 1
            )
            HistogramLine(
                channel: histogram.green,
                color: Color.green,
                proxy: proxy,
                maxValue: histogram.green.max() ?? 1
            )
            HistogramLine(
                channel: histogram.blue,
                color: Color.blue,
                proxy: proxy,
                maxValue: histogram.blue.max() ?? 1
            )
        }
    }
}

struct HistogramView_Previews: PreviewProvider {
    static var previews: some View {
        HistogramView(
            histogram: HistogramLevels(
                red: [0, 1, 2, 3, 4],
                green: [3, 4, 4, 6, 7],
                blue: [10, 9, 8, 7, 6],
                alpha: [2, 8, 4, 6, 5]
            )
        )
        .frame(width: 375, height: 275)
        .border(Color.gray)
    }
}
4. ImagePicker.swift
import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @Binding var selectedImage: UIImage
    @Binding var showSheet: Bool

    func makeUIViewController(
        context: UIViewControllerRepresentableContext<ImagePicker>
    ) -> UIImagePickerController {
        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator
        return imagePicker
    }

    func updateUIViewController(
        _ uiViewController: UIImagePickerController,
        context: UIViewControllerRepresentableContext<ImagePicker>
    ) {
    }

    func makeCoordinator() -> ImagePickerCoordinator {
        Coordinator(self)
    }
}

class ImagePickerCoordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var parent: ImagePicker

    init(_ parent: ImagePicker) {
        self.parent = parent
    }

    func imagePickerController(
        _ picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
    ) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            parent.selectedImage = image
            parent.showSheet = false
        }
    }
}
5. ImageView.swift
import SwiftUI

struct ImageView: View {
    var title: String
    var image: UIImage
    var histogram: HistogramLevels?
    @State private var showHistogram = false

    var body: some View {
        Text(title)
        ZStack(alignment: .bottomTrailing) {
            Image(uiImage: image)
                .resizable()
                .frame(width: 355, height: 250)
                .scaledToFit()
                .border(Color.black)
                .onTapGesture {
                    showHistogram.toggle()
                }
            if let histogram = histogram {
                if showHistogram {
                    HistogramView(histogram: histogram)
                        .background(Color.white)
                        .frame(width: 150, height: 113)
                        .padding(5)
                }
            }
        }
    }
}
6. VImageWrapper.swift
import UIKit
import Accelerate

enum WrappedImage {
    case original
    case processed
}

struct VImageWrapper {
    var uiImage: UIImage
    var processedImage: UIImage?
    let vNoFlags = vImage_Flags(kvImageNoFlags)

  init(uiImage: UIImage) {
    self.uiImage = uiImage
    if let buffer = createVImage(image: uiImage),
      let converted = convertToUIImage(buffer: buffer) {
        processedImage = converted
    }
  }

    func createVImage(image: UIImage) -> vImage_Buffer? {
        guard
            let cgImage = uiImage.cgImage,
            let imageBuffer = try? vImage_Buffer(cgImage: cgImage)
        else {
            return nil
        }
        return imageBuffer
    }

    func convertToUIImage(buffer: vImage_Buffer) -> UIImage? {
        guard
            let originalCgImage = uiImage.cgImage,
            let format = vImage_CGImageFormat(cgImage: originalCgImage),
            let cgImage = try? buffer.createCGImage(format: format)
        else {
            return nil
        }

        let image = UIImage(
            cgImage: cgImage,
            scale: 1.0,
            orientation: uiImage.imageOrientation)
        return image
    }

  mutating func equalizeHistogram() {
    guard
      let image = uiImage.cgImage,
      var imageBuffer = createVImage(image: uiImage),
      var destinationBuffer = try? vImage_Buffer(
        width: image.width,
        height: image.height,
        bitsPerPixel: UInt32(image.bitsPerPixel))
    else {
      print("Error creating image buffers.")
      processedImage = nil
      return
    }
    defer {
      imageBuffer.free()
      destinationBuffer.free()
    }

    let error = vImageEqualization_ARGB8888(
      &imageBuffer,
      &destinationBuffer,
      vNoFlags)

    guard error == kvImageNoError else {
      printVImageError(error: error)
      processedImage = nil
      return
    }
    processedImage = convertToUIImage(buffer: destinationBuffer)
  }

  mutating func reflectImage() {
    guard
      let image = uiImage.cgImage,
      var imageBuffer = createVImage(image: uiImage),
      var destinationBuffer = try? vImage_Buffer(
        width: image.width,
        height: image.height,
        bitsPerPixel: UInt32(image.bitsPerPixel))
    else {
      print("Error creating image buffers.")
      processedImage = nil
      return
    }
    defer {
      imageBuffer.free()
      destinationBuffer.free()
    }

    let error = vImageHorizontalReflect_ARGB8888(
      &imageBuffer,
      &destinationBuffer,
      vNoFlags)

    guard error == kvImageNoError else {
      printVImageError(error: error)
      processedImage = nil
      return
    }
    processedImage = convertToUIImage(buffer: destinationBuffer)
  }

    func getHistogram(_ image: WrappedImage) -> HistogramLevels? {
        guard
            let cgImage = image == .original ? uiImage.cgImage : processedImage?.cgImage,
            var imageBuffer = try? vImage_Buffer(cgImage: cgImage)
        else {
            return nil
        }
        defer {
            imageBuffer.free()
        }

        var redArray: [vImagePixelCount] = Array(repeating: 0, count: 256)
        var greenArray: [vImagePixelCount] = Array(repeating: 0, count: 256)
        var blueArray: [vImagePixelCount] = Array(repeating: 0, count: 256)
        var alphaArray: [vImagePixelCount] = Array(repeating: 0, count: 256)
        var error: vImage_Error = kvImageNoError

        redArray.withUnsafeMutableBufferPointer { rPointer in
            greenArray.withUnsafeMutableBufferPointer { gPointer in
                blueArray.withUnsafeMutableBufferPointer { bPointer in
                    alphaArray.withUnsafeMutableBufferPointer { aPointer in
                        var histogram = [
                            rPointer.baseAddress, gPointer.baseAddress,
                            bPointer.baseAddress, aPointer.baseAddress
                        ]
                        histogram.withUnsafeMutableBufferPointer { hPointer in
                            if let hBaseAddress = hPointer.baseAddress {
                                error = vImageHistogramCalculation_ARGB8888(
                                    &imageBuffer,
                                    hBaseAddress,
                                    vNoFlags
                                )
                            }
                        }
                    }
                }
            }
        }

        guard error == kvImageNoError else {
            printVImageError(error: error)
            return nil
        }
        let histogramData = HistogramLevels(
            red: redArray,
            green: greenArray,
            blue: blueArray,
            alpha: alphaArray
        )
        return histogramData
    }
}

extension VImageWrapper {
    func printVImageError(error: vImage_Error) {
        let errDescription = vImage.Error(vImageError: error).localizedDescription
        print("vImage Error: \(errDescription)")
    }
}

后记

本篇主要讲述了基于AcceleratevImageSwiftUI程序图像处理,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,142评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,298评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,068评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,081评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,099评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,071评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,990评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,832评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,274评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,488评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,649评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,378评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,979评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,625评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,643评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,545评论 2 352

推荐阅读更多精彩内容