Edge Alchemy: Transforming Images through Sobel, Prewitt, and Roberts

Picture a world where light and dark play a secret game, creating hidden shapes in pictures. Imagine that images aren't just pictures, but have tales waiting to be uncovered. This is the realm of edge detection, where special tools turn pixel puzzles into clear stories.

Think of these tools as magicians of pixels. They use their tricks to find edges hiding in pictures. These tools are like the artists who turn blobs into beautiful scenes. There's Sobel, Prewitt, and Roberts—names that sound like characters from a fairy tale. But they are the real heroes who make hidden lines and shapes appear in images.

0:00
/

Imagine how a storyteller weaves tales; these tools do the same with pixels. Sobel adds details like brushstrokes of light and dark, while Prewitt whispers which way the edges go. Roberts, like a gentle artist, uncovers the tiniest details in images.

Are you ready to see what's hidden? Get ready to go from quiet pixels to loud stories. Step into the world of pixel magic, where tools make the invisible visible. Welcome to "Edge Alchemy: Pixel Magic with Sobel, Prewitt, and Roberts." Let the magic begin.

2. The Alchemical Trio: Sobel, Prewitt, and Roberts

Think of these filters as special glasses that help us see edges in images. Each filter has its own way of spotting edges, like three different detectives solving a mystery.

  1. Sobel Filter: This filter pays attention to how colors change from one pixel to another. It's like looking at a painting and noticing where the colors suddenly get brighter or darker. Sobel helps us see the bold outlines in pictures.
  2. Prewitt Filter: Imagine this filter as a detective who not only spots changes in color but also knows which direction they go. It's like figuring out if a line in a drawing is slanting left or right. Prewitt is great at showing the directions of edges.
  3. Roberts Filter: Think of this filter as a magnifying glass that zooms in on small changes in color. It's like noticing tiny details in a photo that might be easy to miss. Roberts helps us find the small, delicate edges.

Just as skilled alchemists, each filter wields a distinct art, guiding us to unlock the enigmas concealed within the pixels.

3. The Art of Transformation: Understanding Edge Detection

In the alchemical laboratory of image processing, understanding the essence of edge detection is akin to deciphering the mystical language of transformation. Just as alchemists sought the philosopher's stone to transmute substances, edge detection aims to transmute pixel values into the realm of edges—lines that define shapes and stories within images.

1. The Alchemical Ingredients: Gradients and Convolution: At the heart of this magical process lie two essential ingredients: gradients and convolution. Gradients act like the alchemical energies that highlight changes in color intensity. Convolution, on the other hand, mimics the process of combining ingredients—a precise technique where filters sweep across pixels, extracting hidden patterns and revealing their latent significance.  

Gradient Magnitudes in the X and Y Directions After Applying Sobel Operator

2. The Elixir of Edge Enhancement: Imagine convolution as a mystic elixir being poured over the image canvas. Just as an alchemical mixture purifies and enhances, convolution sharpens edges, intensifying their presence. Gradients, acting as the ethereal catalysts, emphasize areas of significant change, guiding the transformation from pixel to edge.

Left: Original Image, Right: Combined Gradient Magnitudes in the X and Y Directions After Applying the Sobel Operator

3. The Alchemist's Outcome: Unveiling Edges: The culmination of this digital alchemy is the revelation of edges—those elusive boundaries that shape objects and contours. In the alchemist's pursuit of clarity, edge detection uncloaks these hidden narratives, allowing us to see the world of images with newfound insight.

Detected Edges After Applying the Sobel Operator

As we delve into the alchemical intricacies of edge detection, remember that just as an alchemist unveils the hidden truths of substances, edge detection uncovers the latent truths concealed within pixels. It's a blend of mathematics and magic that brings forth the art of transformation—an art that renders pixels into lines, shapes, and stories that breathe life into images.

🧠
You could try the code in your on computer, get it in Github

4. Sobel Sorcery: Enhancing Edges with Gradients

The Sobel operator is like a mystical seer for images. It peers into each pixel's soul, talking to its neighboring pixels. It calculates how much each pixel's neighbors differ from it, both left-right and up-down. When the differences are great, it suggests that an edge might be lurking there. This mystical operator repeats this incantation for every pixel, conjuring up a map of where the edges might be hiding in the picture's secret realms.

To employ the Sobel operator on an image, we utilize two kernels: the Y kernel and the X kernel, both of which will be elucidated in the subsequent explanation.

The Y kernel of the Sobel operator is a 3x3 matrix that is used to compute the vertical gradient of an image. It's designed to detect changes in pixel intensities in the vertical direction. Here's the Y kernel for the Sobel operator:

Left: Sobel Y Convolution Right: Vertical Gradient after Applying the Kernel

The X kernel of the Sobel operator is a 3x3 matrix that is used to compute the horizontal gradient of an image. It's designed to detect changes in pixel intensities in the horizontal direction. Here's the X kernel for the Sobel operator:

