N
N
Nikita2022-03-19 14:22:26
C++ / C#
Nikita, 2022-03-19 14:22:26

How to load a grayscale JPG image using Magick++?

I searched all over Google, read the official documentation, but did not find how to read the image in grayscale (grayscale). You need to get an array of pixels of size xy , where x and y are the width and height.

PS An example of an image (I hope Habr does not convert it)
6235bd719736e591409796.jpeg
PS2 If you load an image with the same code as regular RGB images are loaded, then zeros are returned on all pixels in all three colors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2022-03-19
@gth-other

Understood. The solution may not be the best, but it works. For anyone who (probably) comes here from google:

std::vector<float> load_jpg(const std::string& file_location) {
    Magick::Image image;
    image.read( file_location);
    image.type(Magick::TrueColorType);
    image.colorspaceType(Magick::sRGBColorspace);
    size_t width = image.baseColumns();
    size_t height = image.baseRows();
    std::vector<float> vector(width * height);
    Magick::ColorRGB colour;
    for (size_t row = 0; row < height; row = row + 1) {
        for (size_t column = 0; column < width; column = column + 1) {
            colour = image.pixelColor(row, column);
            vector[row * width + column] = (float)(0.2126 * colour.red() + 0.7152 * colour.green() + 0.0722 * colour.blue());
        }
    }
    return vector;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question