Java DIP - 应用水印
在本章中,我们学习了两种在图像上应用水印的方法。这些方法是 −
- 应用文本水印
- 应用图像水印
应用文本水印
我们使用 OpenCV 函数 putText 将文本水印应用于图像。它可以在 Core 包下找到。它的语法如下 −
Core.putText(source, Text, Point, fontFace ,fontScale , color);
该函数的参数说明如下 −
Sr.No. | 参数 &描述 |
---|---|
1 |
source 它是源图像。 |
2 |
Text 它是将出现在图像上的字符串文本。 |
3 |
Point 它是文本应出现在图像上的点。 |
4 |
fontFace 字体类型。例如 − FONT_HERSHEY_SIMPLEX、FONT_HERSHEY_PLAIN、FONT_HERSHEY_COMPLEX 等。 |
5 |
fontScale 字体比例因子,乘以字体特定的基本大小。 |
6 |
color 文本颜色。 |
除了 putText 方法之外,Core 类还提供了其他方法。它们被简要描述 −
Sr.No. | 方法 &描述 |
---|---|
1 |
normalize(Mat src, Mat dst, double alpha, double beta, int norm_type) 它规范化数组的范数或值范围。 |
2 |
perspectiveTransform(Mat src, Mat dst, Mat m) 它执行向量的透视矩阵变换。 |
3 |
phase(Mat x, Mat y, Mat angle) 它计算 2D 的旋转角度向量。 |
4 |
rectangle(Mat img, Point pt1, Point pt2, Scalar color) 它绘制一个简单、粗或填充的直立矩形。 |
5 |
reduce(Mat src, Mat dst, int dim, int rtype, int dtype) 它将矩阵简化为向量。 |
6 |
transform(Mat src, Mat dst, Mat m) 它对每个数组元素执行矩阵变换。 |
示例
以下示例演示了如何使用 Core 类将文本水印应用于图像 −
import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class Main { public static void main( String[] args ) { try{ System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread("digital_image_processing.jpg", Highgui.CV_LOAD_IMAGE_COLOR); Mat destination = new Mat(source.rows(),source.cols(), source.type()); Core.putText(source, "Tutorialspoint.com", new Point (source.rows()/2,source.cols()/2), Core.FONT_ITALIC,new Double(1),new Scalar(255)); Highgui.imwrite("watermarked.jpg", source); } catch (Exception e) { System.out.println("Error: "+e.getMessage()); } } }
输出
执行给定的代码时,将看到以下输出 −
原始图像

带文本水印的图像

在图像上应用图像水印
我们将使用 OpenCV 函数 addWeighted 将图像水印应用于图像。它可以在 Core 包下找到。其语法如下 −
Core.addWeighted(InputArray src1, alpha, src2 (Watermark image), beta, gamma, OutputArray dst);
此函数的参数如下所述 −
Sr.No. | 参数 &描述 |
---|---|
1 |
src1 第一个输入数组。 |
2 |
alpha 第一个数组元素的权重。 |
3 |
src2 第二个输入数组,大小和通道数与 src1 相同。 |
4 |
beta 第二个第二个数组元素。 |
5 |
gamma 它是添加到每个总和的标量。 |
6 |
dst 它是具有与输入数组相同大小和通道数的输出数组。 |
示例
以下示例演示了如何使用 Core 类将图像水印应用于图像 −
import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; public class Main { public static void main( String[] args ) { try{ System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); Mat source = Highgui.imread("digital_image_processing.jpg", Highgui.CV_LOAD_IMAGE_COLOR); Mat waterMark = Highgui.imread("watermark.png", Highgui.CV_LOAD_IMAGE_COLOR); Rect ROI = new Rect(waterMark.rows() * 4,waterMark.cols(), waterMark.cols(),waterMark.rows()); Core.addWeighted(source.submat(ROI), 0.8, waterMark, 0.2, 1, source.submat(ROI)); Highgui.imwrite("watermarkedImage.jpg", source); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
输出
执行给定的代码时,将看到以下输出 −
原始图像

水印图像

带水印的图像
