[JAVA] Desktop: OpenCV Add WaterMark

Goal
Test OpenCV add watermark.

OpenCV_Chinese_WaterMark.java


import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class OpenCV_Chinese_WaterMark {

    static {System.loadLibrary(Core.NATIVE_LIBRARY_NAME);}
    private JFrame frmjavaSwing;
    public BufferedImage globalBufferedImage;

    /**
     *  Launch the application.
     */
    public static void main(String[] args){
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try{
                    OpenCV_Chinese_WaterMark window = new OpenCV_Chinese_WaterMark();
                    window.frmjavaSwing.setVisible(true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     * @throws  IOException
     */
    public OpenCV_Chinese_WaterMark() throws IOException{
        init();
    }


    /**
     *  Init the contents of the frame.
     * @throws  IOException
     */
    private void  init() throws IOException{
        Mat source =  Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\lena.jpg ");
        BufferedImage image=matToBufferedImage(source);

        frmjavaSwing = new JFrame();
        frmjavaSwing.setTitle("opencv Chinese floating watermark practice,English Fumiya applied");
        frmjavaSwing.setBounds(100, 100, 639, 356);
        frmjavaSwing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmjavaSwing.getContentPane().setLayout(null);

        final JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setBounds(10, 64, 595, 255);
        lblNewLabel.setIcon(new ImageIcon(image));
        frmjavaSwing.getContentPane().add(lblNewLabel);

        JLabel lblNewLabel_1 = new JLabel("Transparency:");
        lblNewLabel_1.setBounds(10, 21, 46, 15);
        frmjavaSwing.getContentPane().add(lblNewLabel_1);

        final JLabel lblshowAlpha = new JLabel("1.0");
        lblshowAlpha.setBounds(235, 21, 57, 15);
        frmjavaSwing.getContentPane().add(lblshowAlpha);

        final JSlider slider = new JSlider();
        slider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent arg0) {

                lblshowAlpha.setText((float)slider.getValue()/10+"");
                BufferedImage image=HandleWaterMark((float)slider.getValue()/10);
                lblNewLabel.setIcon(new ImageIcon(image));
                setGlobalBufferedImage(image);

            }
        });
        slider.setValue(10);
        slider.setMaximum(10);
        slider.setBounds(54, 12, 161, 24);
        frmjavaSwing.getContentPane().add(slider);

        JButton btnNewButton = new JButton("Save");
        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                BufferedImage image=getGlobalBufferedImage();
                if (image!=null){
                    try {
                        ImageIO.write(image, "png", new File(
                                "D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\lena_watermark.jpg "));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
        });
        btnNewButton.setBounds(277, 16, 89, 25);
        frmjavaSwing.getContentPane().add(btnNewButton);

    }

    //English Fumiya applied
    public BufferedImage HandleWaterMark(float alpha){
        Mat source =  Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\lena.jpg ");
        BufferedImage image=matToBufferedImage(source);
        Graphics2D g2d = image.createGraphics();
        System.out.println(alpha);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));//Setting transparency
        g2d.setColor(new Color(0,0,0));//Character color
        g2d.setFont(new Font("Wang Han sect", 36, 30));//Character type,Character typestyle,Large and small
        //g2d.setFont(new Font("Wang Han Sokantei Ryusei", 36, 20));//Character type,Character typestyle,Large and small
        g2d.drawString("Chengcing Lake", 10,230);//Character position
        g2d.dispose();
        return image;
    }

    public BufferedImage matToBufferedImage(Mat matrix) {
        int cols = matrix.cols();
        int rows = matrix.rows();
        int elemSize = (int)matrix.elemSize();
        byte[] data = new byte[cols * rows * elemSize];
        int type;
        matrix.get(0, 0, data);
        switch (matrix.channels()) {
            case 1:
                type = BufferedImage.TYPE_BYTE_GRAY;
                break;
            case 3:
                type = BufferedImage.TYPE_3BYTE_BGR;
                // bgr to rgb
                byte b;
                for(int i=0; i<data.length; i=i+3) {
                    b = data[i];
                    data[i] = data[i+2];
                    data[i+2] = b;
                }
                break;
            default:
                return null;
        }
        BufferedImage image2 = new BufferedImage(cols, rows, type);
        image2.getRaster().setDataElements(0, 0, cols, rows, data);
        return image2;
    }

    public BufferedImage getGlobalBufferedImage() {
        return globalBufferedImage;
    }

    public void setGlobalBufferedImage(BufferedImage globalBufferedImage) {
        this.globalBufferedImage = globalBufferedImage;
    }
}
Result
![lena_watermark.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/276243/8ec213ea-f463-0c79-7e57-3ced815a8b63.jpeg)

Recommended Posts

Desktop: OpenCV Add WaterMark
Desktop: OpenCV Add Broad
Desktop: OpenCV Threshold
Desktop: OpenCV BilateralFilterBlur
Desktop: OpenCV Dilate
Desktop: OpenCV Expand
Desktop: OpenCV Affine
Desktop: OpenCV Emboss
Desktop: OpenCV CLAHE
Desktop: OpenCV Ellipse2Poly
Desktop: OpenCV HDR
Desktop: OpenCV Polylines
Desktop: OpenCV Denoise
Desktop: OpenCV Sharpness
Desktop: OpenCV Concat
Desktop: OpenCV OpenCV_SalonUseBlurAddWeighted
Desktop: OpenCV Mosaic
Desktop: OpenCV Erode
Desktop: OpenCV Denoise
Desktop: OpenCV Rectangle
Desktop: OpenCV Watershed
Desktop: OpenCV Text
Desktop: OpenCV Inpaint
Desktop: OpenCV NormalizeBlur
Desktop: OpenCV StereoSGBM
Desktop: OpenCV Spot
Desktop: OpenCV Canny
Desktop: OpenCV Denoise3
Desktop: OpenCV Histogram
Desktop: OpenCV Dft
Desktop: OpenCV Decolor
Desktop: OpenCV FaceDetector
Desktop: OpenCV Denoise2
Desktop: OpenCV StereoBM
Desktop: OpenCV Kirsch Filter
Desktop: OpenCV Laplacian Filter 2
Desktop: OpenCV Illumination Change
Desktop: OpenCV Fill ConvexPoly
Desktop: OpenCV Grab Cut
Desktop: OpenCV Sharpness Gui
Desktop: OpenCV Color Change
Desktop: OpenCV Freichennel Filter
Desktop: OpenCV Adaptive Threshold
Desktop: OpenCV Draw Circle
Desktop: OpenCV Fill Poly
Desktop: OpenCV Mean Filter
Desktop: OpenCV Java Repository
Desktop: OpenCV Sobel Filter2
Desktop: OpenCV pyrMeanShift Filter
Desktop: OpenCV OpticalFlow PyrLK
Desktop: OpenCV Virtual Piano
Desktop: OpenCV merge Picture
Desktop: OpenCV Scharr Filter
Desktop: Opencv webcam preview
Desktop: OpenCV Laplacian Filter
Desktop: OpenCV Median Blur
Desktop: OpenCV Robinson Filter
Desktop: OpenCV record video
Desktop: OpenCV Texture Flatting
Desktop: OpenCV Flood Fill
Desktop: OpenCV color space