Image Adjustment

Image adjustment generally includes level, contrast, gamma, hue, saturation and brightness modification.

In Matlab, you can use the func imadjust()

% read the image
I = imread("./pout.tif");
imshow();
% Adjust the contrast the image so that 1% of the data is saturated at low and high intensities, and display it
J = imadjust(I);
figure
imshow(J)
There is no builtin solution in OpenCV to perform it, but it can be easily realized in a loop.

#include <opencv2/opencv.hpp>
#include <vector>
#include <algorithm>

using namespace std;
using namespace cv;

void imadjust(const Mat1b& src, Mat1b& dst, int tol = 1, Vec2i in = Vec2i(0, 255), Vec2i out = Vec2i(0, 255))
{
  // src: input CV_8UC1 image
  // dst: output CV_8UC1 image
  // tol: tolerance, from 0 to 100.
  // in: src image bounds
  // out: dst image bounds
  dst = src.clone();

  tol = max(0, min(100, tol));

  if (tol > 0)
  {
  	// Histogram
  	vector<int> hist(256, 0);
  	for (int r = 0; r < src.rows; r++) {
  	  for (int c = 0; c < src.cols; c++) {
  	  	hist[src(r, c)]++;
  	  }
  	}

  	// Cumulative histogram
  	vector<int> cum = hist;
  	for (int i = 1; i < hist.size(); i++)
  	  cum[i] = cum[i - 1] + hist[i];

  	// Compute bounds
  	int total = src.rows * src.cols;
  	int low_bound = total * tol / 100;
  	int up_bound = total * (100 - tol) / 100;
  	in[0] = distance(cum.begin(), lower_bound(cum.begin(), cum.end(), low_bound));
  	in[1] = distance(cum.begin(), lower_bound(cum.begin(), cum.end(), up_bound));
  }

  // Stretching
  float scale = float(out[1] - out[0]) / float(in[1] - in[0]);
  for (int r = 0; r < dst.rows; r++) {
  	for (int c = 0; c < dst.cols; c++) {
  	  int vs = max(src(r, c) - in[0], 0);
  	  int vd = min(int(vs * scale + 0.5f) + out[0], out[1]);
  	  dst(r, c) = saturate_cast<uchar>(vd);
  	}
  }
}

int main()
{
  char img_file[256] = "./imadjust1.png";

  Mat3b img = imread(img_file);
  if (!img.data) {
  	printf("Warning: the image [%s] is empty!\n", img_file);
  }
   	return 0;

  Mat1b gray;
  cvtColor(img, gray, COLOR_RGB2GRAY);

  Mat1b adjusted;
  imadjust(gray, adjusted);

  imwrite("./adjusted.png", adjusted);
  return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值