📜  在 OpenCV 中向图像添加文本的Java程序

📅  最后修改于: 2022-05-13 01:55:05.499000             🧑  作者: Mango

在 OpenCV 中向图像添加文本的Java程序

OpenCV是用于计算机视觉、图像处理和机器学习的跨平台开源库。它现在在实时操作中起着重要作用,它改进了模块为图像处理提供足够的功能。它具有 C++、C、 Python和Java接口,并支持 Windows、Linux、macOS、iOS和 Android。通过使用它,人们甚至可以处理图像和视频以识别物体、面孔,甚至是人类的笔迹

这里, putText()是一个内置方法,在从下面给出的Java程序中的相应模块导入此方法后,将使用该方法。

语法:导入处理图片的模块:

import org.opencv.imgproc.Imgproc;

语法:使用该类的putText()方法如下:

putText(image, text, org, fontType, fontSize, color, thickness)

参数:

Datatype of parametersName of parameterFunctionalities
Mat objectimageText to be added to an input image object
StringtextText to be inserted to an input image
Point (tuple)orgCoordinates of the bottom left corner of a text string in the image
IntegerfontTypeDepicting the style of fonts
DoublefontSizeSize of text to be added over an input image 
ScalarcolorColor of the text string to be drawn over an input image
IntegerthicknessThe thickness of the line in the unit, by default it is unity

异常:这个类的这个方法没有抛出异常,因为只是传递了元组。例如在BGR色谱中,蓝光元组如下:(255,0,0)

实现:输入图像如下是随机拍摄的。现在文本-“GFG IS COOL”将添加到该图像上。

输入图像

Java
// Importing all OpenCV files
import org.opencv.*;
import org.opencv.imgproc.Imgproc;
  
public class GFG {
  
    // Main driver code
    public static void main(String args[]) throws Exception
    {
  
        // Loading the OpenCV core library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  
        // Reading the contents of the image
        // from local computer directory
        String src = "D:\\InputImage.jpg";
  
        // Creating a Mat object
        Mat image = Imgcodecs.imread(src);
  
        // Text to be added
        String text = "GFG IS COOL";
  
        // Points from where text should be added
        Point org = new Point(170, 280);
  
        // Color of the text
        Scalar color = new Scalar(0, 0, 255);
  
        // Fonttype of the text to be added
        int fontType = Imgproc.FONT_HERSHEY_PLAIN;
  
        // Fontsize of the text to be added
        int fontSze = 1;
  
        // Thickness of the lines in px
        int thickness = 3;
  
        // Adding text to the image using putText method
        Imgproc.putText(image, text, org, fontType,
                        fontSize, color, thickness);
  
        // Displaying the Image after adding the Text
        HighGui.imshow("", image);
  
        // Waiting for a key event to delay
        HighGui.waitKey();
    }
}


输出:添加文字后的图像如下:

输出图像