-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
answer_16.cpp
92 lines (75 loc) · 2.15 KB
/
answer_16.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <math.h>
// BGR -> Gray
cv::Mat BGR2GRAY(cv::Mat img){
// get height and width
int width = img.cols;
int height = img.rows;
// prepare output
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);
// each y, x
for (int y = 0; y < height; y++){
for (int x = 0; x < width; x++){
// BGR -> Gray
out.at<uchar>(y, x) = 0.2126 * (float)img.at<cv::Vec3b>(y, x)[2] \
+ 0.7152 * (float)img.at<cv::Vec3b>(y, x)[1] \
+ 0.0722 * (float)img.at<cv::Vec3b>(y, x)[0];
}
}
return out;
}
// prewitt filter
cv::Mat prewitt_filter(cv::Mat img, int kernel_size, bool horizontal){
int height = img.rows;
int width = img.cols;
int channel = img.channels();
// prepare output
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);
// prepare kernel
double kernel[kernel_size][kernel_size] = {{-1, -1, -1}, {0, 0, 0}, {1, 1, 1}};
if (horizontal){
kernel[0][1] = 0;
kernel[0][2] = 1;
kernel[1][0] = -1;
kernel[1][2] = 1;
kernel[2][0] = -1;
kernel[2][1] = 0;
}
int pad = floor(kernel_size / 2);
double v = 0;
// filtering
for (int y = 0; y < height; y++){
for (int x = 0; x < width; x++){
v = 0;
for (int dy = -pad; dy < pad + 1; dy++){
for (int dx = -pad; dx < pad + 1; dx++){
if (((y + dy) >= 0) && (( x + dx) >= 0) && ((y + dy) < height) && ((x + dx) < width)){
v += img.at<uchar>(y + dy, x + dx) * kernel[dy + pad][dx + pad];
}
}
}
v = fmax(v, 0);
v = fmin(v, 255);
out.at<uchar>(y, x) = (uchar)v;
}
}
return out;
}
int main(int argc, const char* argv[]){
// read image
cv::Mat img = cv::imread("imori.jpg", cv::IMREAD_COLOR);
// BGR -> Gray
cv::Mat gray = BGR2GRAY(img);
// prewitt filter (vertical)
cv::Mat out_v = prewitt_filter(gray, 3, false);
// prewitt filter (horizontal)
cv::Mat out_h = prewitt_filter(gray, 3, true);
//cv::imwrite("out.jpg", out);
cv::imshow("answer (vertical)", out_v);
cv::imshow("answer (horizontal)", out_h);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}