AlgoPlus v0.1.0
Loading...
Searching...
No Matches
sobel_operator.h
1#ifndef SOBEL_OPERATOR_H
2#define SOBEL_OPERATOR_H
3
4#ifdef __cplusplus
5#include <cassert>
6#include <cmath>
7#include <iostream>
8#include <utility>
9#include <vector>
10#include "../image.h"
11#endif
12
18namespace sobel {
24inline std::pair<std::vector<std::vector<int32_t>>, std::vector<std::vector<int32_t>>> kernel() {
25 std::vector<std::vector<int32_t>> G_x = {{1, 0, -1}, {2, 0, -2}, {1, 0, -1}};
26 std::vector<std::vector<int32_t>> G_y = {{1, 2, 1}, {0, 0, 0}, {-1, -2, -1}};
27 return std::make_pair(G_x, G_y);
28}
29
35inline std::vector<std::vector<int32_t>> square(const std::vector<std::vector<int32_t>>& G) {
36 int height = G.size();
37 int width = G[0].size();
38 std::vector<std::vector<int32_t>> res_img(height, std::vector<int32_t>(width));
39 for (int i = 0; i < height; i++) {
40 for (int j = 0; j < width; j++) {
41 res_img[i][j] = sqrt(G[i][j]);
42 }
43 }
44 return res_img;
45}
46
52inline std::vector<std::vector<int32_t>> Sobel(const std::vector<std::vector<int32_t>>& image) {
53 Image img(image);
54
55 std::pair<std::vector<std::vector<int32_t>>, std::vector<std::vector<int32_t>>> kernels =
56 kernel();
57 std::vector<std::vector<int32_t>> k1 = kernels.first;
58 std::vector<std::vector<int32_t>> k2 = kernels.second;
59
60 Image G_x(img.apply_filter2d(k1));
61 Image G_y(img.apply_filter2d(k2));
62
63 G_x = G_x.mul(G_x);
64 G_y = G_y.mul(G_y);
65
66 Image G(G_x); // G = G_x^2
67 G = G.add(G_y); // G += G_y^2
68
69 return square(G.get_2d_array()); // result is: G = sqrt(G_x^2 + G_y^2)
70}
71} // namespace sobel
72
73#endif
Definition image.h:13
Image add(const T img2) const
add function adds the img2 to img
Definition image.h:121
std::vector< std::vector< int32_t > > get_2d_array() const
get_2d_array function
Definition image.h:63
Image mul(const T img2) const
mul function multiplies the img2 to img
Definition image.h:179
Image apply_filter2d(std::vector< std::vector< T > > &filter) const
apply_filter2d function
Definition image.h:207
Sobel operator is used for edge detection. It creates 2 3x3 arrays G_x and G_y and apply them to an i...
Definition sobel_operator.h:18
std::pair< std::vector< std::vector< int32_t > >, std::vector< std::vector< int32_t > > > kernel()
Definition sobel_operator.h:24
std::vector< std::vector< int32_t > > square(const std::vector< std::vector< int32_t > > &G)
square function
Definition sobel_operator.h:35
std::vector< std::vector< int32_t > > Sobel(const std::vector< std::vector< int32_t > > &image)
Sobel apply function.
Definition sobel_operator.h:52