Left: Sobel X Convolution Right: Horizontal Gradient after Applying the Kernel

Then, these two gradients come together like old friends meeting again after years apart. They join forces, and something magical happens – we calculate how strong their connection is (magnitude). This calculation reveals the edges of the image, showing us where things change a lot from one pixel to the next. It's like a secret code that reveals the hidden lines and shapes in the picture.

Left: Merged Gradients Right: Detected Edges After Magnitude Calculation

The arcane script to unravel the mysteries of edges through the art of Sobel lies just beneath these words.

Image sobel(Image& img) {
    Image filtered(img.height, img.width, img.channels);

    // Define Sobel kernels
    int sobelX[3][3] = {{-1,  0,  1}, {-2, 0, 2}, {-1, 0, 1}};
    int sobelY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}};

    // Apply Sobel operator to each pixel
    for (int y = 1; y < img.height - 1; ++y) {
        for (int x = 1; x < img.width - 1; ++x) {

            Pixel gradX, gradY;
            int rr, cc;
            
            for (int i = 0; i < 3; ++i) {
                for (int j = 0; j < 3; ++j) {
                    rr =  y + i - 1; cc = x + j - 1;
                    gradX += img.at(rr, cc) * sobelX[i][j];
                    gradY += img.at(rr, cc) * sobelY[i][j];
                }
            }

            filtered.at(y, x) = sqrt( gradX.avg() * gradX.avg() + gradY.avg() * gradY.avg() );
        }
    }
    return filtered;
}

5. Prewitt's Directional Elegance: Edge Sensitivity

The Prewitt operator acts like a curious explorer in the world of pictures. It looks at each pixel and talks to its nearby friends. It figures out how different a pixel's neighbors are from it, both next to it and above and below it. When these differences are big, it hints at the possibility of an edge being present. This clever operator performs this action for every pixel, creating a sort of treasure map that points to where the edges might be concealed in the image's hidden corners.

To employ the Prewitt operator on an image, we utilize two kernels: the Y kernel and the X kernel, both of which will be elucidated in the subsequent explanation.

The Y kernel of the Prewitt operator is a 3x3 matrix that is used to compute the vertical gradient of an image. It's designed to detect changes in pixel intensities in the vertical direction. Here's the Y kernel for the Prewitt operator:

Left: Prewitt Y Convolution Right: Vertical Gradient after Applying the Kernel

The X kernel of the Prewitt operator is a 3x3 matrix that is used to compute the horizontal gradient of an image. It's designed to detect changes in pixel intensities in the horizontal direction. Here's the X kernel for the Prewitt operator:

Then, like two streams flowing from distant mountains, these gradients converge once more after years of winding paths apart. They intertwine their currents, and in this merging of waters, a kind of alchemy takes place – we measure the intensity of their connection (magnitude). This calculation unveils the contours of the image's boundaries, illuminating where transformations from one pixel to the next are most pronounced. It's akin to deciphering a secret script that unveils the veiled contours and hidden forms within the picture's canvas.

Left: Merged Gradients Right: Detected Edges After Magnitude Calculation

The elusive key to unlock the riddles of edges, crafted through the craft of Prewitt, dwells just below the surface of these sentences, waiting to be discovered.

Image prewitt(Image& img) {
    Image filtered(img.height, img.width, img.channels);

    // Define Prewitt kernels
    int prewittX[3][3] = {{-1,  0,  1}, {-2, 0, 2}, {-1, 0, 1}};
    int prewittY[3][3] = {{-1, -2, -1}, { 0, 0, 0}, { 1, 2, 1}};

    // Apply Prewitt operator to each pixel
    for (int y = 1; y < img.height - 1; ++y) {
        for (int x = 1; x < img.width - 1; ++x) {

            Pixel gradX, gradY;
            int rr, cc;
            
            for (int i = 0; i < 3; ++i) {
                for (int j = 0; j < 3; ++j) {
                    rr =  y + i - 1; cc = x + j - 1;
                    gradX += img.at(rr, cc) * prewittX[i][j];
                    gradY += img.at(rr, cc) * prewittY[i][j];
                }
            }

            filtered.at(y, x) = sqrt( gradX.avg() * gradX.avg() + gradY.avg() * gradY.avg() );
        }
    }
    return filtered;
}

6. Roberts Revealed: Unearthing Fine Edges

The Roberts operator assumes the role of an inquisitive wanderer within the realm of images. It observes each pixel and engages in conversation with its neighboring companions. It deciphers the variations between a pixel and its neighboring counterparts, those adjacent as well as those above and below. When these variances are substantial, it offers a subtle suggestion of an imminent edge. This astute operator undertakes this endeavor pixel by pixel, weaving together a parchment akin to a map of hidden treasures, marking out the enigmatic locations where the image's concealed edges might lie.

To employ the Roberts operator on an image, we utilize two kernels: the Y kernel and the X kernel, both of which will be elucidated in the subsequent explanation.

