public static Mat Contrast(Mat src, int percent) {
float alpha = percent / 100.0f;
alpha = Math.max(-1f, Math.min(1f, alpha));
Mat temp = src.clone();
int row = src.rows();
int col = src.cols();
int thresh = 127;
for (int i = 0; i < row; i++) {
byte[] t = new byte[col * 3];
byte[] s = new byte[col * 3];
src.get(i, 0, s);
temp.get(i, 0, t);
for (int j = 0; j < col; j++) {
int b = s[j * 3] & 0xff;
int g = s[j * 3 + 1] & 0xff;
int r = s[j * 3 + 2] & 0xff;
int newb, newg, newr;
if (alpha == 1) {
t[j * 3 + 2] = (byte) (r > thresh ? 255 : 0);
t[j * 3 + 1] = (byte) (g > thresh ? 255 : 0);
t[j * 3] = (byte) (b > thresh ? 255 : 0);
continue;
} else if (alpha >= 0) {
newr = (int) (thresh + (r - thresh) / (1 - alpha));
newg = (int) (thresh + (g - thresh) / (1 - alpha));
newb = (int) (thresh + (b - thresh) / (1 - alpha));
} else {
newr = (int) (thresh + (r - thresh) * (1 + alpha));
newg = (int) (thresh + (g - thresh) * (1 + alpha));
newb = (int) (thresh + (b - thresh) * (1 + alpha));
}
newr = Math.max(0, Math.min(255, newr));
newg = Math.max(0, Math.min(255, newg));
newb = Math.max(0, Math.min(255, newb));
t[j * 3 + 2] = (byte) newr;
t[j * 3 + 1] = (byte) newg;
t[j * 3] = (byte) newb;
}
temp.put(i, 0, t);
}
return temp;
}
以上代码改编自c++代码:(7条消息) OpenCV-图像对比度_opencv 对比度_翟天保Steven的博客-CSDN博客