Giter Site home page Giter Site logo

yangkj / harbeth Goto Github PK

View Code? Open in Web Editor NEW
486.0 13.0 72.0 57.06 MB

🎨 GPU accelerated image / video and camera filter library based on Metal. Support macOS & iOS. 图像、视频、相机滤镜框架

License: MIT License

Ruby 0.31% Swift 43.18% Metal 56.09% Objective-C 0.42%
filter graphics video vr camera metal image coreimage

harbeth's Introduction

Harbeth

Animated Still

Carthage compatible CocoaPods Compatible CocoaPods Compatible Platform

Harbeth is a high performance Swift library for GPU accelerated image processing and realtime camera capture and video smooth playback, and then add filters based on Metal, and also compatible for CoreImage filters and using Metal performance shaders filters.

This library is highly inspired by GPUImage.


English | 简体中文

Features

🟣 At the moment, the most important features of metal moudle can be summarized as follows:

  • Support more platform system, macOS and iOS, both UIKit/AppKit and SwiftUI.
  • High performance quickly add filters at these sources:
    • UIImage, NSImage, CIImage, CGImage, CMSampleBuffer, CVPixelBuffer.
  • The built-in metal kernel filters is roughly divided into the following modules:
  • Setup MetalPerformanceShaders filters And also compatible for CoreImage filters.
  • Previews and rendering backed with the power of Metal.
  • Drop-in support for your own custom filters using LUTs or using Cube.
  • Realtime camera capture and video smooth playback with filters.
  • Video source processing video file by Kakapos library.

A total of 100+ kinds of built-in filters are currently available.✌️

Requirements

iOS Target macOS Target Xcode Version Swift Version
iOS 10.0+ macOS 10.13+ Xcode 10.0+ Swift 5.0+

Usage

Image

  • 🎷 Code zero intrusion add filter function for image.
let filter1 = C7ColorMatrix4x4(matrix: Matrix4x4.Color.sepia)
let filter2 = C7Granularity(grain: 0.8)
let filter3 = C7SoulOut(soul: 0.7)

let filters = [filter1, filter2, filter3]

// Use:
let dest = HarbethIO.init(element: originImage, filters: filters)
// Synchronize do something..
ImageView.image = try? dest.output()

// OR Use:
ImageView.image = try? originImage.makeGroup(filters: filters)

// OR Use:
ImageView.image = originImage.filtering(filter1, filter2, filter3)

// OR Use Operator:
ImageView.image = originImage ->> filter1 ->> filter2 ->> filter3
  • Asynchronous do something..

This performance is the best. 🚗🚗

let dest = HarbethIO.init(element: ``Source``, filter: ``filter``)

dest.transmitOutput(success: { [weak self] image in
    // do something..
})

ImageView

// It's used the same way as NSImageView.
let renderView = RenderImageView.init(image: originImage)

renderView.filters = [C7Storyboard(ranks: 2)]

Camera

  • 📸 Camera capture generates pictures.
// Add an edge detection filter:
let filter = C7EdgeGlow(lineColor: .red)

// Generate camera collector:
let camera = C7CollectorCamera.init(delegate: self)
camera.captureSession.sessionPreset = AVCaptureSession.Preset.hd1280x720
camera.filters = [filter]

extension CameraViewController: C7CollectorImageDelegate {
    func preview(_ collector: C7Collector, fliter image: C7Image) {
        // do something..
    }
}

Video

  • 📺 Local video or Network video are simply apply with filters.
lazy var video: C7CollectorVideo = {
    let videoURL = URL.init(string: "Link")!
    let asset = AVURLAsset.init(url: videoURL)
    let playerItem = AVPlayerItem.init(asset: asset)
    let player = AVPlayer.init(playerItem: playerItem)
    let video = C7CollectorVideo.init(player: player, delegate: self)
    let filter = C7ColorMatrix4x4(matrix: Matrix4x4.Color.sepia)
    video.filters = [filter]
    return video
}()

self.video.play()

extension PlayerViewController: C7CollectorImageDelegate {
    func preview(_ collector: C7Collector, fliter image: C7Image) {
        // do something..
    }
}

SwiftUI Support

  • For the direct use HarbethView, it is just a simple implementation.
  • The SwiftUI API is still in-progress and may not be production ready. We're looking for help! 🤲
