OpenCV - 添加文本
您可以使用 imgproc 类的方法 arrowedLine() 向图像添加文本。以下是此方法的语法。
putText(img, text, org, fontFace, fontScale, Scalar color, int thick)
此方法接受以下参数 −
mat − 一个 Mat 对象,表示要添加文本的图像。
text − 一个 string 变量,表示要添加的文本。
org −一个 Point 对象,表示图像左下角的文本字符串。
fontFace − 一个表示字体类型的整型变量。
fontScale − 一个 double 类型的变量,表示与字体特定基本大小相乘的比例因子。
scalar − 一个 Scalar 对象,表示要添加的文本的颜色。(BGR)
thickness − 一个表示线条粗细的整数,默认情况下,thickness 的值为 1。
示例
以下程序演示了如何向图像添加文本并使用 JavaFX 窗口显示它。
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class AddingTextToImage extends Application {
Mat matrix = null;
@Override
public void start(Stage stage) throws Exception {
// 从相机捕获快照
AddingTextToImage obj = new AddingTextToImage();
WritableImage writableImage = obj.LoadImage();
// 设置图像视图
ImageView imageView = new ImageView(writableImage);
// 设置图像视图的适合高度和宽度
imageView.setFitHeight(600);
imageView.setFitWidth(600);
// 设置图像视图的保留比例
imageView.setPreserveRatio(true);
// 创建 Group 对象
Group root = new Group(imageView);
// 创建场景对象
Scene scene = new Scene(root, 600, 400);
// 设置舞台标题
stage.setTitle("向图像添加文本");
// 将场景添加到舞台
stage.setScene(scene);
// 显示舞台内容
stage.show();
}
public WritableImage LoadImage() throws Exception {
// 加载 OpenCV 核心库
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// 从文件读取图像并将其存储到 Matrix 对象中
String file ="E:/OpenCV/chap8/input.jpg";
Mat matrix = Imgcodecs.imread(file);
// 添加文本
Imgproc.putText (
matrix, // Matrix obj of the image
"Ravivarma's Painting", // Text to be added
new Point(10, 50), // point
Core.FONT_HERSHEY_SIMPLEX , // front face
1, // front scale
new Scalar(0, 0, 0), // Scalar object for color
4 // Thickness
);
// 对图像进行编码
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", matrix, matOfByte);
// 将编码的 Mat 存储在字节数组中
byte[] byteArray = matOfByte.toArray();
// 显示图像
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage bufImage = ImageIO.read(in);
this.matrix = matrix;
//创建可写图像
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
public static void main(String args[]) {
launch(args);
}
}
执行上述程序后,你将获得以下输出 −

