赞
踩
参考:https://www.cnblogs.com/ggYYa/p/5707259.html
原图:
处理后的图片:
代码:
- public class BalanceWhite {
-
- public static void main(String[] args) {
- System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
- Mat src = Imgcodecs.imread("d:/c/bai1.png");
-
- if (src.empty()) {
- System.err.println("The picture doesn't exist");
- return;
- }
- // 自己写的显示图片的方法
- Images.showImage(src);
- BalanceWhite b = new BalanceWhite();
- b.balanceWhite(src);
- }
-
- // 白平衡算法
- void balanceWhite(Mat src) {
- Mat dstImage = new Mat();
-
- List<Mat> imgChannels = new ArrayList<>();
-
- // 分离通道
- Core.split(src, imgChannels);
- Mat imageBlueChannel = imgChannels.get(0);
- Mat imageGreenChannel = imgChannels.get(1);
- Mat imageRedChannel = imgChannels.get(2);
-
- // 求各通道的平均值
- double imageBlueChannelAvg = Core.mean(imageBlueChannel).val[0];
- double imageGreenChannelAvg = Core.mean(imageGreenChannel).val[0];
- double imageRedChannelAvg = Core.mean(imageRedChannel).val[0];
-
- // 求出各通道所占增益
- double K = (imageRedChannelAvg + imageGreenChannelAvg + imageRedChannelAvg) / 3;
- double Kb = K / imageBlueChannelAvg;
- double Kg = K / imageGreenChannelAvg;
- double Kr = K / imageRedChannelAvg;
-
- // 更新白平衡后的各通道BGR值,原来是用addWeighted()方法,为了知道清楚的了解内部的运算,写了一个方法。
- addK(imageBlueChannel, Kb);
- addK(imageGreenChannel, Kg);
- addK(imageRedChannel, Kr);
-
- // 使用 addWeighted() 方法,效果和 addK() 方法一样
- // Core.addWeighted(imageBlueChannel, Kb, imageBlueChannel, 0, 0,
- // imageBlueChannel);
- // Core.addWeighted(imageGreenChannel, Kg, imageGreenChannel, 0, 0,
- // imageGreenChannel);
- // Core.addWeighted(imageRedChannel, Kr, imageRedChannel, 0, 0,
- // imageRedChannel);
-
- Core.merge(imgChannels, dstImage);
-
- // 自己写的显示图片方法
- Images.showImage(dstImage);
-
- }
-
- // 增加每个元素的增益值
- void addK(Mat mat, double k) {
- for (int i = 0; i < mat.rows(); i++) {
- for (int j = 0; j < mat.cols(); j++) {
- double val = mat.get(i, j)[0] * k;
- mat.put(i, j, val);
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。