<?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 Muhammad Asad on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Asad on Medium]]></description>
        <link>https://medium.com/@molvOps?source=rss-46702fa1e2b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xHMASWRi8pesswl20LGhTg.jpeg</url>
            <title>Stories by Muhammad Asad on Medium</title>
            <link>https://medium.com/@molvOps?source=rss-46702fa1e2b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:36:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@molvOps/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[How to make an API using Django REST Framework — DRF]]></title>
            <link>https://medium.com/@molvOps/how-to-make-an-api-using-django-rest-framework-drf-5dce67924098?source=rss-46702fa1e2b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dce67924098</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Muhammad Asad]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 17:13:17 GMT</pubDate>
            <atom:updated>2026-02-16T17:13:17.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DYYEc7FKyBYRAg4c" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Django is a high-level Python web framework designed to help developers build elegant and advanced web applications quickly. It follows the <strong>Model–View–Template (MVT)</strong> architecture and comes with many built-in features such as authentication, ORM, admin panel, and URL routing. Traditionally, Django is used to render HTML pages on the server and deliver them to users via web browsers.</p><p>However, modern applications rarely rely only on server-rendered pages. Mobile apps, SPAs (React, Vue, Angular), IoT devices, and other clients usually communicate with the backend via <strong>APIs</strong>, not HTML. This is where <strong>Django REST Framework (DRF)</strong> comes in. It is a powerful toolkit built on top of Django that makes it easy to build <strong>RESTful APIs</strong>. Instead of returning HTML templates, DRF returns structured data formats like <strong>JSON</strong>, making it ideal for mobile and frontend applications.</p><p>In this blog, we will build a simple API step-by-step using Django REST Framework — starting from project setup, defining models, creating serializers, building API views, and finally testing our endpoints.</p><p>Before building any API, we need to set up a Django project and install Django REST Framework.</p><p>1- First we created a virtual environment, which you know is compulsory for separating our project’s environment settings from others and eventually preventing package clashes.</p><pre>python -m venv venv  <br>source venv/bin/activate   # macOS/Linux<br>venv\Scripts\activate      # Windows</pre><p><strong>2- DRF </strong>installation command. <strong>Django</strong> is the core web framework and <strong>DRF </strong>adds API capabilities on top of Django.</p><pre>pip install django djangorestframework</pre><p>3- Following command creates the main Django configuration folder containing:<br>settings.py – project configuration<br>urls.py – URL routing<br>wsgi.py / asgi.py – deployment entry points</p><pre>django-admin startproject api_project<br>cd api_project</pre><p>4- Create an app. Apps in Django are modular components. We will keep all API-related code inside this api app. Suppose we are developing a Student Management System for school, then we would create an app for Students, second for Fee, another for Teachers etc, and all of them would give us different endpoints and API settings for configuration.</p><pre>python manage.py startapp api</pre><p>5- Open api_project/settings.py and include your app and <strong>rest_framework </strong>in INSTALLED_APPS. This tells django that you have an app inside your project eventually enabling it to load <strong>DRF</strong> and our <strong>api</strong> app.</p><pre>INSTALLED_APPS = [<br>    ...<br>    &#39;rest_framework&#39;,<br>    &#39;api&#39;,<br>]</pre><p>6- Run this command and you will see your server is running at <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> i.e. at localhost and port 8000.</p><pre>python manage.py runserver</pre><p>An API is usually built around data. In Django, data is represented using <strong>models</strong>, which map directly to database tables using ORM (Object Relational Mapping). For this tutorial, we’ll create a simple <strong>Student</strong> model (you can replace it with any domain object later).</p><p>1- Open api/models.py and add:</p><pre>from django.db import models<br><br>class Student(models.Model):<br>    name = models.CharField(max_length=100)<br>    email = models.EmailField(unique=True)<br>    age = models.IntegerField()<br>    created_at = models.DateTimeField(auto_now_add=True)<br><br>    def __str__(self):<br>        return self.name</pre><p>models.Model Base class for all Django models (maps to a DB table).<br>CharField String column with max length constraint<br>EmailField Special field with email validation.<br>IntegerField Numeric column.<br>DateTimeField(auto_now_add=True) Automatically stores creation timestamp.<br>__str__ function controls how the object appears in Django Admin and shell.</p><p>2- After defining a model, Django must generate and apply migrations.</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p><strong>Migrations</strong> are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.</p><p>makemigrations Basically generates the SQL commands for preinstalled apps we added inside INSTALLED_APPS but it doesn’t execute them.<br>migrate on the other hand, executes those scripts and creates actual database tables.</p><p>3- If you wanna use built in admin features offered by django, you can register your model in admin.py and it will give you access your Models and perform CRUD manually through GUI without making a separate admin panel.</p><pre>from django.contrib import admin<br>from .models import Student<br><br>admin.site.register(Student)<br><br>#and then create an admin user i.e. superuser in django language<br><br>python manage.py createsuperuser  #Run this in terminal and give credentials<br><br>#Run server and visit <br>http://127.0.0.1:8000/admin/<br><br>#and you will be able to see auth panel and then Students to add, edit, Delete etc.</pre><p>At this point, we have a Django model, but Django alone <strong>cannot expose JSON APIs automatically</strong>. This is where <strong>Django REST Framework (DRF)</strong> comes in. DRF introduces two core concepts:</p><p>i) <strong>Serializers</strong> which convert Python objects to JSON and vice versa. A serializer is like a form for APIs<strong>.</strong></p><p>ii) <strong>Viewsets </strong>which handle HTTP requests (GET, POST, PUT, DELETE) automatically. Viewsets basically execute the functionality of Views in simple Django but they combine all the relevant logic inside a single class and require less code as compared to normal views.</p><p>1- Create a file api/serializers.py:</p><pre>from rest_framework import serializers<br>from .models import Student<br><br>class StudentSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Student<br>        fields = &quot;__all__&quot;</pre><p>Serializer validates incoming JSON to native python objects (which we defined in models.py) and similarly convert these objects to JSON for returning a response. It also enforces constraints like (required fields, types, uniqueness, etc.)</p><p>ModelSerializers is basically DRF shortcut that automatically maps model fields to serializer fields, and reduces boilerplate code.<br>fields = &quot;__all__&quot; means expose all model fields via API. Remember, don’t use fields = &quot;__all__&quot; if you have some sensitive field in models.py like password etc. (in that case, exclude that field from serializer)</p><p>2- Create api/views.py:</p><pre>from rest_framework import viewsets<br>from .models import Student<br>from .serializers import StudentSerializer<br><br>class StudentViewSet(viewsets.ModelViewSet):<br>    queryset = Student.objects.all()<br>    serializer_class = StudentSerializer</pre><p>We can consider ViewSet as <strong>controller </strong>for <strong>REST APIs</strong>. A ViewSet class is simply <strong>a type of class-based View, that does not provide any method handlers</strong> such as .get() or .post(), and instead provides actions such as .list() and .create(). The ModelViewSet class inherits from GenericAPIView and provides all CRUD endpoints e.g. .retrieve(), .create(), .update() etc automatically.</p><p>queryset Defines which objects the API can access. It is basically a collection of data from a database. A <strong>QuerySet </strong>is built up as a list of objects and makes it easier to get the data we actually need, by allowing us to filter and order the data at an early stage.</p><p>Traditional Django views require manual logic, while <strong>ViewSets a</strong>uto-generate REST endpoints, follow REST conventions, and work ideally with routers offering less boilerplate code, i.e. One class = full REST API.</p><p>Flow of a POST API request is Client sends JSON, viewsets receive it, serializers validate incoming data to python models objects and save in database, and similarly retrieve/list objects from database and convert to JSON for GET requets.</p><p>3- Now we need to expose our ViewSet as real API endpoints. DRF provides <strong>routers</strong> that automatically generate RESTful URLs for us. In api/urls.py:</p><pre>from rest_framework.routers import DefaultRouter<br>from .views import StudentViewSet<br><br>router = DefaultRouter()<br>router.register(r&#39;students&#39;, StudentViewSet)<br><br>urlpatterns = router.urls</pre><p>Then include it in the project’s main urls.py:</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&quot;api/&quot;, include(&quot;api.urls&quot;)),<br>]</pre><p>This would allow <strong>DRF to </strong>automatically create these endpoints:</p><p>GET /api/students/ List students<br>POST /api/students/ Create student<br>GET /api/students/&lt;id&gt;/ Retrieve<br>PUT/PATCH /api/students/&lt;id&gt;/ Update<br>DELETE /api/students/&lt;id&gt;/ Delete</p><p>No manual URL handling required.</p><p>Django REST Framework makes building APIs in Django straightforward and scalable. With serializers, ViewSets, and routers, you can go from a database model to a fully functional REST API with minimal boilerplate and clean architecture.</p><p>If you found this guide helpful, give it a clap and follow me for more backend and system design content. And if you spot any mistakes or have suggestions, feel free to share — I’m always looking to improve and refine my understanding.</p><p><strong>References:<br></strong><a href="https://www.django-rest-framework.org/api-guide/viewsets/">https://www.django-rest-framework.org/api-guide/viewsets/</a><br><a href="https://www.w3schools.com/django/django_queryset.php">https://www.w3schools.com/django/django_queryset.php</a><br><a href="https://www.django-rest-framework.org/">https://www.django-rest-framework.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dce67924098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speech-to-Text Conversion in iOS — using Speech framework]]></title>
            <link>https://medium.com/@molvOps/speech-to-text-conversion-in-ios-using-speech-framework-2d82aaf6e35d?source=rss-46702fa1e2b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d82aaf6e35d</guid>
            <category><![CDATA[speech]]></category>
            <category><![CDATA[speech-to-text-conversion]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Muhammad Asad]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 09:30:22 GMT</pubDate>
            <atom:updated>2025-11-22T09:30:22.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Speech-to-Text Conversion in iOS — using Speech framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1eY2fmcV8Bd0ZF9" /><figcaption>Photo by <a href="https://unsplash.com/@ricvath?utm_source=medium&amp;utm_medium=referral">Richard Horvath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wanted to convert speech to text in your iOS app? Using Apple’s <strong>Speech framework</strong>, we can capture what a user says, process it in real-time, and get the transcription. In this blog, I’ll walk you through an advanced implementation that handles <strong>real-world scenarios</strong>: detecting when the user starts speaking, handling silence, and stopping the engine efficiently before the default 1-minute timer runs out.</p><p>Let’s start with a function which would be called when user would tap on a mic icon (or whatever you have placed) in your code.</p><pre>@objc func micTapped() {<br>        // Prevent double start<br>        if isListening { return }<br>        isListening = true<br>        micIcon.tintColor = .red<br>        micIcon.isUserInteractionEnabled = false<br>        <br>        let recognizer = SFSpeechRecognizer(locale: Locale(identifier: &quot;en-US&quot;))<br>        let request = SFSpeechAudioBufferRecognitionRequest()<br>        let audioEngine = AVAudioEngine()<br>        let inputNode = audioEngine.inputNode<br>        <br>        var hasSpoken = false<br>        var speechTimer: Timer?</pre><p>We first checked if we are already listening to user voice or not using traditional boolean check, to prevent double start or app crashes, and then we change our UI accordingly.</p><p>SFSpeechRecognizer is a class which helps us to check authorization of recognition service and initiate the procedure. Here we have instantiated object with ‘en-US’ which is useful for creating recognizer attached with specific locale.</p><p>SFSpeechAudioBufferRecognitionRequest is the object that <strong>receives live audio buffers</strong> from the microphone and streams them to the recognizer. It allows real-time speech recognition and can <strong>report partial/full results</strong> as the user speaks. We use this request object to route audio from a device’s microphone to the speech recognizer.</p><p>AVAudioEngine is responsible for <strong>capturing audio from the device microphone</strong>. Its inputNode represents the input source (mic), and we attach a tap to send audio buffers to the recognition request.</p><p>hasSpoken is a boolean used to track if the user has actually started speaking, and speechTimer is a Timer that helps us <strong>detect pauses after speech</strong>, so we can stop the engine automatically when the user finishes talking instead of waiting for the default 1-minute limit.</p><pre>SFSpeechRecognizer.requestAuthorization { status in<br>            guard status == .authorized else {<br>                DispatchQueue.main.async {<br>                    self.showToast(message: &quot;Enable Speech Recognition in Settings&quot;)<br>                    self.resetMicUI()<br>                }<br>                return<br>            }<br>            <br>            do {<br>                let audioSession = AVAudioSession.sharedInstance()<br>                try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers)<br>                try audioSession.setActive(true, options: .notifyOthersOnDeactivation)<br>                <br>                self.recognitionTask?.cancel()<br>                self.recognitionTask = nil<br>                request.shouldReportPartialResults = true</pre><p>SFSpeechRecognizer.requestAuthorization is used to <strong>check if the user has granted permission</strong> for speech recognition. Without authorization, the recognizer cannot function, and we must inform the user to enable it in Settings. For this, you have to add a simple NSSpeechRecognitionUsageDescription key with a valid usage description in your <strong>info.plist</strong> file.</p><p>AVAudioSession manages the <strong>audio behavior of the app</strong>. By setting its category to .record and mode to .measurement, we ensure <strong>high-quality audio capture</strong> optimized for recognition. The .duckOthers option lowers the volume of other audio sources temporarily so the microphone input is clear.</p><p>try audioSession.setActive(true, options: .notifyOthersOnDeactivation) activates the session and ensures other audio sessions are properly notified when we stop recording.</p><pre>self.recognitionTask = recognizer?.recognitionTask(with: request) { result, error in<br>    if let result = result {<br>        let spokenText = result.bestTranscription.formattedString.trimmingCharacters(in: .whitespacesAndNewlines)<br>        <br>        // Cancel previous speech completion timer<br>        speechTimer?.invalidate()<br>        <br>        // Set a new timer that fires when speech seems complete<br>        speechTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { _ in<br>            hasSpoken = true<br>            self.silenceTimer?.invalidate() // Cancel the no-input timeout<br>            <br>            // Speech has paused for 1 second, consider it complete<br>            self.stopRecording(audioEngine: audioEngine, request: request, inputNode: inputNode)<br>            DispatchQueue.main.async {<br>                self.newSearchBar.text = spokenText<br>                self.performSearch()<br>                self.resetMicUI()<br>            }<br>        }<br>    }<br>    <br>    if error != nil {<br>        speechTimer?.invalidate()<br>        self.silenceTimer?.invalidate()<br>        self.stopRecording(audioEngine: audioEngine, request: request, inputNode: inputNode)<br>        DispatchQueue.main.async {<br>            self.resetMicUI()<br>        }<br>    }<br>}</pre><p>recognitionTask is the <strong>core function</strong> that continuously processes audio from the buffer and converts it into text. The closure provides result (partial or final transcription) and error.</p><p>result.bestTranscription.formattedString contains the <strong>current recognized text</strong>, which we trim to remove extra spaces.</p><p>speechTimer is used to detect when the user has paused or finished speaking. By setting it to fire 1 second after the last recognized word, we can <strong>stop the audio engine promptly</strong>, rather than waiting for the SpeechRecognizer’s default 1-minute listening period. (You can customize the time according to your needs). Essentially, this ensures a smoother user experience: as soon as the user stops speaking, the timer triggers, ending the recognition request and audio engine. This way, even short speeches are processed immediately without unnecessary delay.</p><pre>let originalFormat = inputNode.outputFormat(forBus: 0)<br>guard originalFormat.sampleRate &gt; 0 &amp;&amp; originalFormat.channelCount &gt; 0 else {<br>    DispatchQueue.main.async {<br>        self.showToast(message: &quot;Invalid audio format&quot;)<br>        self.resetMicUI()<br>    }<br>    return<br>}<br><br>inputNode.installTap(onBus: 0, bufferSize: 1024, format: originalFormat) { buffer, _ in<br>    request.append(buffer)<br>}<br><br>audioEngine.prepare()<br>try audioEngine.start()<br><br>DispatchQueue.main.async {<br>    self.showToast(message: &quot;Listening...&quot;)<br>}<br><br>// 7s silence timeout (only for no initial speech)<br>DispatchQueue.main.async {<br>    self.silenceTimer?.invalidate()<br>    self.silenceTimer = Timer.scheduledTimer(withTimeInterval: 7.0, repeats: false) { _ in<br>        if !hasSpoken {<br>            speechTimer?.invalidate()<br>            self.stopRecording(audioEngine: audioEngine, request: request, inputNode: inputNode)<br>            DispatchQueue.main.async {<br>                self.showToast(message: &quot;No input detected&quot;)<br>                self.resetMicUI()<br>            }<br>        }<br>    }<br>}</pre><p><strong>outputFormat(forBus: 0)</strong>: Even though we are using the <strong>microphone (input)</strong>, in AVAudioEngine, the inputNode exposes audio through its <strong>output</strong>. Think of it as a pipe: the microphone feeds audio into the engine, and the engine outputs it as a stream we can process. We ask for the format of this “output stream” to know <strong>how the audio data is structured</strong> (sample rate, number of channels).</p><p>A bus is like a <strong>channel or lane</strong> in the audio engine. Bus 0 is the primary input channel of the microphone. In more complex setups, audio nodes can have multiple buses for multiple streams, but here we just need the main one. In start we checked the sample rate and channel count. If both are zero, it means the audio stream is invalid, so we stop early to avoid crashes or garbage data.</p><p><strong>installTap(onBus:bufferSize:format:block:)</strong>: This attaches a <strong>listener to the audio stream</strong>. Every time a chunk of audio is captured (1024 frames in this case), it’s sent to our closure as buffer, which we append to the SFSpeechAudioBufferRecognitionRequest. This is how live audio flows into the recognizer.</p><p><strong>audioEngine.prepare() and </strong><strong>audioEngine.start()</strong>: Prepares internal resources and <strong>starts capturing audio</strong> from the mic. Until this is called, no audio is flowing.</p><p><strong>7-second silence timeout (</strong><strong>silenceTimer) </strong>handles the case when the user opens the mic but doesn’t speak. If no words are detected within 7 seconds (hasSpoken == false), we stop the engine and show a “No input detected” message. This prevents the app from waiting indefinitely and keeps the experience smooth.</p><pre>private func stopRecording(audioEngine: AVAudioEngine, request: SFSpeechAudioBufferRecognitionRequest, inputNode: AVAudioInputNode) {<br>    audioEngine.stop()<br>    request.endAudio()<br>    inputNode.removeTap(onBus: 0)<br>    <br>    // Cancel any ongoing recognition task<br>    self.recognitionTask?.cancel()<br>    self.recognitionTask = nil<br>    <br>    // Reset audio session<br>    try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)<br>}<br><br>private func resetMicUI() {<br>    self.micIcon.tintColor = .gray<br>    self.micIcon.isUserInteractionEnabled = true<br>    self.isListening = false<br>}</pre><p>These are helper functions which we have used in our function. <strong>audioEngine.stop() </strong>stops the audio engine immediately, halting microphone capture. This prevents audio from continuing to flow into the recognizer and <strong>request.endAudio()</strong> signals to the SFSpeechRecognizer that no more audio will be sent, allowing it to finalize transcription.</p><p><strong>inputNode.removeTap(onBus: 0)</strong>removes the tap we installed earlier. Without this, the node would continue sending audio buffers even if we stopped the engine. recognitionTask?.cancel() stops the current recognition session and frees up system resources.</p><p>We deactivate the AVAudioSession to restore normal audio behavior on the device. The option .notifyOthersOnDeactivation ensures other apps (music, calls) resume smoothly.</p><p>If you found this guide useful, give it a clap and follow me for more iOS development tips and Swift tricks. If you notice any mistakes or have suggestions, your feedback is highly appreciated, it helps me create better content!</p><h3>References</h3><ul><li><a href="https://developer.apple.com/documentation/speech/sfspeechrecognizer">SFSpeechRecognizer: Apple Documentation</a></li><li><a href="https://developer.apple.com/documentation/AVFAudio/AVAudioSession">AVAudioSession Documentation</a></li><li><a href="https://developer.apple.com/documentation/speech/sfspeechrecognitionrequest">SFSpeechRecognitionRequest: Apple Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d82aaf6e35d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Image Blur Detection — Power of Accelerate]]></title>
            <link>https://medium.com/@molvOps/ios-image-blur-detection-power-of-accelerate-721f1b9e850f?source=rss-46702fa1e2b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/721f1b9e850f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Muhammad Asad]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 08:22:26 GMT</pubDate>
            <atom:updated>2025-11-13T08:22:26.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Image Blur Detection — Power of Accelerate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gX-xWVBuBIot8pZQ" /><figcaption>Photo by <a href="https://unsplash.com/@mohamadaz?utm_source=medium&amp;utm_medium=referral">Mohammad Alizade</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many apps — from gallery cleaners to camera utilities — it’s often useful to <strong>identify and remove blurry photos</strong>. Blurry images take up storage and reduce user experience, especially in apps where image quality matters.</p><p>In this blog, I’ll walk you through <strong>two approaches</strong> to detect blurry images in iOS:</p><p>A <strong>basic Core Image (CIImage)</strong>–based approach, and <br>An optimized version using <strong>Apple’s Accelerate framework</strong> for high performance.</p><p>We’ll understand how simple image filtering and variance calculation can help determine sharpness — and why <strong>Laplacian </strong>filters play a key role here.</p><p>Before diving into performance optimizations, let’s first understand the <strong>core logic</strong> behind detecting blur in an image.<br>When an image is sharp, its <strong>edges are clearly defined</strong> — the transition between light and dark regions happens abruptly.<br>In contrast, a <strong>blurry image</strong> has <strong>soft, gradual transitions</strong>, meaning the pixel intensity changes are smoother and less pronounced.</p><p>To quantify this difference, we measure the <strong>edge strength</strong> within the image. If the overall edge strength is low, it indicates that fine details are missing — a clear sign of blur.<br>In other words, <strong>blur detection works by analyzing how quickly pixel intensities change</strong> across an image: the slower the change, the blurrier the photo. Here’s how we would achieve it:</p><pre>func isBlurry(_ image: UIImage) -&gt; Bool {<br>        guard let image = image.cgImage else {return false}<br>        let ciImage = CIImage(cgImage: image)<br>        <br>        // first apply grey filter and then apply convolution to make edges clear and then calculate laplace variance<br>        let greyFilter = CIFilter(name: &quot;CIPhotoEffectMono&quot;)<br>        greyFilter?.setValue(ciImage, forKey: kCIInputImageKey)<br>        guard let greyImage = greyFilter?.outputImage else {return false}<br>        <br>        let laplaceKernel : [CGFloat] = [<br>            0, 1, 0,<br>            1, -4, 1,<br>            0, 1, 0<br>        ]<br>        let convFilter = CIFilter(name: &quot;CIConvolution3X3&quot;)<br>        convFilter?.setValue(greyImage, forKey: kCIInputImageKey)<br>        convFilter?.setValue(CIVector(values: laplaceKernel, count: 9), forKey: &quot;inputWeights&quot;)<br>        convFilter?.setValue(0.0, forKey: &quot;inputBias&quot;)<br>        guard let lapCI = convFilter?.outputImage else {return false}<br>        <br>        let context = CIContext()<br>        guard let lapCG = context.createCGImage(lapCI, from: lapCI.extent) else { return false }<br>        let lapImage = UIImage(cgImage: lapCG)<br>        if let variance = lapImage.pixelVariance(), variance &lt; 100 {<br>            return true<br>        }<br>        <br>        return false<br>    }</pre><p><strong>1- Convert Image to GreyScale:<br></strong>As stated earlier, we don’t need color information to measure blur — just brightness variation is enough. Converting to grayscale simplifies computation and focuses on light intensity changes.</p><p><strong>2- Apply a Laplacian Filter (edge detector):<br></strong>The Laplacian operator highlights regions of rapid intensity change — in other words, <strong>edges</strong>. A sharp image will have many strong edges (large pixel intensity differences), while a blurred one will have softer transitions (lower differences). Look at this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*it3YkEj_bkux3iOxe3g2Bg.png" /></figure><p>As you can see the blurry images barely have any edges, while the focused ones have a lot of responses.</p><p><strong>3- Calculate the variance of Filtered Image:<br></strong>Once the edges are extracted, we compute the <strong>variance of pixel intensities</strong> — a statistical measure of how spread out the pixel values are. A high variance indicates strong edges, meaning the image is sharp and clear, while a low variance reflects weak edges, suggesting the image is blurry.</p><p>Based on this variance, we have built a simple function that returns a boolean result — true if the image is blurry (variance below a threshold), and false otherwise.</p><p>When iterating through all assets and processing each image with this function, the overall operation becomes significantly slower, negatively impacting the user experience.<br>Each image must first be converted to grayscale, then processed through a Laplacian kernel, and finally analyzed for variance — steps that collectively introduce <strong>heavy computational overhead</strong>.<br>Furthermore, <strong>Core Image</strong>, while convenient, can be slower due to its <strong>high memory footprint</strong> and <strong>internal GPU/CPU context switching</strong>, especially when applied repeatedly in loops.</p><p>To overcome this, we can use the <strong>Accelerate framework</strong> — Apple’s high-performance Framework designed specifically for <strong>vectorized and parallelized </strong>numerical operations.<br>Accelerate uses <strong>SIMD (Single Instruction, Multiple Data)</strong> instructions under the hood, allowing it to process thousands of pixel values in a single CPU cycle.<br>By replacing Core Image filters with <strong>vImage</strong> and <strong>vDSP</strong> functions, we offload the expensive per-pixel computations to optimized, low-level routines written in C and assembly, giving us a massive performance boost.</p><p>This not only reduces execution time dramatically but also minimizes memory allocations and context creation overhead.<br>In short, Accelerate allows us to perform <strong>Laplacian convolution and variance analysis directly on pixel buffers</strong>, keeping the logic identical to our earlier approach — just executed at native speed.</p><p>As a result, even when scanning <strong>hundreds or thousands of images</strong>, the operation remains responsive and efficient, making it suitable for real-world, production-grade apps. Here is the complete implementation:</p><pre>func isBlurryAccelerate(_ image: UIImage) -&gt; Bool {<br>        guard let cgImage = image.cgImage else { return false }<br>        <br>        let width = cgImage.width<br>        let height = cgImage.height<br>        let colorSpace = CGColorSpaceCreateDeviceGray()<br>        var bitmapData = [UInt8](repeating: 0, count: width * height)<br>        <br>        guard let context = CGContext(data: &amp;bitmapData, width: width, height: height,<br>                                      bitsPerComponent: 8, bytesPerRow: width,<br>                                      space: colorSpace, bitmapInfo: 0) else { return false }<br>        context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))<br>        <br>        var floatPixels = [Float](repeating: 0, count: width * height)<br>        vDSP_vfltu8(bitmapData, 1, &amp;floatPixels, 1, vDSP_Length(width * height))<br>        <br>        // Apply Laplacian Filter<br>        let kernel: [Float] = [0, 1, 0, 1, -4, 1, 0, 1, 0]<br>        var result = [Float](repeating: 0, count: width * height)<br>        <br>        floatPixels.withUnsafeMutableBytes { srcPtr in<br>            result.withUnsafeMutableBytes { dstPtr in<br>                var srcBuffer = vImage_Buffer(data: srcPtr.baseAddress!, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: width * 4)<br>                var dstBuffer = vImage_Buffer(data: dstPtr.baseAddress!, height: vImagePixelCount(height), width: vImagePixelCount(width), rowBytes: width * 4)<br>                <br>                vImageConvolve_PlanarF(&amp;srcBuffer, &amp;dstBuffer, nil, 0, 0, kernel, 3, 3, 0, vImage_Flags(kvImageEdgeExtend))<br>            }<br>        }<br>        <br>        var mean: Float = 0<br>        var stdDev: Float = 0<br>        vDSP_normalize(result, 1, nil, 1, &amp;mean, &amp;stdDev, vDSP_Length(result.count))<br>        <br>        return stdDev &lt; 10.0 // Adjust threshold as needed<br>    }</pre><p><strong>Applying GreyScale Filter:<br></strong>In the Accelerate-based implementation, we first extract the <strong>raw pixel data</strong> of the image into a grayscale buffer. The bitmapData array is a flat array of UInt8 values representing the brightness of each pixel. By creating a CGContext with this buffer, we can draw the image directly into it, converting it into a grayscale format without the overhead of Core Image filters.</p><p>This step ensures that the subsequent computations operate on a simple, contiguous memory layout, which is much faster for vectorized processing.</p><p><strong>Conversion to Float:<br></strong>Next, we convert this byte data into <strong>floating-point </strong>numbers using vDSP_vfltu8. The floatPixels array now contains Float representations of the pixel intensities. This conversion is necessary because Accelerate’s vImage and vDSP routines operate efficiently on <strong>floating-point arrays</strong>, enabling <strong>vectorized math </strong>and <strong>SIMD acceleration</strong> across the entire image.</p><p>Each pixel value from 0 to 255 is cast to a Float so that mathematical operations like convolution and variance calculation can be performed precisely and efficiently.</p><p><strong>Applying Laplace Filter:<br></strong>The core of blur detection is the <strong>Laplacian convolution</strong>, which highlights edges in the image. We perform this using vImageConvolve_PlanarF, passing in the source buffer, destination buffer, the Laplacian kernel, and the kernel size. This function applies the convolution across the entire image in a highly optimized way, leveraging Accelerate’s low-level routines for fast memory access and SIMD operations.</p><p>The kvImageEdgeExtend flag ensures that the edges of the image are handled gracefully by extending border values, preventing artifacts that could skew the variance calculation.</p><p><strong>Calculating Variance:<br></strong>After convolution, we calculate the <strong>mean and standard deviation</strong> of the resulting pixel values using vDSP_normalize. This function efficiently computes the distribution of edge strengths across the image. The standard deviation here acts as a measure of <strong>edge variability</strong>: a sharp image will have high variability because edges are pronounced, while a blurry image will have low variability due to smoothed edges.</p><p>We can then set a <strong>threshold on the standard deviation</strong> — for example, if stdDev &lt; 10.0, the image is considered blurry. Using standard deviation rather than variance or other measures provides a normalized scale that is robust to different image sizes and intensity ranges, making the method reliable across a variety of images.</p><p><strong>Results:</strong></p><p>By using Accelerate for these operations, we significantly reduce the computational overhead compared to Core Image. The image is processed directly in memory buffers, all pixel-level computations are vectorized, and expensive loops are executed in optimized native code rather than Swift. This allows the function to handle <strong>hundreds of images efficiently</strong>, making it suitable for production applications that need responsive and scalable blur detection.</p><p><strong>Optimization Tips:</strong></p><ul><li><strong>Downscale large images</strong> before processing (e.g., 256–512px on the longest side) to preserve edges while reducing computation.</li><li><strong>Reuse memory buffers</strong> across multiple images to minimize allocations and runtime overhead.</li><li><strong>Run processing off the main thread</strong> to maintain UI responsiveness, especially with large photo libraries.</li></ul><p><strong>Cautions:</strong></p><ul><li><strong>Threshold tuning:</strong> The standard deviation threshold may need adjustment depending on image content, lighting, or dataset. A fixed value may not work for all cases.</li><li><strong>Edge cases:</strong> Extreme rotations, heavy noise, or low-light images can produce misleading results. Consider combining with additional heuristics for higher accuracy.</li><li><strong>Memory safety:</strong> Ensure buffers and vImage operations are correctly sized and aligned to avoid crashes or corrupted results.</li></ul><p>If you found this guide useful, <strong>give it a clap and follow me</strong> for more iOS development tips and Swift performance tricks.<br>And if you notice any mistakes or have suggestions, your <strong>feedback is greatly appreciated</strong> — it helps me improve and deliver better content!</p><p><strong>References:<br></strong><a href="https://developer.apple.com/documentation/accelerate">Apple Accelerate Framework</a><br><a href="https://getstream.io/blog/accelerate-framework/">Accelerate Working UnderHood</a><br><a href="https://developer.apple.com/documentation/accelerate/vimage">vImage Convolution Guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721f1b9e850f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Image Similarity Detection —  Implemen]]></title>
            <link>https://medium.com/@molvOps/ios-image-similarity-detection-implemen-9eccfca2838d?source=rss-46702fa1e2b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eccfca2838d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Asad]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 07:48:16 GMT</pubDate>
            <atom:updated>2025-11-06T07:48:16.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Image Similarity Detection — Implementing pHash in Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xvO3J2wotEpffW7k" /><figcaption>Photo by <a href="https://unsplash.com/@tomterifx?utm_source=medium&amp;utm_medium=referral">thom masat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever noticed multiple photos in your iPhone gallery that look almost identical — maybe taken a few seconds apart or from slightly different angles? I recently built a feature for iOS that automatically detects such <em>visually similar images</em> using <strong>Perceptual Hashing (pHash)</strong>.</p><p>In this post, I’ll walk you through how I implemented image similarity detection in Swift — from fetching photos to comparing their perceptual hashes, which would eventually help us in finding similar images!</p><p><strong>1- Fetching User Photos</strong></p><p>Before comparing images, we first need access to all the photos stored in the user’s gallery. Using the <strong>Photos framework (PHAsset)</strong>, we can fetch all image assets sorted by their creation date.</p><pre>func fetchUserImages(completion: @escaping ([PHAsset]) -&gt; Void) {<br>    var fetchedAssets: [PHAsset] = []<br>    <br>    let options = PHFetchOptions()<br>    options.sortDescriptors = [NSSortDescriptor(key: &quot;creationDate&quot;, ascending: false)]<br>    options.predicate = NSPredicate(format: &quot;mediaType == %d&quot;, PHAssetMediaType.image.rawValue)<br>    <br>    let result = PHAsset.fetchAssets(with: .image, options: options)<br>    result.enumerateObjects { asset, _, _ in<br>        fetchedAssets.append(asset)<br>    }<br>    <br>    self.allAssets = fetchedAssets<br>    completion(fetchedAssets)<br>}</pre><p>Here, we fetched the user’s images from Photos library using <strong>PHAsset’s </strong>method <strong>PHFetchOptions </strong>which lets us filter and sort the assets (in this case, only images), and stored all fetched assets into an array and return them asynchronously via a completion handler.</p><p><strong>2. Detecting Similar Images with Perceptual Hashing</strong></p><p>Once we have all the user’s images fetched, the next step is to find which ones look visually similar. To do that, we’ll use a technique called <a href="https://apiumhub.com/tech-blog-barcelona/introduction-perceptual-hashes-measuring-similarity/"><strong>Perceptual Hashing</strong></a><strong> (pHash)</strong>.</p><p>Perceptual Hashing is a type of<strong> content-based hashing algorithm</strong> that generates a unique numerical fingerprint for an image — not by comparing raw pixels, but by analyzing its <strong>visual structure, patterns, and brightness</strong>. This allows us to detect similarity between images that may not be identical pixel by pixel but still look the same to the human eye.</p><p>In our approach, we loop through each fetched image, calculate its <strong>pHash</strong>, and then compare it with the hashes of already-processed images using the <strong>Hamming distance</strong> — a metric that counts the number of differing bits between two binary strings of equal length.</p><p>If the Hamming distance is below a certain threshold (for example, ≤ 5), we consider those images <strong>visually similar</strong> and group them together.</p><pre>func categorizeForSimilarity(_ assets: [PHAsset]) {<br>    let similarThreshold = 5<br>    <br>    for asset in assets {<br>        let options = PHImageRequestOptions()<br>        options.isSynchronous = true<br>        var assetImage: UIImage?<br>        <br>        PHImageManager.default().requestImage(<br>            for: asset,<br>            targetSize: CGSize(width: 100, height: 100),<br>            contentMode: .aspectFit,<br>            options: options<br>        ) { image, _ in<br>            assetImage = image<br>        }<br>        <br>        guard let image = assetImage else { continue }<br>        guard let hash = self.pHash(image) else { continue } // Core function<br>        <br>        if let existingKey = self.similarDict.keys.first(where: { self.hammingDistance(hash, $0) &lt;= similarThreshold }) {<br>            self.similarDict[existingKey, default: []].append(asset)<br>        } else {<br>            self.similarDict[hash] = [asset]<br>        }<br>    }<br>    <br>    // Keep only groups with more than one similar image<br>    self.similarDict = self.similarDict.filter { $0.value.count &gt; 1 }<br>}</pre><ul><li><strong>targetSize: CGSize(width: 100, height: 100)</strong><br>We don’t need full-resolution photos to find similarities. Downscaling reduces memory usage and speeds up hashing.</li><li><strong>options.isSynchronous = true</strong><br>Ensures that each image is fetched before moving to the next one. This keeps logic simple for our demo, but in production, run this on a background thread to avoid blocking the UI.</li><li><strong>similarThreshold = 5</strong><br>The threshold controls how “close” two images need to be to be considered similar. A <strong>lower value</strong> makes it stricter (only nearly identical images match), while a <strong>higher value</strong> makes it more tolerant.</li><li><strong>Grouping logic:</strong><br>For each new image, we check if any existing hash in similarDict is close enough. If yes, we group them together, otherwise, it becomes the first image of a new group.</li></ul><p>Then comes the core logic which lies in calculating the Perceptual Hashes of images. Here is the function:</p><pre>func pHash(_ image: UIImage) -&gt; UInt64? {<br>    let size = CGSize(width: 8, height: 8)<br>    guard let resized = image.resized(to: size),<br>          let gray = resized.toGrayscale(), // extension function<br>          let pixels = gray.pixelValues() else { return nil } // extension function<br>    <br>    let avg = pixels.reduce(0, { $0 + UInt64($1) }) / UInt64(pixels.count)<br>    var hash: UInt64 = 0<br>    for (i, p) in pixels.enumerated() {<br>        if UInt64(p) &gt; avg {<br>            hash |= (1 &lt;&lt; UInt64(i))<br>        }<br>    }<br>    return hash<br>}</pre><ul><li>We resize the image to <strong>8×8 pixels</strong>. This drastically reduces the data while keeping the broad visual structure. (An 8×8 grid gives us exactly <strong>64 pixels</strong>, which fits perfectly in a UInt64.)</li><li>The image is converted to <strong>grayscale</strong> so color differences don’t affect similarity.</li><li>We compute the <strong>average brightness</strong> of the 64 pixels. Each pixel brighter than this average gets a 1, otherwise a 0. This gives us a 64-bit binary pattern — the image’s <strong>perceptual fingerprint</strong>.</li><li>pixels.enumerated() gives us both the <strong>index (</strong><strong>i)</strong> and <strong>brightness value (</strong><strong>p)</strong> of each pixel.</li><li>For every pixel, if the pixel is <strong>brighter than the average</strong>, we set bit <strong>i</strong> to 1, otherwise, that bit remains 0.</li></ul><p><strong>Hamming Distance Extension:</strong></p><pre>func hammingDistance(_ a: UInt64, _ b: UInt64) -&gt; Int {<br>    return (a ^ b).nonzeroBitCount<br>}</pre><ul><li>XOR (^) highlights which bits differ between two hashes.</li><li>nonzeroBitCount quickly counts the differing bits.</li><li>A smaller number means the images are more visually alike.<br>For instance: <br> Distance 0–2: likely identical<br> Distance 3–5: visually similar<br> Distance &gt;5: likely different</li></ul><p><strong>Greyscale Conversion Extension:</strong></p><pre>func toGrayscale() -&gt; UIImage? {<br>    guard let cgImage = self.cgImage else { return nil }<br>    let ciImage = CIImage(cgImage: cgImage)<br>    let filter = CIFilter(name: &quot;CIPhotoEffectMono&quot;)<br>    filter?.setValue(ciImage, forKey: kCIInputImageKey)<br>    guard let output = filter?.outputImage else { return nil }<br>    let context = CIContext()<br>    guard let outCG = context.createCGImage(output, from: output.extent) else { return nil }<br>    return UIImage(cgImage: outCG)<br>}</pre><p>Here we simply apply CIPhotoEffectMono ( i.e. greyscale filter) to our image and then return it.</p><p><strong>pixelValues Calculation Function:</strong></p><pre>func pixelValues() -&gt; [UInt8]? {<br>    guard let cgImage = self.cgImage else { return nil }<br>    guard let data = cgImage.dataProvider?.data else { return nil }<br>    let ptr = CFDataGetBytePtr(data)<br>    let length = CFDataGetLength(data)<br>    guard length &gt; 0 else {return nil}<br>        <br>    var pixels: [UInt8] = []<br>    for i in stride(from: 0, to: length, by: 4) {<br>        pixels.append(ptr![i])<br>      }<br>      return pixels<br>  }</pre><p>Each pixel in a CGImage is represented by 4 bytes — <strong>Red, Green, Blue, and Alpha (RGBA)</strong>.<br>Here, we loop through the raw pixel buffer, stepping by 4 bytes at a time, and take the <strong>first byte</strong> (the red channel, which carries brightness in a grayscale image).</p><p>This gives us an array like [120, 135, 90, 200, ...], representing the brightness of each pixel.<br>These values are then used in the pHash function to calculate the <strong>average brightness</strong> and determine which bits to set in the 64-bit perceptual hash.</p><p><strong>Results:</strong></p><p>Here are the results which i got after implementing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*nf1WoP731KxjGeCLH9jGPg.png" /></figure><p><strong>Constraints:</strong></p><p>After implementation, you might notice that some <strong>visually different images</strong> are still grouped together. This happens because <strong>perceptual hashing </strong>has its own limitations, such as:</p><p>1- pHash captures global structure, not details. Two very different images that share similar brightness patterns (like light backgrounds or centered objects) can end up with similar hashes.</p><p>2- If the same scene is captured under slightly different lighting, the average brightness changes, which can alter many bits in the hash — sometimes enough to make similar images look “different,” or vice versa.</p><p>3- The method groups an image into the first “close-enough” cluster it finds. This works fine for small sets, but can misclassify edge cases when multiple groups have overlapping similarity ranges.</p><p>4- The similarity threshold (&lt;= 5) is a rough heuristic — too low and you miss similar images, too high and you include unrelated ones. The ideal value depends heavily on the dataset and lighting consistency.</p><p>But in the end, I achieved around <strong>95% accuracy</strong>, which is quite impressive — especially considering that it doesn’t require integrating or running any <strong>pre-trained machine-learning model</strong> inside the app.</p><p><strong>Conclusion:</strong></p><p>While this method works great for small data set, there are a few ways to make it faster and more memory-efficient for large-scale use:</p><p>1- Run hashing operations on a background thread using DispatchQueue.global() to prevent blocking the UI.</p><p>2- Apple’s <strong>Accelerate</strong> framework (specifically vDSP) can perform image resizing, grayscale conversion, and average calculations <strong>much faster</strong> using SIMD and vectorized operations. Replacing pixel-by-pixel loops with Accelerate functions can dramatically reduce CPU time for large photo sets.</p><p>3- Cache computed hashes using UserDefaults or Core Data so you don’t reprocess the same photos every time the app runs.</p><p><strong>References &amp; Further Reading</strong></p><p><a href="https://developer.apple.com/documentation/photokit">Apple Developer Documentation — PhotoKit</a><br><a href="https://apiumhub.com/tech-blog-barcelona/introduction-perceptual-hashes-measuring-similarity/">Perceptual Hashing and its Working</a><br><a href="https://developer.apple.com/documentation/accelerate">Apple Developer Documentation — Accelerate</a></p><p>If you found this post helpful, feel free to <strong>leave a clap and follow me</strong> for more iOS and Swift development content.<br>And if you spot any mistakes or have suggestions, I’d truly appreciate your feedback — it helps me learn and improve!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eccfca2838d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>