矩形绘制
使用rectangle() 方法在图像上绘制一个矩形。 该方法的一个构造方法如下:
rectangle(img, pt1, pt2, color, thickness);
参数意义如下:
- mat
表示要在其上绘制矩形的图像的Mat对象 - pt1 和 pt2
两个Point对象,表示要绘制的矩形的顶点。s - calar
表示矩形颜色的标量对象(BGR)。 - thickness
表示矩形厚度的整数; 默认情况下,厚度值为1。
需要指出的是,pt1是待绘制的矩形左上角点,pt2是矩形待绘制的右下角点,二者为矩形对角线上的点。OpenCV中方向为屏幕左上角为坐标原点,依该点水平向右为X正半轴方向,依该点竖直向下为Y轴正半轴方向,与Android和iOS相同,但与OS X不同。
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());
}
// Run in sub thread to avoid trouble with main thread, and non JavaFX platform could call drawRectangle
// directly in handleButtonEvent().
private void runInSubThread(String filePath){
new Thread(new Runnable() {
@Override
public void run() {
try {
WritableImage writableImage = drawRectangle(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage drawRectangle(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Imgproc.rectangle(src, new Point(187,90), new Point(251,165), new Scalar(0,0,255), 2);
Imgproc.rectangle(src, new Point(10,10), new Point(100,100), new Scalar(0,255,255), 2);
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", src, matOfByte);
byte[] bytes = matOfByte.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage bufImage = ImageIO.read(in);
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
}
运行图