Search code examples
c++imagemagickmagick++image-preprocessing

Convert image magick command to magick++ c++ code


I'm working on an image preprocessing project in my university and used an image magick script to clean image background.Now I want to get the same output through Magick++ (c++ api for imageMagick).

ImageMagick Command: "convert -respect-parenthesis ( INPUT_IMAGE.jpg -colorspace gray -contrast-stretch 0 ) ( -clone 0 -colorspace gray -negate -lat 25x25+30% -contrast-stretch 0 ) -compose copy_opacity -composite -fill white -opaque none -alpha off -background white OUTPUT_IMAGE.jpg"

I tried to convert this code to Magick++ code and failed in "-lat", "-contrast-stretch" and "-compose" positions.

This is my c++ code so far:

Image backgroungImage;
backgroungImage.read("INPUT_IMAGE.jpg");
backgroungImage.colorSpace(GRAYColorspace);
backgroungImage.type(GrayscaleType);
backgroungImage.contrastStretch(0, QuantumRange);
backgroungImage.write("Partial_output.jpg");

If anyone has an idea or a better solution please let me know. thanx in advance.


Solution

  • You're on the right track with -contrast-stretch. For -lat, remember that's an abbreviation of "Local Adaptive Threshold". So the C++ code would look like...

    Image backgroundImage;
    // INPUT_IMAGE.jpg
    backgroundImage.read("INPUT_IMAGE.jpg");
    // -colorspace gray 
    backgroundImage.colorSpace(GRAYColorspace);
    // -contrast-stretch 0
    backgroundImage.contrastStretch(0, QuantumRange);
    // -clone 0
    Image foregroundImage(backgroundImage);
    // -negate
    foregroundImage.negate();
    // -lat 25x25+30%
    foregroundImage.adaptiveThreshold(25, 25, QuantumRange * 0.30);
    // -contrast-stretch 0
    backgroundImage.contrastStretch(0, QuantumRange);
    // -compose copy_opacity -composite
    backgroundImage.composite(foregroundImage, 0, 0, CopyAlphaCompositeOp);
    // -fill white -opaque none
    backgroundImage.opaque(Color("NONE"), Color("WHITE"));
    // -alpha off
    backgroundImage.alpha(false);
    // -background white
    backgroundImage.backgroundColor(Color("WHITE"));
    // OUTPUT_IMAGE.jpg
    backgroundImage.write("OUTPUT_IMAGE.jpg");
    

    Hope that helps!