<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bahadır Sönmez on Medium]]></title>
        <description><![CDATA[Stories by Bahadır Sönmez on Medium]]></description>
        <link>https://medium.com/@sonmezbahad?source=rss-7a6489157ea6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2TdXJgDmDuLYDimr</url>
            <title>Stories by Bahadır Sönmez on Medium</title>
            <link>https://medium.com/@sonmezbahad?source=rss-7a6489157ea6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:45:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sonmezbahad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implement Real-time Filtering With CIFilter]]></title>
            <link>https://medium.com/better-programming/real-time-filtering-with-cifilter-bf7af16aee04?source=rss-7a6489157ea6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf7af16aee04</guid>
            <category><![CDATA[cifilter]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bahadır Sönmez]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 06:02:39 GMT</pubDate>
            <atom:updated>2026-10-08T11:14:14.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implement Real-Time Filtering With CIFilter</h3><h4>Perform core image filtering on AVFoundation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZVEfb5zZ78KZWDri" /><figcaption>Photo by <a href="https://unsplash.com/@habibdadkhah?utm_source=medium&amp;utm_medium=referral">Habib Dadkhah</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my <a href="https://medium.com/@sonmezbahad/creating-a-custom-filter-with-cifilter-3e5a6445ec15">previous article</a>, I talked about creating a custom filter with CIFilter. In this article, I will talk about how to use CIFilter filters for real-time filtering. Camera usage and camera usage permission are required for the application to work. Make sure you ask for the Privacy — Camera Usage Description permission in Info.plist.</p><p>First, let’s create a class called CameraCapture to process and transfer the images captured by the camera. This class is initialized with a camera position and a callback closure.</p><pre>typealias Callback = (CIImage?) -&gt; ()<br>private let position: AVCaptureDevice.Position<br>private let callback: Callback<br>init(position: AVCaptureDevice.Position = .front, callback: @escaping Callback) {<br>  self.position = position<br>  self.callback = callback<br>  super.init()<br>}</pre><p>Define an AVCaptureSession and a user-initiated DispatchQueue in the class. It’s important to define userInitiated, as it will always appear in the UI.</p><pre>private let session = AVCaptureSession()<br>private let bufferQueue = DispatchQueue(label: &quot;someLabel&quot;, qos: .userInitiated)</pre><p>Write two public functions to start and end the session since the session is private.</p><pre>func start() {<br>  session.startRunning()<br>}</pre><pre>func stop() {<br>  session.stopRunning()<br>}</pre><p>Create a function for session configuration and call it after super.init(). To process the images captured by the camera, CameraCapture must conform to the AVCaptureVideoDataOutputSampleBufferDelegate protocol.</p><pre>private func configureSession() {<br>// 1<br>session.sessionPreset = .hd1280x720<br>// 2<br>let discovery = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: .video, position: position)<br>guard let camera = discovery.devices.first, let input = try? AVCaptureDeviceInput(device: camera) else {<br>// Error handling<br>return<br>}<br>session.addInput(input)<br>// 3<br>let output = AVCaptureVideoDataOutput()<br>output.setSampleBufferDelegate(self, queue: bufferQueue)<br>session.addOutput(output)<br>}</pre><p>Let’s take a step-by-step look at what’s inside the function.</p><p>1. Determining the image quality.<br>2. Finding and configuring suitable video-capturing elements with AVCaptureDevice.DiscoverySession and creating capture input with AVCaptureDeviceInput<br>3. Create the output with AVCaptureVideoDataOutput and add the delegate to the class</p><p>The captured image needs to be converted to CIImage and fed into the callback closure. Write an extension for CameraCapture that conforms AVCaptureVideoDataOutputSampleBufferDelegate for this.</p><pre>extension CameraCapture:AVCaptureVideoDataOutputSampleBufferDelegate {<br>  func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {<br>    guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }<br>    DispatchQueue.main.async {<br>      let image = CIImage(cvImageBuffer: imageBuffer)<br>      self.callback(image.transformed(by: CGAffineTransform(rotationAngle: 3 * .pi / 2)))<br>    }<br>  }<br>}</pre><p>Create a CIImage with the sampleBuffer from the delegate function and pass it to the callback. Since the incoming image is sideways, it is necessary to rotate it 270 degrees. As a result, the following class is created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e5562949b9336b2d2dce883b12e9d0a/href">https://medium.com/media/8e5562949b9336b2d2dce883b12e9d0a/href</a></iframe><p>After creating the CameraCapture class without any problems, filtering can be performed using this class. Create a ViewController with UIImageView and CameraCapture instances.</p><pre>class RealtimeFilterViewController: UIViewController {<br>  var imageView: UIImageView!<br>  var cameraCapture: CICameraCapture?<br>  override func viewDidLoad() {<br>    super.viewDidLoad()<br>    imageView = UIImageView(frame: view.bounds)<br>    view.addSubview(imageView)<br>    cameraCapture = CICameraCapture(cameraPosition: .front, callback: { image in })<br>    cameraCapture?.start()<br>  }<br>}</pre><p>Now it’s time to filter and show the image from the callback. Select and apply any built-in filter. Let’s choose the xRay filter. Do the filtering inside the callback closure. Finally, cameraCapture looks like this:</p><pre>cameraCapture = CICameraCapture(cameraPosition: .front, callback: { image in<br>  guard let image = image else { return }<br>  let filter = CIFilter.xRay()<br>  filter.setDefaults()<br>  filter.inputImage = image<br>  let uiImage = UIImage(ciImage: (filter.outputImage!.cropped(to: image.extent)))<br>  self.imageView.image = uiImage<br>})</pre><p>Let’s run it this way. But what’s that? Nothing appears, and a message is constantly logged to the console.</p><pre>2022-11-08 15:06:14.829234+0300 RealtimeFiltering[2903:883376] [api] -[CIContext(CIRenderDestination) _startTaskToRender:toDestination:forPrepareRender:forClear:error:] The image extent and destination extent do not intersect.</pre><p>The message is pretty clear. The image extent and destination extent do not intersect. We should define a function to transform and scale the image into the bounds of our view. Create an extension and use this function:</p><pre>import CoreImage<br>extension CIImage {<br>  func transformToOrigin(withSize size: CGSize) -&gt; CIImage {<br>    let originX = extent.origin.x<br>    let originY = extent.origin.y<br>    let scaleX = size.width / extent.width<br>    let scaleY = size.height / extent.height<br>    let scale = max(scaleX, scaleY)<br>    return transformed(by: CGAffineTransform(translationX: -originX, y: -originY)).transformed(by: CGAffineTransform(scaleX: scale, y: scale))<br>  }<br>}</pre><p>Now, let’s use this function to define the uiImage, and bam! We have created a working real-time filtering application.</p><pre>let uiImage = UIImage(ciImage: (filter.outputImage!.cropped(to: image.extent).transformToOrigin(withSize: self.view.bounds.size)))</pre><p>Finally, <em>RealtimeFilterViewController</em> should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e100ad8d209968dfddcdd69d2b479a4e/href">https://medium.com/media/e100ad8d209968dfddcdd69d2b479a4e/href</a></iframe><p>It works perfectly for one simple filter. The output image looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjy09uYhixC9OweU1YcLWg.jpeg" /><figcaption>Input Image → Output Image</figcaption></figure><p>But what if several filters are used as a chain? Let’s try it. Change the cameraCapture definition like this:</p><pre>cameraCapture = CICameraCapture(cameraPosition: .front, callback: { image in<br>  guard let image = image else { return }<br>  let filter = CIFilter.thermal()<br>  let filter2 = CIFilter.xRay()<br>  let filter3 = CIFilter.motionBlur()<br>  filter.setDefaults()<br>  filter2.setDefaults()<br>  filter3.setDefaults()<br>  filter.inputImage = image<br>  filter2.inputImage = filter.outputImage!<br>  filter3.inputImage = filter2.outputImage!<br>  let uiImage = UIImage(ciImage: (filter3.outputImage!.cropped(to: image.extent).transformToOrigin(withSize: self.view.bounds.size)))<br>  self.imageView.image = uiImage<br>})</pre><p>It still works, but when looking at the resource consumption, it looks like it’s literally draining.</p><figure><img alt="CPU, memory and energy usage of Realtime Filtering app" src="https://cdn-images-1.medium.com/max/540/1*gVamaCwNt0DEFwtLepHh5w.png" /></figure><p>This way is not efficient at all. So, what to do? Fortunately, Apple is aware of this and has provided a more efficient way. It’s MTKView. Create a class named MetalRenderView that inherits MTKView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c03f185d4a02e798502972701dfcbd2/href">https://medium.com/media/8c03f185d4a02e798502972701dfcbd2/href</a></iframe><p>The application will crash if the device does not support the Metal framework. The most important part of MetalRenderView is the renderImage function. This function is called when the image is assigned and makes the image suitable for MTKView. For more information, Apple’s <a href="https://developer.apple.com/documentation/metalkit/mtkview">document</a> for MTKView can be used.</p><p>Now, let’s show the filtered image with the help of this MetalRenderView. First, let’s replace the imageView in the RealtimeFilterViewController with MetalRenderView.</p><pre>var metalView: MetalRenderView!</pre><p>Secondly, replace the following block in viewDidLoad<em>:</em></p><pre>imageView = UIImageView(frame: view.bounds)<br>view.addSubview(imageView)</pre><p>…with this</p><pre>metalView = MetalRenderView(frame: view.bounds, device: MTLCreateSystemDefaultDevice())<br>view.addSubview(metalView)</pre><p>Then replace these two lines inside the <em>callback</em> closure</p><pre>let uiImage = UIImage(ciImage: (filter3.outputImage!.cropped(to: image.extent).transformToOrigin(withSize: self.view.bounds.size)))<br>self.imageView.image = uiImage</pre><p>with this</p><pre>self.metalView.setImage(filter3.outputImage?.cropped(to: image.extent))</pre><p>MetalRenderView handles transformToOrigin method on its own. Now, RealtimeFilterViewController should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8bd75b877481cea23661879bfefb9bc/href">https://medium.com/media/c8bd75b877481cea23661879bfefb9bc/href</a></iframe><p>Now, let’s run the application again and see the difference. It looks slightly better. But the slight difference will be more valuable when the number of filters increases or when working with more difficult filters.</p><figure><img alt="CPU, memory and energy usage of Realtime Filtering app" src="https://cdn-images-1.medium.com/max/548/1*NotEAuYg0SkN4aQgN8g5Nw.png" /></figure><p>Yes, we now have a fully working and more efficient real-time filtering application. The application can be developed with different filters and different UI enhancements. The app may be able to take pictures, but that’s a topic for another article.</p><pre>Want to Connect?<br><br>Linkedin: https://www.linkedin.com/in/bahadir-sonmez<br>Website: https://www.bahadirsonmez.com</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf7af16aee04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/real-time-filtering-with-cifilter-bf7af16aee04">Implement Real-time Filtering With CIFilter</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a custom filter with CIFilter]]></title>
            <link>https://medium.com/@sonmezbahad/creating-a-custom-filter-with-cifilter-3e5a6445ec15?source=rss-7a6489157ea6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5a6445ec15</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[cifilter]]></category>
            <category><![CDATA[custom-filter]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bahadır Sönmez]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 19:49:44 GMT</pubDate>
            <atom:updated>2022-10-31T19:52:34.447Z</atom:updated>
            <content:encoded><![CDATA[<p>CIFilter is one of the many great features that Apple has given us. There are already filters prepared by Apple that are very easy to use. We can access them with ‘import CIImage.CIFilterBuiltins’. But what if the filter we’re looking for isn’t among them? In such cases, it is possible to create customized filters using the Kernel language. So how? In this article, I will talk about how we can achieve this.</p><h3>Creating the kernel</h3><p>Now let’s see how we can use the <a href="https://en.wikipedia.org/wiki/Bilateral_filter">Bilateral Filter</a>. First, we need to create a ‘<em>metal’</em> file. Let’s name this file ‘FilterKernels’. Let’s replace the contents of the file with the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17ad35654348b2a2593eae534db05bf6/href">https://medium.com/media/17ad35654348b2a2593eae534db05bf6/href</a></iframe><p>First, we need to understand how the filter works. As written on the Wikipedia page, the filter takes four inputs and gives output due to some calculations. Our first input is the input image, the second input is the radius, the third input is spatial sigma, and the fourth is the sigma range. In this case, our output is the filtered image. When we translate the function on the Wikipedia page into kernel language, we encounter a function like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e548eb72c2984684bb38dd3647538827/href">https://medium.com/media/e548eb72c2984684bb38dd3647538827/href</a></iframe><p>When we take this code into the namespace coreimage, the Kernel side is completed without any problems. Now it’s time for how to use it. In the last case, the Bilateral Filter Kernel file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d5e97cc8b4ced7bacc12d179149ab3/href">https://medium.com/media/d8d5e97cc8b4ced7bacc12d179149ab3/href</a></iframe><h3>Creating the filter</h3><p>In order to use the filter we have created with the CIFilter infrastructure, we need to create its own class of filter. First, we create the BilateralFilter class that inherits from CIFilter. We define the kernel function we will use with a lazy variable. Then we define the inputs that the filter will use. Finally, we override the <em>outputImage</em> variable in CIFilter and return the result of our own function. In the last case, the BilaterFilter class takes the following form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da09cfeb51bb0e8f67b2c7254ffe547b/href">https://medium.com/media/da09cfeb51bb0e8f67b2c7254ffe547b/href</a></iframe><h3>Using the filter</h3><p>The filter we created can now be used like other CIFilter filters. When we use the following configuration as an example,</p><pre>let filter = BilateralFilter()<br>filter.inputImage = anImage<br>filter.radius = 13.0<br>filter.spatial = 15.0<br>filter.range = 0.1<br>filter.outputImage!</pre><p>We get a result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*bOjSw4z2b4d9GNO1KycPQg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5a6445ec15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>