let filters: [C7FilterProtocol] = [
    CIHighlight(highlight: intensity),
    C7WaterRipple(ripple: intensity),
]
HarbethView(image: inputImage, filters: filters, content: { image in
    image.resizable()
        .aspectRatio(contentMode: .fit)
})

CocoaPods

  • If you want to import Metal module, you need in your Podfile:
pod 'Harbeth'
  • If you want to import OpenCV image module, you need in your Podfile:
pod 'OpencvQueen'

Swift Package Manager

Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

Xcode 11+ is required to build Harbeth using Swift Package Manager.

To integrate Harbeth into your Xcode project using Swift Package Manager, add it to the dependencies value of your Package.swift:

dependencies: [
    .package(url: "https://github.com/yangKJ/Harbeth.git", branch: "master"),
]

Remarks

The general process is almost like this, the Demo is also written in great detail, you can check it out for yourself.🎷

HarbethDemo

Tip: If you find it helpful, please help me with a star. If you have any questions or needs, you can also issue.

Thanks.🎇

About the author

Buy me a coffee or support me on GitHub.

yellow-button

Alipay or WeChat. Thanks.


License

Harbeth is available under the MIT license. See the LICENSE file for more info.


harbeth's People

Contributors

safina008 avatar yangkj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

harbeth's Issues

Harbeth loads CPU a lot

Hello, try to compare Harbeth and GPUImage on iPhone SE and found interesting thing.
Harbeth not load GPU at all, only CPU. And it's working not so good on earlier iPhones.

How it could be fixed? Could Harbeth use GPU like GPUIMage?
Harbeth
Screenshot 2024-06-08 at 11 42 27

GPUImage
Screenshot 2024-06-08 at 11 45 28

