直方图均衡化
直方图均衡化其作用为改变原有的图像直方图分布,用改变后的灰度LUT方式重建图像,来调整图像的亮度与对比度。其函数声明如下:
equalizeHist(src, dst);
其中src为单通道的8单位灰度图像,dst为输出源。
Java代码(JavaFX Controller层)
public class Controller{
@FXML private Text fxText;
@FXML private ImageView imageView;
@FXML public void handleButtonEvent(ActionEvent actionEvent) throws IOException {
Node source = (Node) actionEvent.getSource();
Window theStage = source.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JPG Files(*.jpg)", "*.jpg"));
File file = fileChooser.showOpenDialog(theStage);
runInSubThread(file.getPath());
}
private void runInSubThread(String filePath){
new Thread(new Runnable() {
@Override
public void run() {
try {
WritableImage writableImage = drawHistogram(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage equalizeHistogram(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Mat dst = new Mat();
Mat convert_temp = new Mat();
Mat gray = new Mat();
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
Imgproc.equalizeHist(gray, dst);
dst.copyTo(convert_temp);
List<Mat> images = new ArrayList<>();
images.add(convert_temp);
Mat mask = Mat.ones(src.size(), CvType.CV_8UC1);
Mat hist = new Mat();
Imgproc.calcHist(images, new MatOfInt(0), mask, hist, new MatOfInt(256), new MatOfFloat(0,255));
Core.normalize(hist, hist,0,255, Core.NORM_MINMAX);
int height = hist.rows();
dst.create(400,400,src.type());
dst.setTo(new Scalar(200,200,200));
float[] histData = new float[256];
hist.get(0,0, histData);
int offset_x = 50;
int offset_y = 350;
Imgproc.line(dst, new Point(offset_x, 0), new Point(offset_x, offset_y), new Scalar(0,0,0));
Imgproc.line(dst, new Point(offset_x, offset_y), new Point(400, offset_y), new Scalar(0,0,0));
for (int i = 0; i < height - 1; i++) {
int y1 = (int)histData[i];
int y2 = (int)histData[i+1];
Rect rect = new Rect();
rect.x = offset_x + i;
rect.y = offset_y - y1;
rect.width = 1;
rect.height = y1;
Imgproc.rectangle(dst, rect.tl(), rect.br(), new Scalar(15,15,15) );
}
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", dst, matOfByte);
byte[] bytes = matOfByte.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage bufImage = ImageIO.read(in);
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
}
运行图
|