⭐ Use the OpenCv plug-in in Unity to generate Gcode from images

Now I encounter a need to use pictures to generate Gcode in Unity.

Tell the hardware to draw it

After reading some information, I finally decided to use OpenCV to do it.

The left side of the picture below is the generated Gcode file, and the right side is the picture to be drawn.

Without further ado, let’s get straight to the code.

using System.IO;
using UnityEngine;
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.ImgprocModule;
using OpenCVForUnity.UnityUtils;
using System.Collections.Generic;
using OpenCVForUnity.ImgcodecsModule;

public class ImageToGCode : MonoBehaviour
{
    void Start()
    {
        // 加载图像
        Mat src = Imgcodecs.imread("C:/Users/Administrator/Desktop/edc86edc_E375522_2c6a6d08.png");

        // 转换为灰度图像
        Mat gray = new Mat();
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);

        // 应用二值化
        Mat binary = new Mat();
        Imgproc.threshold(gray, binary, 128, 255, Imgproc.THRESH_BINARY_INV);

        // 边缘检测
        Mat edges = new Mat();
        Imgproc.Canny(binary, edges, 50, 150, 3, false);

        // 查找轮廓
        List<MatOfPoint> contours = new List<MatOfPoint>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(edges, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

        Debug.Log(contours.Count+"<=数量");
        // 将轮廓转换成G-code
        string gcode = generateGCode(contours);

        // 输出G-code到文件
        using (StreamWriter writer = new StreamWriter("C:/Users/Administrator/Desktop/output001.gcode"))
        {
            writer.Write(gcode);
        }
    }

    private static string generateGCode(List<MatOfPoint> contours)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        // G-code初始化,设置单位等
        sb.Append("G21 ; Set units to millimeters\n");
        sb.Append("G90 ; Use absolute coordinates\n");
        sb.Append("M3 S0 ; Turn off laser\n");

        for (int i = 0; i < contours.Count; i++)
        {
            MatOfPoint contour = contours[i];

            // 获取轮廓的第一个点
            Point[] points = contour.toArray();
            Point firstPoint = points[0];
            sb.Append(string.Format("G0 X{0:F3} Y{1:F3} F1500.00\n", firstPoint.x * 0.5, firstPoint.y * 0.5));
            sb.Append("M3 S1000 ; Turn on laser to start cutting\n");

            // 遍历轮廓的其他点
            for (int j = 1; j < points.Length; j++)
            {
                Point point = points[j];
                sb.Append(string.Format("G1 X{0:F3} Y{1:F3} F1500.00\n", point.x * 0.5, point.y * 0.5));
            }

            // 关闭激光并移动到下一个轮廓的起始点
            sb.Append("M3 S0 ; Turn off laser\n");
        }

        // 结束G-code
        sb.Append("M5 ; Stop laser/spindle\n");
        sb.Append("G0 X0 Y0 ; Return to home\n");

        return sb.ToString();
    }
}

Guess you like

Origin blog.csdn.net/weixin_53501436/article/details/134806025