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 |
#include <iostream> #include <vector> #include <algorithm> const int WIDTH = 5; const int HEIGHT = 5; const int THRESHOLD = 128; class Image { public: Image(const std::vector<std::vector<int>>& pixels) : pixels(pixels) {} void applyThreshold() { for (int i = 0; i < HEIGHT; ++i) { for (int j = 0; j < WIDTH; ++j) { pixels[i][j] = (pixels[i][j] >= THRESHOLD) ? 255 : 0; } } } void printImage() const { for (const auto& row : pixels) { for (int pixel : row) { std::cout << (pixel == 255 ? '#' : ' ') << ' '; } std::cout << '\n'; } } private: std::vector<std::vector<int>> pixels; }; int main() { // Example grayscale image (5x5) std::vector<std::vector<int>> grayscaleImage = { { 10, 50, 150, 200, 250 }, { 30, 70, 120, 180, 220 }, { 40, 90, 130, 190, 240 }, { 60, 100, 140, 170, 210 }, { 80, 110, 160, 180, 230 } }; Image image(grayscaleImage); std::cout << "Original Image:\n"; image.printImage(); image.applyThreshold(); std::cout << "\nThresholded Image:\n"; image.printImage(); return 0; } |
Explanation
- Class Definition (
Image
):- Private Members:
pixels
: A 2D vector representing the grayscale image, where each element is a pixel intensity (0 to 255).
- Public Methods:
Image(const std::vector<std::vector<int>>& pixels)
: Constructor initializes the image with given pixel values.void applyThreshold()
: Applies a threshold to the image.- Pixels with intensity greater than or equal to
THRESHOLD
are set to 255 (white). - Pixels with intensity less than
THRESHOLD
are set to 0 (black).
- Pixels with intensity greater than or equal to
void printImage() const
: Prints the image to the console.- Prints
#
for white pixels and space for black pixels.
- Prints
- Private Members:
main
Function:- Initializes a sample grayscale image with a 5×5 grid of pixel intensities.
- Creates an
Image
object with the sample image. - Prints the original image.
- Applies the thresholding operation.
- Prints the thresholded image.