灰度化权重公式:
gray = r * 0.3 + g * 0.59 + b * 0.11;
代码
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
public class OpenCVTest {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) {
OpenCVTest openCVTest = new OpenCVTest();
//读入图片
Mat src = Imgcodecs.imread("F:\\opencvPhoto\\photo\\opencv.jpg");
//灰度化
Mat dst = openCVTest.gray(src);
//保存图片
Imgcodecs.imwrite("F:\\opencvPhoto\\result\\dst.jpg", dst);
}
/**
* 灰度化
* @param mat 原图片 (三通道)
* @return 灰度化图片(单通道)
*/
public Mat gray(Mat mat) {
Mat grayMat = new Mat(mat.size(), CvType.CV_8UC1);
for (int row = 0; row < mat.rows(); row++) {
for (int col = 0; col < mat.cols(); col++){
double b = mat.get(row, col)[0];
double g = mat.get(row, col)[1];
double r = mat.get(row, col)[2];
double gray = r * 0.3 + g * 0.59 + b * 0.11;
grayMat.put(row, col, gray);
}
}
return grayMat;
}
}
图片测试
原图
灰度化