cv::Mat Image_reader::decode_image()

in src/mlio/image_reader.cc [238:292]


cv::Mat Image_reader::decode_image(const cv::Mat &buf, int mode, const Instance &instance) const
{
    cv::Mat decoded_img{};
    try {
        decoded_img = cv::imdecode(buf, mode);
    }
    catch (const cv::Exception &e) {
        if (warn_bad_instances() || error_bad_example_) {
            auto msg = fmt::format(
                "The image decode operation failed for the image #{1:n} in the data store '{0}' with the following exception: {2}",
                instance.data_store().id(),
                instance.index(),
                e.what());

            if (warn_bad_instances()) {
                logger::warn(msg);
            }

            if (error_bad_example_) {
                throw Invalid_instance_error{msg};
            }
        }

        return decoded_img;
    }

    if (decoded_img.empty()) {
        if (warn_bad_instances() || error_bad_example_) {
            auto msg = fmt::format(
                "The image decode operation failed for the image #{1:n} in the data store '{0}'.",
                instance.data_store().id(),
                instance.index());

            if (warn_bad_instances()) {
                logger::warn(msg);
            }

            if (error_bad_example_) {
                throw Invalid_instance_error{msg};
            }
        }

        return decoded_img;
    }

    if (mode == cv::ImreadModes::IMREAD_UNCHANGED && decoded_img.channels() != 4) {
        throw std::invalid_argument{fmt::format(
            "The image #{1:n} in the data store '{0}' contains {2:n} channels while it is expected to contain 4 channels.",
            instance.data_store().id(),
            instance.index(),
            decoded_img.channels())};
    }

    return decoded_img;
}