From 4ee23bb4428927d13684017e393bb9f5d8351c1f Mon Sep 17 00:00:00 2001 From: augustin64 Date: Tue, 1 Apr 2025 18:27:35 +0200 Subject: [PATCH] Load mask --- src/seam-carving.cpp | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/seam-carving.cpp b/src/seam-carving.cpp index 0b22704..2a6a250 100644 --- a/src/seam-carving.cpp +++ b/src/seam-carving.cpp @@ -242,7 +242,7 @@ std::vector carving_step(const std::vector source_img, } void seam_carving(unsigned char *source, int width, int height, int nbChannels, - const char *out_filename, int nbSeams, bool vertical) { + const char *out_filename, int nbSeams, bool vertical, unsigned char* mask=nullptr) { int nbColorChannels = nbChannels > 3 ? 3 : nbChannels; int curWidth = width; int curHeight = height; @@ -290,8 +290,8 @@ void seam_carving(unsigned char *source, int width, int height, int nbChannels, } } for (auto k = 0; k < width * height; k++) { - // for (auto i=0; i < nbColorChannels; i++) //* Uncomment if you prefer to - // see darkened source image + //* Uncomment if you prefer to see darkened source image + // for (auto i=0; i < nbColorChannels; i++) // output[nbChannels*k+i] = source_img[nbChannels*k+i]/nbChannels; for (auto ch = 0; ch < nbColorChannels; ch++) { @@ -347,8 +347,8 @@ void seam_carving(unsigned char *source, int width, int height, int nbChannels, int main(int argc, char **argv) { CLI::App app{"seam-carving"}; + std::string maskImage; std::string sourceImage; - std::string maskImage = "mask.png"; std::string outputImage = "output.png"; int nbSeams = 1; bool vertical = false; @@ -378,10 +378,39 @@ int main(int argc, char **argv) { int width, height, nbChannels; unsigned char *source = stbi_load(sourceImage.c_str(), &width, &height, &nbChannels, 0); - nbSeams = std::min(nbSeams, width); + + unsigned char* mask = nullptr; + if (!maskImage.empty()) { + int maskWidth, maskHeight, maskChannels; + mask = + stbi_load(maskImage.c_str(), &maskWidth, &maskHeight, &maskChannels, 0); + + if (maskWidth != width || maskHeight != height) { + std::cerr << maskImage << " and " << sourceImage + << " differ in dimension. Please provide a valid mask." + << std::endl; + exit(1); + } + if (maskChannels < 3) { + std::cerr << maskImage << " needs to be RGB." << std::endl; + exit(1); + } + unsigned char r, g, b; + for (auto i=0; i < width*height; i++) { + r = mask[maskChannels*i]; + g = mask[maskChannels*i]; + b = mask[maskChannels*i]; + mask[2*i] = (r == 0) && (g == 255) && (b == 0); + mask[2*i+1] = (r == 255) && (g == 0) && (b == 0); + } + //* From now on, mask has the same dimensions as source and exactly 2 channels + //* The first channel is positive, the second one negative. + } + + nbSeams = std::min(nbSeams, vertical ? width-1 : height-1); // We want to keep at least one row or column seam_carving(source, width, height, nbChannels, outputImage.c_str(), - nbSeams, vertical); + nbSeams, vertical, mask=mask); stbi_image_free(source); exit(0);