Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách vẽ các hình học trên ảnh bằng thư viện OpenCV Java

Lớp Imgproc trong gói org.opencv.imgproc cung cấp nhiều phương thức vẽ hình học:

Hình dạngPhương thức & Mô tả
ElipDùng ellipse().
Hình trònDùng circle().
Hình chữ nhậtDùng rectangle().
Đa giácDùng fillPoly() hoặc polylines().
Đường thẳngDùng line().

Ví dụ vẽ nhiều hình học

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.highgui.HighGui;
import java.util.ArrayList;
import java.util.List;

public class DrawingGeometricalShapes {
    public static void main(String args[]) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat src = Imgcodecs.imread("D:\\blank.jpg");
        Scalar color = new Scalar(0, 0, 120);
        // Vẽ hình tròn tô đặc
        Imgproc.circle(src, new Point(75, 65), 40, color, Imgproc.FILLED);
        // Vẽ elip tô đặc
        Imgproc.ellipse(src, new RotatedRect(new Point(330, 60), new Size(100, 65), 180), color, Imgproc.FILLED);
        // Vẽ đường thẳng
        Imgproc.line(src, new Point(540, 30), new Point(540, 90), color, 5);
        // Vẽ đa giác tô đặc
        List<MatOfPoint> list = new ArrayList<>();
        list.add(new MatOfPoint(
            new Point(410, 60), new Point(430, 30),
            new Point(470, 30), new Point(490, 60),
            new Point(470, 100), new Point(430, 100)));
        Imgproc.fillPoly(src, list, color, 8);
        // Vẽ hình chữ nhật tô đặc
        Imgproc.rectangle(src, new Point(150, 30), new Point(250, 95), color, Imgproc.FILLED);
        HighGui.imshow("Geometrical shapes", src);
        HighGui.waitKey();
    }
}

Kết quả

Cách vẽ các hình học trên ảnh bằng thư viện OpenCV Java