-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry3.cpp
More file actions
84 lines (63 loc) · 2.55 KB
/
try3.cpp
File metadata and controls
84 lines (63 loc) · 2.55 KB
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
#include <iostream>
#include <vector>
#include <algorithm>
#define cimg_use_jpeg
#include "CImg.h"
using namespace cimg_library;
std::vector<std::vector<uint8_t>> getPixelValues(const char* filename, int& width, int& height) {
CImg<uint8_t> image(filename);
width = image.width();
height = image.height();
std::vector<std::vector<uint8_t>> pixelValues(height, std::vector<uint8_t>(width));
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
pixelValues[y][x] = image(x, y);
}
}
return pixelValues;
}
std::vector<std::vector<uint8_t>> medianFilter(const std::vector<std::vector<uint8_t>>& image, int filterSize) {
int width = image[0].size();
int height = image.size();
std::vector<std::vector<uint8_t>> filteredImage(height, std::vector<uint8_t>(width));
int filterOffset = filterSize / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
std::vector<uint8_t> pixels;
for (int filterY = -filterOffset; filterY <= filterOffset; filterY++) {
for (int filterX = -filterOffset; filterX <= filterOffset; filterX++) {
int imageX = std::min(std::max(x + filterX, 0), width - 1);
int imageY = std::min(std::max(y + filterY, 0), height - 1);
pixels.push_back(image[imageY][imageX]);
}
}
std::sort(pixels.begin(), pixels.end());
uint8_t medianValue = pixels[pixels.size() / 2];
filteredImage[y][x] = medianValue;
}
}
return filteredImage;
}
void saveImage(const std::vector<std::vector<uint8_t>>& image, const char* filename, int width, int height) {
CImg<uint8_t> outputImage(width, height, 1, 1);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
outputImage(x, y) = image[y][x];
}
}
outputImage.save_jpeg(filename);
}
int main() {
const char* filename = "lenna4.jpg";
int width, height;
// Get the pixel values for the image
std::vector<std::vector<uint8_t>> pixelValues = getPixelValues(filename, width, height);
int radius = 3;
// Apply median filter to the image
std::vector<std::vector<uint8_t>> filteredImage = medianFilter(pixelValues, radius);
// Save the filtered image
const char* outputFilename = "filtered_lenna.jpg";
saveImage(filteredImage, outputFilename, width, height);
std::cout << "Median filter applied and filtered image saved successfully." << std::endl;
return 0;
}