文本绘制
在OpenCV中文本的绘制依赖于putText() 该方法。该函数一个常用构造函数如下:
putText(img, text, org, fontFace, fontScale,color,thickness)
下面是该函数的各参数解释:
-
mat
表示要在其上绘制矩形的图像的Mat对象。 -
text
表示要添加的文本的字符串变量。 -
org
表示图像中左下角文本字符串的Point对象,即文本的第一个字符变量左下角的位置。 -
fontFace
表示字体类型的整型变量。 -
fontScale
类型为double的变量表示与字体特定的基本大小相乘的缩放因子。 -
color
表示矩形颜色的标量对象(BGR)。 -
thickness
表示矩形厚度的整数。
常见fontFace枚举常量如下:
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 = drawText(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage drawText(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Imgproc.putText(src, "OpenCV.Kicinio", new Point(118,122),Core.FONT_HERSHEY_SIMPLEX ,
1, new Scalar(2,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;
}
}
运行图