[JAVA] Desktop: OpenCV Emboss For Rectangle

Goal
Test OpenCV emboss for rectangle.

OpenCV_EmbossForRectangle.java


import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import org.opencv.core.MatOfPoint;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class OpenCV_EmbossForRectangle {
    static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
    private JFrame frmjavaSwing;

    public int srcX=0;
    public int srcY=0;

    public int secondX=0;
    public int secondY=0;

    public Point innerP1;
    public Point innerP2;

    public Mat matWantToSave;

    public Mat EmbossArea1;
    public Mat EmbossArea2;
    public Mat EmbossArea3;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    OpenCV_EmbossForRectangle window = new OpenCV_EmbossForRectangle();
                    window.frmjavaSwing.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public OpenCV_EmbossForRectangle() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        final Mat source = Imgcodecs.imread(
                "D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\DSC_0836.jpg ");

        BufferedImage image=matToBufferedImage(source);

        frmjavaSwing = new JFrame();
        frmjavaSwing.setTitle("Relief ROI production Relief production practice");
        frmjavaSwing.setBounds(100, 100, 990, 395);
        frmjavaSwing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmjavaSwing.getContentPane().setLayout(null);

        final JLabel lblLocation = new JLabel("");
        lblLocation.setBounds(10, 10, 112, 25);
        frmjavaSwing.getContentPane().add(lblLocation);

        final JLabel lblLocation2 = new JLabel("");
        lblLocation2.setBounds(158, 10, 112, 25);
        frmjavaSwing.getContentPane().add(lblLocation2);

        JPanel panel = new JPanel();
        panel.setBounds(10, 45, 473, 301);
        frmjavaSwing.getContentPane().add(panel);

        final JLabel lblNewLabel = new JLabel("");
        panel.add(lblNewLabel);

        //Supervision mouse case,點 擊 2nd individual 點
        lblNewLabel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent arg0) {
                lblLocation2.setText("X:"+arg0.getX()+",Y:"+arg0.getY());

                setSecondX(arg0.getX());
                setSecondY(arg0.getY());

                BufferedImage newImage=matToBufferedImage(paintRectangle(arg0.getX(),arg0.getY()));
                lblNewLabel.setIcon(new ImageIcon(newImage));


            }
        });

        final JLabel lblRoi = new JLabel("");
        lblRoi.setBounds(494, 45, 478, 306);
        frmjavaSwing.getContentPane().add(lblRoi);


        lblNewLabel.setIcon(new ImageIcon(image));

        JButton btnNewButton = new JButton("擷tori ROI average and standing");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                getRoiAndEmboss();
                if (getEmbossArea1()!=null){

                    Mat source1 = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\DSC_0836.jpg ");
                    //Re-grabbing small copy to large
                    //Area1
                    Mat embossArea1=getEmbossArea1();//get Relief Area1 Block

                    //Tori Area1 and Area3 ROI area
                    Rect roi=new Rect(Math.min(getSrcX(),getSecondX()),Math.min(getSrcY(),getSecondY()),Math.abs(getSecondX()-getSrcX()),Math.abs(getSecondY()-getSrcY()));//Impossible Hihara Keidai,Small

                    //Paste source1
                    Mat destinationROI = source1.submat( roi );
                    embossArea1.copyTo( destinationROI , embossArea1);
                    //Area2
                    Mat embossArea2=getEmbossArea2();//get Relief Area2 Block
                    //Tori Area2 and Area3 ROI area
                    Rect tempInner=new Rect(getInnerP1(),getInnerP2());
                    //Paste source1
                    Mat innerMat=source1.submat( tempInner );
                    embossArea2.copyTo( innerMat , embossArea2);

                    //Area3
                    Mat embossArea3=getEmbossArea3();//get Relief Area3 Block
                    //Paste source1
                    embossArea3.copyTo( destinationROI , embossArea3);

                    BufferedImage image=matToBufferedImage(source1);
                    lblRoi.setText("");
                    lblRoi.setIcon(new ImageIcon(image));

                }else{
                    lblRoi.setText("Unregulated ROI block!");
                }

            }
        });
        btnNewButton.setBounds(278, 10, 150, 25);
        frmjavaSwing.getContentPane().add(btnNewButton);


        //Supervision mouse case,點 擊 1st individual 點
        lblNewLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                lblLocation2.setText("");
                lblLocation.setText("From the beginning:X:"+arg0.getX()+",Y:"+arg0.getY());
                setSrcX(arg0.getX());
                setSrcY(arg0.getY());
                BufferedImage newImage=matToBufferedImage(paintPoint(arg0.getX(),arg0.getY()));
                lblNewLabel.setIcon(new ImageIcon(newImage));
            }
        });



    }
    //繪 圖 at the first individual
    public Mat paintPoint(int x,int y){
        Mat src = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\DSC_0836.jpg ");
        Imgproc.circle(src, new Point(x,y), 2, new Scalar(0,55,255),2);
        return src;

    }
    //繪 ROI 區,Greedy or bas-relief
    public Mat paintRectangle(int x,int y){
        Mat src = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\DSC_0836.jpg ");
        Point srcPoint=new Point(getSrcX(),getSrcY());
        Imgproc.rectangle(src, srcPoint, new Point(x,y), new Scalar(0,0,255),2);
        setSecondX(x);
        setSecondY(y);
        return src;

    }
    //Relief 圖 ROI 區 變 Standing or floating
    public void getRoiAndEmboss(){
        Mat RoiMat;
        Mat MaskTemplate = null;
        Mat dst = new Mat();
        if(getSecondX()>0 && getSecondY()>0){
            Mat source=
                    Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\DSC_0836.jpg ");
            Rect roi=new Rect(new Point(getSrcX(),getSrcY()),new Point(getSecondX(),getSecondY()));

            RoiMat=source.submat(roi);
            // source.

            //area1-start,Hypotenuse on the upper left of the area 1,Upper right diagonal,Lower right hypotenuse
            //Oblique angle 45 degrees,Calculated radian
            double angleRad = 45*Math.PI / 180.0;   // convert angle to radians
            //Predefined 與 ROI same size,All white bush road model board
            MaskTemplate=new Mat(RoiMat.size(),CvType.CV_8UC1,new Scalar(0));

            int length = 25;//Relief or floating thickness
            Point direction = new Point(length * Math.cos(angleRad), length * Math.sin(angleRad)); // calculate direction

            //Polygon fillPoly Required materials
            List<MatOfPoint> allMatOfPoint=new ArrayList<MatOfPoint>();
            MatOfPoint mop1=new MatOfPoint();
            List<Point> allPoint1=new ArrayList<Point>();

            //area1 6 pieces,Circulation required
            allPoint1.add(new Point(0,0));//p1
            allPoint1.add(new Point(0 +direction.x*0.5,0 +direction.y*0.5));//p2
            allPoint1.add(new Point(RoiMat.width()-direction.x*0.5,0 +direction.y*0.5));//p3
            allPoint1.add(new Point(RoiMat.width()-direction.x*0.5,RoiMat.height()-direction.y*0.5));//p4
            allPoint1.add(new Point(RoiMat.width(),RoiMat.height()));//p5
            allPoint1.add(new Point(RoiMat.width(),0));//p6
            mop1.fromList(allPoint1);
            allMatOfPoint.add(mop1);
            Imgproc.fillPoly(MaskTemplate, allMatOfPoint,  new Scalar(255,255,255));//Completion filling,area1 white(255,255,255)

            //Polygon area1 mat
            Core.bitwise_and(RoiMat, RoiMat, dst,MaskTemplate);
            //area1 Meiryo Kasori
            dst.convertTo(dst, -1, 2, 50);
            //Construction global value,Demand for repatriation
            setEmbossArea1(dst);
            //area1-end

            //area2-start,Rectangle area 2 inner rectangular part
            Mat dst2 = new Mat();

            //inner rectangular part 份變 子 ROI
            Rect rectDst2=new Rect(new Point(0 +direction.x*0.5,0 +direction.y*0.5),new Point(RoiMat.width()-direction.x*0.5,RoiMat.height()-direction.y*0.5));
            //Construction global value,Demand for repatriation
            setInnerP1(getSrcX()+(int)direction.x*0.5,0 +getSrcY()+(int)direction.y*0.5);
            setInnerP2(getSrcX()+RoiMat.width()-direction.x*0.5,getSrcY()+RoiMat.height()-direction.y*0.5);
            //Arrival area2 inner rectangular part,And because Mat
            dst2=RoiMat.submat(rectDst2);
            //Construction global value,Demand for repatriation
            setEmbossArea2(dst2);


            //area3-start,Hypotenuse on the upper left of the area 1,Lower left diagonal,Lower right hypotenuse
            Mat dst3 = new Mat();
            RoiMat=source.submat(roi);
            //Predefined 與 ROI same size,All white bush road model board
            MaskTemplate=new Mat(RoiMat.size(),CvType.CV_8UC1,new Scalar(0));

            //Polygon fillPoly Required materials
            allMatOfPoint=new ArrayList<MatOfPoint>();
            MatOfPoint mop2=new MatOfPoint();
            List<Point> allPoint2=new ArrayList<Point>();
            //Collective owned coordinates,area3 6 pieces,Circulation required
            allPoint2.add(new Point(0,0));//p1
            allPoint2.add(new Point(0 +direction.x*0.5,0 +direction.y*0.5));//p2
            allPoint2.add(new Point(0 +direction.x*0.5,RoiMat.height()-direction.y*0.5));//p3
            allPoint2.add(new Point(RoiMat.width()-direction.x*0.5,RoiMat.height()-direction.y*0.5));//p4
            allPoint2.add(new Point(RoiMat.width(),RoiMat.height()));//p5
            allPoint2.add(new Point(0,RoiMat.height()));//p6
            mop2.fromList(allPoint2);
            allMatOfPoint.add(mop2);

            //Completion filling,White for area3(255,255,255)
            Imgproc.fillPoly(MaskTemplate, allMatOfPoint,  new Scalar(255,255,255));
            //Polygonal area3 mat
            //Core.add(RoiMat, RoiMat, dst3,MaskTemplate);
            Core.bitwise_and(RoiMat, RoiMat, dst3,MaskTemplate);
            //area3 ash darkening
            dst3.convertTo(dst3, -1, 0.5, -50);
            //Construction global value,Demand for repatriation
            setEmbossArea3(dst3);
            //area3-end

        }else{
            RoiMat=null;
        }
    }




    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 int getSrcX() {
        return srcX;
    }

    public void setSrcX(int srcX) {
        this.srcX = srcX;
    }

    public int getSrcY() {
        return srcY;
    }

    public void setSrcY(int srcY) {
        this.srcY = srcY;
    }

    public int getSecondX() {
        return secondX;
    }

    public void setSecondX(int secondX) {
        this.secondX = secondX;
    }

    public int getSecondY() {
        return secondY;
    }

    public void setSecondY(int secondY) {
        this.secondY = secondY;
    }

    public Mat getMatWantToSave() {
        return matWantToSave;
    }

    public void setMatWantToSave(Mat matWantToSave) {
        this.matWantToSave = matWantToSave;
    }

    public Mat getEmbossArea1() {
        return EmbossArea1;
    }

    public void setEmbossArea1(Mat embossArea1) {
        EmbossArea1 = embossArea1;
    }

    public Mat getEmbossArea2() {
        return EmbossArea2;
    }

    public void setEmbossArea2(Mat embossArea2) {
        EmbossArea2 = embossArea2;
    }

    public Mat getEmbossArea3() {
        return EmbossArea3;
    }

    public void setEmbossArea3(Mat embossArea3) {
        EmbossArea3 = embossArea3;
    }

    public Point getInnerP1() {
        return innerP1;
    }

    public void setInnerP1(double d,double e) {
        Point tmpPoint=new Point(d,e);
        this.innerP1 = tmpPoint;
    }

    public Point getInnerP2() {
        return innerP2;
    }

    public void setInnerP2(double d,double e) {
        Point tmpPoint=new Point(d,e);
        this.innerP2 = tmpPoint;
    }

}
Result
![opencv_emboss_rectangle.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/276243/1ba4b6c2-50d3-ef17-c712-ea51dccb974e.jpeg)

Recommended Posts

Desktop: OpenCV Emboss For Rectangle
Desktop: OpenCV Emboss
Desktop: OpenCV Rectangle
Desktop: OpenCV EqualizeHist For YUV
Desktop: OpenCV Flood Fill For Fun
Desktop: OpenCV Threshold
Desktop: OpenCV BilateralFilterBlur
Desktop: OpenCV Dilate
Desktop: OpenCV Rectangle Check Inside By ClipLine
Desktop: OpenCV Affine
Desktop: OpenCV CLAHE
Desktop: OpenCV Ellipse2Poly
Desktop: OpenCV HDR
Desktop: OpenCV Denoise
Desktop: OpenCV Concat
Desktop: OpenCV Mosaic
Desktop: OpenCV Erode
Desktop: OpenCV Denoise
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 Illumination Change
Desktop: OpenCV Add WaterMark
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 Add Broad
Desktop: OpenCV Robinson Filter
Desktop: OpenCV record video
Desktop: OpenCV Texture Flatting
Desktop: OpenCV Flood Fill
Desktop: OpenCV color space
Desktop: OpenCV SqrBox Filter
Desktop: OpenCV resize image