Convert 2D image Data to 1D array .

Let say you have a 2D array which store pixel value of an image . Write a program to convert 2D data in 1D array so that i can have random access to data with given (x,y) coordinate .
1 Reply
nour_oud
nour_oud13mo ago
here's a c++ prg:
c++
#include <iostream>
#include <vector>

class Image {
private:
std::vector<int> pixels;
int width;
int height;

public:
Image(int w, int h) : width(w), height(h) {
pixels.resize(width * height);
}

int getIndex(int x, int y) {
return y * width + x;
}

void setPixel(int x, int y, int value) {
int index = getIndex(x, y);
pixels[index] = value;
}

int getPixel(int x, int y) {
int index = getIndex(x, y);
return pixels[index];
}
};

int main() {
Image img(3, 2);

img.setPixel(0, 0, 255);
img.setPixel(1, 0, 128);
img.setPixel(2, 0, 64);
img.setPixel(0, 1, 192);
img.setPixel(1, 1, 0);
img.setPixel(2, 1, 255);

std::cout << "Pixel value at (1, 0): " << img.getPixel(1, 0) << std::endl;
std::cout << "Pixel value at (2, 1): " << img.getPixel(2, 1) << std::endl;

return 0;
}
c++
#include <iostream>
#include <vector>

class Image {
private:
std::vector<int> pixels;
int width;
int height;

public:
Image(int w, int h) : width(w), height(h) {
pixels.resize(width * height);
}

int getIndex(int x, int y) {
return y * width + x;
}

void setPixel(int x, int y, int value) {
int index = getIndex(x, y);
pixels[index] = value;
}

int getPixel(int x, int y) {
int index = getIndex(x, y);
return pixels[index];
}
};

int main() {
Image img(3, 2);

img.setPixel(0, 0, 255);
img.setPixel(1, 0, 128);
img.setPixel(2, 0, 64);
img.setPixel(0, 1, 192);
img.setPixel(1, 1, 0);
img.setPixel(2, 1, 255);

std::cout << "Pixel value at (1, 0): " << img.getPixel(1, 0) << std::endl;
std::cout << "Pixel value at (2, 1): " << img.getPixel(2, 1) << std::endl;

return 0;
}
Want results from more Discord servers?
Add your server