The Y kernel of the Roberts operator is a 2x2 matrix that is used to compute the vertical gradient of an image. It's designed to detect changes in pixel intensities in the vertical direction. Here's the Y kernel for the Roberts operator:

Left: Prewitt Y Convolution Right: Vertical Gradient after Applying the Kernel

The X kernel of the Roberts operator is a 2x2 matrix that is used to compute the horizontal gradient of an image. It's designed to detect changes in pixel intensities in the horizontal direction. Here's the X kernel for the Roberts operator:

Then, akin to celestial bodies drawn by cosmic forces, these gradients find each other anew after traversing separate celestial paths for epochs. They intertwine their luminous trails, and in this celestial dance, an enchanting fusion occurs – we gauge the fervor of their embrace (magnitude). This act of measurement unveils the very topography of the image's borders, casting light on regions where shifts from one pixel to the next are vividly expressed. It's akin to interpreting the hushed language of ancient scripts, unveiling the concealed tales of shapes and lines etched within the canvas of the picture.

The enigmatic lantern that illuminates the mysteries of edges, handcrafted by the skilled hands of Prewitt, lies beneath the layers of these words, ready to cast its revealing glow.

Image roberts(Image& img) {
    Image filtered(img.height, img.width, img.channels);

    // Define Roberts kernels
    int robertsX[2][2] = { { 1, 0 }, { 0, -1 }};
    int robertsY[2][2] = { { 0, 1 }, { -1, 0 }};

    // Apply Roberts operator to each pixel
    for (int y = 1; y < img.height - 1; ++y) {
        for (int x = 1; x < img.width - 1; ++x) {

            Pixel gradX, gradY;
            int rr, cc;

            for (int i = 0; i < 2; ++i) {
                for (int j = 0; j < 2; ++j) {
                    rr =  y + i - 1; cc = x + j - 1;
                    gradX += img.at(rr, cc) * robertsX[i][j];
                    gradY += img.at(rr, cc) * robertsY[i][j];
                }
            }

            filtered.at(y, x) = sqrt( gradX.avg() * gradX.avg() + gradY.avg() * gradY.avg() );
        }
    }

    return filtered;
}

7. Alchemical Convergence: Comparative Analysis

We're exploring Sobel, Prewitt, and Roberts methods to see how well they work. By doing this, we can figure out which one is good for different types of pictures. Let's dive into this exploration of edge detection and see how these techniques measure up!

Fine Detail Mastery: Prewitt's Edge Detection Advantage

Prewitt's edge detection is like having a magnifying glass for delicate patterns. Imagine you're looking at a detailed drawing with thin lines – Prewitt can zoom in on these small lines and make them stand out. This makes Prewitt a great choice for images with intricate, delicate structures like a complex network of branches on a tree.

Roberts
Prewitt
Sobel

Vertical and Horizontal Precision: Sobel's Dominance in Structured Scenes

Sobel's edge detection is like a ruler that's really good at measuring straight lines. Picture a tall building with strong vertical lines – Sobel can precisely spot these up-and-down lines without being distracted by slanted or subtle details. It's like having a tool that's tailor-made for buildings and structured scenes.

Roberts
Prewitt
Sobel

Diagonal Edge Excellence: Roberts' Proficiency in Angular Patterns

Roberts' edge detection is like a compass for finding diagonal paths. Think of a picture with a sloping pattern, like a staircase – Roberts is a master at catching these tilted edges. It's like having a guide that's exceptional at spotting diagonal lines, which can be trickier for other methods like Sobel and Prewitt.

Roberts
Prewitt
Sobel

8. Applying the Elixir: Practical Use Cases

  • Medical Imaging: Enhancing diagnostic accuracy through edge detection.
  • Computer Vision: Object recognition and tracking in complex scenes.
  • Art Restoration: Preserving and revitalizing historical artworks.
  • Industrial Quality Control: Ensuring precision and consistency in manufacturing.

9. Conclusion: The Eloquent Poesy of Edge Alchemy

In this journey through edge detection—a place where pixels turn into stories—we've explored Sobel, Prewitt, and Roberts. It's like a meeting of math and magic. These filters work like special potions, unveiling the secrets in images. They bring out hidden tales in how pixels change from one to the next.

From Sobel's bold strokes that carve contours to Prewitt's compass that guides us along pathways, and Roberts' delicate whispers that bring forth nuances, we've delved into the alchemical artistry of edge detection. These filters, like alchemists of old, have summoned order from chaos, making the invisible visible.

Yet, this journey is not merely about the past and present; it's a gateway to the future. As technology advances, we stand at the precipice of uncharted territories. Just as alchemists dreamed of transmutation, edge detection's future promises innovations that blend machine learning, hybrid techniques, and creative insight. The human-machine symphony will amplify the magic, as pixels become not just images but the foundation of narratives that unfold before our eyes.