Answer:
#include <iostream>
using namespace std;
// Pixel structure
struct Pixel
{
unsigned int red;
unsigned int green;
unsigned int blue;
Pixel() {
red = 0;
green = 0;
blue = 0;
}
};
// function prototype
int energy(Pixel** image, int x, int y, int width, int height);
// main function
int main() {
// create array of pixel 3 by 4
Pixel** image = new Pixel*[3];
for (int i = 0; i < 3; i++) {
image[i] = new Pixel[4];
}
// initialize array
image[0][0].red = 255;
image[0][0].green = 101;
image[0][0].blue = 51;
image[1][0].red = 255;
image[1][0].green = 101;
image[1][0].blue = 153;
image[2][0].red = 255;
image[2][0].green = 101;
image[2][0].blue = 255;
image[0][1].red = 255;
image[0][1].green = 153;
image[0][1].blue = 51;
image[1][1].red = 255;
image[1][1].green = 153;
image[1][1].blue = 153;
image[2][1].red = 255;
image[2][1].green = 153;
image[2][1].blue = 255;
image[0][2].red = 255;
image[0][2].green = 203;
image[0][2].blue = 51;
image[1][2].red = 255;
image[1][2].green = 204;
image[1][2].blue = 153;
image[2][2].red = 255;
image[2][2].green = 205;
image[2][2].blue = 255;
image[0][3].red = 255;
image[0][3].green = 255;
image[0][3].blue = 51;
image[1][3].red = 255;
image[1][3].green = 255;
image[1][3].blue = 153;
image[2][3].red = 255;
image[2][3].green = 255;
image[2][3].blue = 255;
// create 3by4 array to store energy of each pixel
int energies[3][4];
// calculate energy for each pixel
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
energies[i][j] = energy(image, i, j, 3, 4);
}
}
// print energies of each pixel
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
// print by column
cout << energies[j][i] << " ";
}
cout << endl;
}
}
// function prototype
int energy(Pixel** image, int x, int y, int width, int height) {
// get adjacent pixels
Pixel left, right, up, down;
if (x > 0) {
left = image[x - 1][y];
if (x < width - 1) {
right = image[x + 1][y];
}
else {
right = image[0][y];
}
}
else {
left = image[width - 1][y];
if (x < width - 1) {
right = image[x + 1][y];
}
else {
right = image[0][y];
}
}
if (y > 0) {
up = image[x][y - 1];
if (y < height - 1) {
down = image[x][y + 1];
}
else {
down = image[x][0];
}
}
else {
up = image[x][height - 1];
if (y < height - 1) {
down = image[x][y + 1];
}
else {
down = image[x][0];
}
}
// calculate x-gradient and y-gradient
Pixel x_gradient;
Pixel y_gradient;
x_gradient.blue = right.blue - left.blue;
x_gradient.green = right.green - left.green;
x_gradient.red = right.red - left.red;
y_gradient.blue = down.blue - up.blue;
y_gradient.green = down.green - up.green;
y_gradient.red = down.red - up.red;
int x_value = x_gradient.blue * x_gradient.blue + x_gradient.green * x_gradient.green + x_gradient.red * x_gradient.red;
int y_value = y_gradient.blue * y_gradient.blue + y_gradient.green * y_gradient.green + y_gradient.red * y_gradient.red;
// return energy of pixel
return x_value + y_value;
}
Step-by-step explanation:
Please see attachment for ouput