C++: grayscale conversion and thresholding

A color pixel has red, green, and blue channels. A grayscale image keeps only brightness. Because human vision is most sensitive to green and least to blue, the standard luma formula weights the channels unequally: 0.299·R + 0.587·G + 0.114·B.

C++
#include <cmath>
#include <iostream>
#include <vector>

struct Rgb {
  int r, g, b;
};

int main() {
  std::vector<Rgb> pixels = {{255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 255}};
  std::vector<int> gray;
  double total = 0;
  for (const Rgb& p : pixels) {
    int value = static_cast<int>(std::lround(0.299 * p.r + 0.587 * p.g + 0.114 * p.b));
    gray.push_back(value);
    total += value;
  }
  double threshold = total / gray.size();

  std::cout << "gray:";
  for (int v : gray) {
    std::cout << " " << v;
  }
  std::cout << "\nthreshold: " << threshold << "\nbinary:";
  for (int v : gray) {
    std::cout << " " << (v > threshold ? 1 : 0);
  }
  std::cout << "\n";
}
Read the full lesson