output崩溃

    /// Copy the texture to the pixel buffer.
    /// - Parameter texture: metal texture.
    public func copyToPixelBuffer(with texture: MTLTexture) {
        base.c7.lockBaseAddress(.readOnly)
        if let pixelBufferBytes = CVPixelBufferGetBaseAddress(base) {
            // Fixed if the CVPixelBuffer and MTLTexture size is not equal.
            // If the size is inconsistent, using the modified size filter will crash.
            // Such as: C7Resize, C7Crop and so on Shape filter.
            if base.c7.size == texture.c7.toC7Size() {
                let bytesPerRow = CVPixelBufferGetBytesPerRow(base)
                let region = MTLRegionMake2D(0, 0, texture.width, texture.height)
                texture.getBytes(pixelBufferBytes, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
            }
        }
        base.c7.unlockBaseAddress(.readOnly)
    }

这句texture.getBytes(pixelBufferBytes, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)会崩溃:
_validateGetBytes:143: failed assertion `GetBytes Validation
bytesPerRow(3268) must be >= (8640).

我这里每次都崩溃,换了其他分辨率也会崩溃。
调用代码如下:

            let cameraFrame: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
            let dest = HarbethIO(element: cameraFrame, filters: [c7lookUpFilter])
            let outputPixelBuffer = try? dest.output()

Crash

Can you please check the source image for both Brightness and Exposure.

image

Look up Filter

Hello,

Some LUT images are not working.
They do work with BBMetalImage.

Thanks,
Kevin Shah

21
22
23

创建新的 metal 会闪退

正常按钮点击 ,使用 C7LookupTable 滤镜, 在没做其他任何更改的情况下,添加了一个 Metal文件, 会闪退 ,报错
-[MTLDebugComputeCommandEncoder dealloc]:289: failed assertion `Command encoder released without endEncoding.' , 因为找不到pod 下的Metal滤镜路径了, let function = try Device.readMTLFunction(kernel)
抛出了error HarbethError

Multiple filters in video lock app

Hello!
Trying to filtering video with multiple filters like in demo.
App is locked, not crushed
Code stopping in file Compute.swift, 37 row
screen

0.2.1版本问题反馈

问题:使用C7BlendFilter滤镜normal类型叠加一张照片和一个view生成的带透明通道的图片,
最后生成出来图片颜色不对,应该是R和B像素排列问题。

临时修复办法:Image文件里删除的部分代码恢复

let loader = Shared.shared.device!.textureLoader
        let options = [MTKTextureLoader.Option.SRGB : false]
        if let texture = try? loader.newTexture(cgImage: cgimage, options: options) {
            return texture
        }

这个生成图片的方法没有用过,只是暂时修复了一下,希望作者大佬抽空看下这个问题😬😬

关于视频滤镜导出

之前用了 MetalPetal 做滤镜,但想用你这个做视频滤镜后导出,有没有办法能使用 metalpetal 的滤镜用你的视频导出~

以及,视频导出如果要crop,应该怎么做,比如原来是个宽高比 3:4的视频,想居中crop 1:1 应该怎么写,求大神指导

Wrong colors on video

Try to do some demo with video again, and don't know, how to rotate and change color on it.
Here's original photo.
image

And here after Harbeth, and it's wrong rotated
image

Can you explain me that?

.HEIC 文件添加滤镜后翻转

override func viewDidLoad() {
super.viewDidLoad()

    let originalImage = UIImage(named: "IMG_0004.HEIC")
    let imageView = UIImageView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
    imageView.backgroundColor = UIColor.red
    imageView.contentMode = UIView.ContentMode.scaleAspectFill
    imageView.layer.masksToBounds = true
    self.view.addSubview(imageView)
    imageView.image = originalImage
    
    let filter1 = C7ColorMatrix4x4(matrix: Matrix4x4.sepia)
    var filter3 = C7Granularity()
    filter3.grain = 0.8

    var filter4 = C7SoulOut()
    filter4.soul = 0.7
    
    let filters = [filter1 ,filter3 ,filter4] as [C7FilterProtocol]
    imageView.image = try? originalImage?.makeGroup(filters: filters)
}

代码如上,添加滤镜后图像旋转了180度,换成其它图片没有问题

以下图片文件地址
https://github.com/Alienchang/BlogImages/blob/main/iOS/jichu/IMG_0004.HEIC

Can't import filters

Hello, can u help me?
I can't import some filters in my project.
image

I use Package Dependencies for Harbeth

App crush when video have 60 fps

Commit of this issue (#26) crush app
When i try to filter some video, it's crush due to loss memory
Domain: IDEDebugSessionErrorDomain
Code: 11
Failure Reason: Message from debugger: Terminated due to memory issue
User Info: {
DVTErrorCreationDateKey = "2023-09-27 16:20:37 +0000";
IDERunOperationFailingWorker = DBGLLDBLauncher;
}
I tryed with 30.1 fps and 60 fps but whatever it's crushing

How to correctly run the demo?

Hey,
I am trying to run the demo, but I only get a crash on Device.init, please give me some help.

Here is the information:
Xcode: Version 15.0 (15A240d)
Device: iPhone 11
OS: iOS 17

image

崩溃

较大分辨率图片比如这张,添加滤镜会崩溃!
IMGP0529

想请教Document下面的文档来源

请问Document下面的文档是作者你自己的翻译吗,对英文读写能力不足的我来说真的是太棒了!另外想请问有更多的关于metal、shader的中文翻译资料?

iPhone 15 Pro, Apple Log

Hi!

Just a question, does this framework support Apple Log? I can't get it to work with MetalPetal, so I hope it works in this framework =)

Not sure exactly why it doesn't work. Maybe x422? Pixel format? Not sure.

Hue filter set artifacts on photo

I use filters array on photo
When hue filter is in filters there are some artifacts on photo
Without hue filter everything is correct

IMG_3424
IMG_3425
IMG_3423

Rotate video on export block app

Hello! When I try to use this code (rotate video right) when fiter exporting video by Kakapos my app blocked export session

let filtering = FilterInstruction { buffer, time, callback in
      let uiimage = UIImage(cgImage: buffer.c7.toCGImage()!, scale: 1, orientation: orientation!)
      let dest = HarbethIO(element: uiimage, filters: self.filters)

      return dest.transmitOutput { image in
            callback(image.c7.toPixelBuffer() ?? buffer)
      }
}

But on simulator (iPhone 15 pro) it's works great

Demo app crashes due to memory limit

I've downloaded the repo to try it out and the demo app doesn't seem to be able to run. I always get the same error:

Thread 1: EXC_RESOURCE (RESOURCE_TYPE_MEMORY: high watermark memory limit exceeded) (limit=3376 MB)

image

Running on an iPhone 15 Pro on iOS 17.4.1. I also tested on an iPhone SE (3rd Gen) on the same iOS version and I get the same error.

Any ideas how to work around it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.