bool Image_reader::crop()

in src/mlio/image_reader.cc [336:390]


bool Image_reader::crop(cv::Mat &src, cv::Mat &dst, const Instance &instance) const
{
    if (src.rows < img_dims_[1] || src.cols < img_dims_[2]) {
        if (warn_bad_instances() || error_bad_example_) {
            auto msg = fmt::format(
                "The input image dimensions (rows: {2:n}, cols: {3:n}) are smaller than the output image dimensions (rows: {4:n}, cols: {5:n}) for the image #{1:n} in the data store '{0}'.",
                instance.data_store().id(),
                instance.index(),
                src.rows,
                src.cols,
                img_dims_[1],
                img_dims_[2]);

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

            if (error_bad_example_) {
                throw std::invalid_argument{msg};
            }
        }

        return false;
    }

    // Crop from the center.
    int y = (src.rows - img_dims_[1]) / 2;
    int x = (src.cols - img_dims_[2]) / 2;

    try {
        cv::Rect roi{x, y, img_dims_[2], img_dims_[1]};
        src(roi).copyTo(dst);
    }
    catch (const cv::Exception &e) {
        if (warn_bad_instances() || error_bad_example_) {
            auto msg = fmt::format(
                "The image crop 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 false;
    }

    return true;
}