c++ - Cimg 随机抛出 CImgIOException

标签 c++ multithreading image exception cimg

我有一些代码可以并行运行一堆线程。每个线程执行一个函数,以便在从目录加载的图像上复制“水印”,并将修改后的图像保存在用户指定的另一个目录中。为了获得结果,我必须使用 CImg 库。我不明白为什么有时 CImg 会抛出 CImgIOException喜欢CImg<unsigned char>::save_other(): Failed to save file , 或 CImg<unsigned char>::save_jpeg(): Failed to save file .我安装了 imagemagick,所以使用 jpeg/jpg 格式保存和打开图像应该没有问题。

这是我的代码:

#include <atomic>
#include <chrono>
#include "CImg.h"
#include <cstdlib>
#include <filesystem>
#include <functional>
#include <iostream>
#include <mutex>
#include <optional>
#include <queue>
#include <string>
#include <thread>
#include <typeinfo>

using namespace cimg_library;

std::mutex IMAGES_MUTEX, IO_MUTEX;
std::atomic_int PROCESSED_IMAGES = 0;

void apply_watermark(std::queue<std::string>& images, CImg<unsigned char>& watermark, int workload, \
                     std::string output_dir, int id) {
    std::queue<std::string> to_process;
    int counter = 0;
    bool stop = false;
    CImg<unsigned char> img;

    while (!stop) {
        IMAGES_MUTEX.lock();
        while(counter < workload) {
            if (images.empty()) {
                std::cout << "Thread " << id << ": founded empty queue" << std::endl;
                counter = workload;
                stop = true;
            } else {
                std::cout << "Thread " << id << ": aquiring image" << images.front() << std::endl;
                to_process.push(images.front());
                images.pop();
                counter += 1;
            }
        }
        IMAGES_MUTEX.unlock();

        counter = 0;

        while(!(to_process.empty())) {
            img.assign(to_process.front().c_str());

            if (!(img.width() != 1024 || img.height() != 768)) {
                cimg_forXY(watermark, x, y) {
                    int R = (int)watermark(x, y, 0, 0);

                    if (R != 255) {
                        img(x, y, 0, 0) = 0;
                        img(x, y, 0, 1) = 0;
                        img(x, y, 0, 2) = 0;
                    }
                }

                std::string fname = to_process.front().substr(to_process.front().find_last_of('/') + 1);

                IO_MUTEX.lock();
                std::cout << "Thread " << id << ": saving image " << fname << std::endl;
                IO_MUTEX.unlock();

                img.save_jpeg(((std::string)output_dir + (std::string)"/" + fname).c_str());
                to_process.pop();
                PROCESSED_IMAGES += 1;
            } else {
                to_process.pop();
            }
            img.clear();
        }
    }
    return;
}

int main(int argc, char const *argv[]) {
    auto completion_time_start = std::chrono::high_resolution_clock::now();

    if (argc != 5) {
        std::cout << "MISSING PARAMETERS!" << std::endl;

        return -1;
    }

    int par_degree = std::atoi(argv[3]);

    if (!(std::filesystem::exists(argv[2]))) {
        std::cout << "WATERMARK NOT FOUND!" << std::endl;

        return -1;
    }

    CImg<unsigned char> wtrk(argv[2]);
    std::queue<std::string> images;

    if (!(std::filesystem::exists(argv[1]))) {
        std::cout << "IMAGES' DIRECTORY NOT FOUND!" << std::endl;

        return -1;
    }

    for (auto& path : std::filesystem::directory_iterator(argv[1])) {
        std::string fname = path.path().string().substr(path.path().string().find_last_of('/') + 1);

        if (fname != ".DS_Store") {
            images.push(path.path().string());
        }
    }

    if (!(std::filesystem::exists((std::string)argv[4]))) {
        std::filesystem::create_directory((std::string)argv[4]);
    }

    if (par_degree == 1) {
        while(!(images.empty())) {
            CImg<unsigned char> img(images.front().c_str());

            if (!(img.width() != 1024 || img.height() != 768)) {
                cimg_forXY(wtrk, x, y) {
                    int R = (int)wtrk(x, y, 0, 0);

                    if (R != 255) {
                        img(x, y, 0, 0) = 0;
                        img(x, y, 0, 1) = 0;
                        img(x, y, 0, 2) = 0;
                    }
                }

                std::string fname = images.front().substr(images.front().find_last_of('/') + 1);
                img.save_jpeg(((std::string)argv[4] + (std::string)"/" + fname).c_str());
                images.pop();
                PROCESSED_IMAGES += 1;
            } else {
                images.pop();
            }
        }
    } else {
        int workload = (int)images.size() / par_degree;
        std::thread workers[par_degree];

        for (int i = 0; i < par_degree; i++) {
            workers[i] = std::thread(apply_watermark, std::ref(images), std::ref(wtrk), workload, \
                                     (std::string)argv[4], i);
        }

        for (int i = 0; i < par_degree; i++) {
            workers[i].join();
        }
    }

    auto completion_time_end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::ratio<1>> completion_time = completion_time_end - \
                                                                   completion_time_start;

    std::cout << "\nPARALLELISM DEGREE: " << par_degree << std::endl;
    std::cout << "COMPLETION TIME: " << completion_time.count() << " SECONDS" << std::endl;
    std::cout << "PROCESSED IMAGES: " << PROCESSED_IMAGES << std::endl;

    return 0;
}

所有的异常都是在保存图片的过程中抛出的,我对C++语言还很陌生,我真的不知道。仅使用一个线程(主线程)运行程序不会产生任何问题。

这是一个启动命令的例子:

./test ../imgs ../watermark.jpg 4 ../output_dir

我们将不胜感激。

最佳答案

我怀疑写命令不是线程安全的。例如,大多数 jpeg 编码器/解码器使用需要为每个线程制作的结构,在这里它们可能是共享的。尽管 cimg 网站上有声明,但尚不清楚是否/如何考虑到这一点。

我将通过序列化执行 .save_jpeg 命令来检验假设,尽管解决方案将来自不使用 cimg,而是直接调用 libjpeg-turbo:

//somewhere in global
std::mutex protect_save_image;

//At your section
{
    std::unique_lock lk(protect_save_image);
    img.save_jpeg(((std::string)argv[4] + (std::string)"/" + fname).c_str());`
}

此外,如果线程数非常高(又名 par_degree > 1000),您可能会超过可用文件描述的最大数量,从而导致 IO 失败。

关于c++ - Cimg 随机抛出 CImgIOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179907/

相关文章:

c++ - 在 DXGI 格式之间转换 RGBA 数据

c++ - 在 Linux 上中止线程 sleep

c++ - scanf_s 错误 Visual Studio

java - 使用 JMS 和 Spring 进行测试

java - Scala 和 Java 的 future 显然有意想不到的互动

c# - 处理线程静态变量

javascript - 如何在执行函数之前加载一些图像

c++ - 使用 qmake 查找编译器供应商/版本

java - 使用 PHP 或 Java 将带有foreignObject 标签的 svg 导出为图像

image - 使用 julia 将图像从 RGB 转换为 HSL 并再次转换回来