The following code generates a grayscale image which contains 10 different shades of grey. The approach taken is to create a view on the part of the original image and colorise it with the computed next shade of grey. The width of the view is equal to the width of the image divided by the number of colors, and the height is unchanged.
#include <opencv2/core/mat.hpp>
#include <opencv2/highgui.hpp>
int main() {
constexpr int width = 100;
constexpr int height = 100;
constexpr int number_of_colors = 10;
constexpr int color_width = width / number_of_colors;
cv::Mat grayscale_image(height, width, CV_8UC1);
for (int color_index = 0; color_index < number_of_colors; color_index++) {
const int next_color_value = color_index * 255 / (number_of_colors - 1);
cv::Mat color_roi = grayscale_image(
cv::Rect(color_width * color_index, 0, color_width, height));
color_roi = cv::Scalar(next_color_value);
}
cv::imshow("image", grayscale_image);
cv::waitKey(0);
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project("grayscale_image" VERSION 0.1.0)
find_package(OpenCV 4 REQUIRED core highgui)
add_executable(grayscale_image
main.cpp
)
target_link_libraries(grayscale_image
${OpenCV_LIBS}
)
Building (assuming these files are saved in a~/grayscale/
directory:
cd ~/grayscale/
cmake -S . -B build -G "Ninja Multi-Config"
./build/Release/grayscale_image
Result:
