OpenCVSharp 笔记17 鼠标操作与响应

        #region 鼠标操作与响应
        static Mat tempMat;
        static void Main(string[] args)//
        {
            MouseCallback draw = new MouseCallback(draw_circle);
            Mat src = Cv2.ImRead("lenna.png", ImreadModes.AnyColor);
            Cv2.ImShow("src image", src);
            tempMat = new Mat(src.Size(), src.Type());
            Cv2.CopyTo(src,tempMat);
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(src);
            IntPtr ptr = System.Runtime.InteropServices.GCHandle.ToIntPtr(handle);

            Cv2.SetMouseCallback("src image", draw, ptr);
            Cv2.WaitKey();
        }

        static Point sp = new Point(-1, -1);
        static Point ep = new Point(-1, -1);
        public static void draw_circle(MouseEventTypes @event, int x, int y, MouseEventFlags flags, IntPtr userData)
        {
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.FromIntPtr(userData);
            Mat src = (Mat)handle.Target;
            if (@event == MouseEventTypes.LButtonDown)
            {
                sp.X = x;
                sp.Y = y;
                Console.WriteLine("起点坐标 ({0},{1})", sp.X, sp.Y);
            }
            else if (@event == MouseEventTypes.LButtonUp)
            {
                ep.X = x;
                ep.Y = y;
                Console.WriteLine("终点坐标 ({0},{1})", ep.X, ep.Y);
                if (ep.X > sp.X && ep.Y > sp.Y)
                {
                    Cv2.Rectangle(src, sp, ep, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias, 0);//绘制矩形 参数1:操作图像 2:矩形左上点 3:矩形右下点 4:颜色 5:线宽  6:线型  7:缩放参数(0为不缩放)
                    Cv2.ImShow("ROI区域", src.SubMat(sp.Y, ep.Y, sp.X, ep.X));

                    Cv2.ImShow("src image", src);
                    sp.X = -1;
                    sp.Y = -1;
                }
            }
            else if (@event == MouseEventTypes.MouseMove && sp.X > 0 && sp.Y > 0)
            {
                ep.X = x;
                ep.Y = y;
                if (ep.X > sp.X && ep.Y > sp.Y)
                {
                    Cv2.CopyTo(tempMat,src);
                    Cv2.Rectangle(src, sp, ep, new Scalar(0, 0, 255), 2, LineTypes.AntiAlias, 0);//绘制矩形 参数1:操作图像 2:矩形左上点 3:矩形右下点 4:颜色 5:线宽  6:线型  7:缩放参数(0为不缩放)
                    Cv2.ImShow("src image", src);
                }
            }
        }
        #endregion

效果如下:

根据鼠标左键按下拖动然后松开的范围进行矩形绘制,矩形内区域图像会被截取出来显示

你可能感兴趣的:(OpenCVSharp,opencv)