调整图像的对比度
#include <spdlog/spdlog.h>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>
namespace zhjr {
namespace utils {
/**
* @brief 调整图像的对比度
* @param input_image
* @param output_image
* @return
*/
bool adjustContrast(const cv::Mat& input_image, cv::Mat& output_image,
bool use_official = false) {
SPDLOG_LOGGER_INFO(spdlog::default_logger(), "开始调整图像对比度");
SPDLOG_LOGGER_INFO(spdlog::default_logger(), "OpenCV {}", CV_VERSION);
if (input_image.empty()) {
return false;
}
if (!use_official) { // 自己实现
SPDLOG_LOGGER_INFO(spdlog::default_logger(),
"调整图像对比度:用自己实现的方法");
size_t rows = input_image.rows;
size_t cols = (input_image.cols - 1) * input_image.channels();
size_t offset_x = input_image.channels();
output_image = cv::Mat::zeros(input_image.size(), input_image.type());
for (size_t row = 1; row < (rows - 1); row++) {
const uchar* ptr_last_row = input_image.ptr<uchar>(row - 1);
const uchar* ptr_curr_row = input_image.ptr<uchar>(row);
const uchar* ptr_next_row = input_image.ptr<uchar>(row + 1);
uchar* ptr_output = output_image.ptr<uchar>(row);
for (size_t col = offset_x; col < cols; col++) {
ptr_output[col] = cv::saturate_cast<uchar>(
5 * ptr_curr_row[col] -
(ptr_curr_row[col - offset_x] + ptr_curr_row[col + offset_x] +
ptr_last_row[col] + ptr_next_row[col]));
}
}
} else { // 官方接口 cv::filter2D
SPDLOG_LOGGER_INFO(spdlog::default_logger(),
"调整图像对比度:用官方接口 cv::filter2D");
cv::Mat kernel = (cv::Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
cv::filter2D(input_image, output_image, input_image.depth(), kernel);
}
SPDLOG_LOGGER_INFO(spdlog::default_logger(), "完成调整图像对比度");
return true;
}
} // namespace utils
} // namespace zhjr
int main(int argc, char* argv[]) {
std::string image_file = "../data/lena.jpg";
cv::Mat input_image = cv::imread(image_file);
cv::Mat output_image;
if (!zhjr::utils::adjustContrast(input_image, output_image, false)) {
SPDLOG_LOGGER_ERROR(spdlog::default_logger(), "调整图像对比度失败");
return false;
}
cv::putText(input_image, "input_image", cv::Point(0, 30),
cv::FONT_HERSHEY_COMPLEX, 1.0, cv::Scalar(0, 255, 0), 2);
cv::putText(output_image, "output_image", cv::Point(0, 30),
cv::FONT_HERSHEY_COMPLEX, 1.0, cv::Scalar(0, 255, 0), 2);
std::vector<cv::Mat> images{input_image, output_image};
cv::Mat output_image_contrast;
cv::hconcat(images, output_image_contrast);
cv::imshow("images", output_image_contrast);
cv::waitKey();
cv::destroyAllWindows();
return EXIT_SUCCESS;
}
输出结果: