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
|
#include <iostream>
const int rgb = 3; // stride per pixel
void print_pixel(int x, int y, int width, int rgbarr[])
{
size_t index = rgb * width * y + rgb * x;
int r = rgbarr[index + 0];
int g = rgbarr[index + 1];
int b = rgbarr[index + 2];
std::cout << "Pixel (" << x << ", " << y << ") [starting index " << index << "] value = "
<< "RGB(" << r << ", " << g << ", " << b << ")\n";
}
void print_x_y(size_t index, int width)
{
int x = (index/rgb) % width;
int y = (index/rgb) / width;
std::cout << "Pixel (X, Y) at [index " << index << "] = (" << x << ", " << y << ")\n";
}
void assign_color_to_pixel(
int rgbarr[], int x, int y, int r, int g, int b,
int width) // necessary to pass in widt along with (x, y)
{
size_t index = rgb * width * y + rgb * x;
rgbarr[index + 0] = r;
rgbarr[index + 1] = g;
rgbarr[index + 2] = b;
}
int main()
{
const int width = 3;
const int height = 2;
const int size = rgb * width * height;
int rgbarr[size]; // Dynamically allocate if size not known at compile-time
for (int i = 0; i < size; i += rgb)
{
std::cout << i << "/" << size << std::endl;
rgbarr[i+0] = i+1 % 256; // RED
rgbarr[i+1] = ((i+1) / 2) % 256; // BLUE
rgbarr[i+2] = ((i+1) * 2) % 256; // GREEN
}
// INDEX & PIXEL VALUES GIVEN (X, Y) PAIR
int x = 2; // 3rd column
int y = 1; // 2nd row
print_pixel(x, y, width, rgbarr);
print_pixel(x-1, y-1, width, rgbarr);
std::cout << '\n';
// (X, Y) PAIR GIVEN INDEX
print_x_y(rgb * 4, width); // 5th pixel, red component
print_x_y(rgb * 4 + 1, width); // 5th pixel, green component (same pixel)
print_x_y(rgb * 5 + 2, width); // 6th pixel, blue component (different pixel)
// example
assign_color_to_pixel(
rgbarr, // array
x, y, // (X, Y) coordinate
200, 100, 50, // (R G B) value
width // necessary information
);
}
|