现在遇到一个需求,用Unity里用图片生成Gcode

告知硬件让它去画出来

翻阅了一些资料最后决定用OpenCV去做

下图左侧是生成的Gcode文件 右侧是要画的图片

话不多说直接代码

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 millimetersn");
        sb.Append("G90 ; Use absolute coordinatesn");
        sb.Append("M3 S0 ; Turn off lasern");

        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.00n", firstPoint.x * 0.5, firstPoint.y * 0.5));
            sb.Append("M3 S1000 ; Turn on laser to start cuttingn");

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

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

        // 结束G-code
        sb.Append("M5 ; Stop laser/spindlen");
        sb.Append("G0 X0 Y0 ; Return to homen");

        return sb.ToString();
    }
}

原文地址:https://blog.csdn.net/weixin_53501436/article/details/134806025

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_46864.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注