-3

How can I create a grayscale image in c++? Image size 100x100. I know that in python this can be done using numpy. The best option would be if this image looks like a scale of 10 colors from white to black. I work in Vivado HLS, so I can only use one-dimensional arrays

I think I've looked all over the internet looking for a solution, which is why I'm here. I suppose I need to create an array, which then needs to be converted to Mat.But how to do it?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • 1
    Please show some effort... You may add Python code that creates the image using NumPy. The 1D array indexing is simple, [here](https://stackoverflow.com/a/2151141/4926757) is an example. cv::Mat has a constructor that accepts a pointer to (1D) array as image data. – Rotem Nov 25 '22 at 21:53
  • this is about FPGA stuff. I doubt the C++-to-HDL compiler can deal with true C++ (OpenCV code). that thing supports plain C++ code for numerical kernels, which it ports to HDL, which can be synthesized to run on an FPGA. – Christoph Rackwitz Nov 26 '22 at 18:50
  • welcome. [tour], [ask]. be descriptive in your question, use salient tags. I've added a few based on your mention of "Vivado HLS" – Christoph Rackwitz Nov 26 '22 at 18:52

1 Answers1

1

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:

generated image

tomaszmi
  • 443
  • 2
  • 6