You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Canny提取最大轮廓内部区域时遇CS0104引用歧义错误求解

解决Graphics命名空间冲突问题

你遇到的这个错误是典型的命名空间冲突——你的项目同时引用了System.Drawing和UnityEngine两个库,而这两个库恰好都包含名为Graphics的类,编译器没法自动判断你要使用哪一个。下面给你几个实用的解决办法:

首先先回顾下你的代码和报错信息:

你的代码

Rectangle rect = CvInvoke.BoundingRectangle(contours[largest_contour_index]); 
Bitmap target = new Bitmap(rect.Width, rect.Height); 
using (Graphics g = Graphics.FromImage(target)) { 
    g.DrawImage(imageInput, new Rectangle(0, 0, target.Width, target.Height), rect, GraphicsUnit.Pixel); 
} 
imageBox2.Image = imageInput;

报错信息

Error CS0104 'Graphics' is an ambiguous reference between 'System.Drawing.Graphics' and 'UnityEngine.Graphics'


方法一:明确指定完整命名空间

直接在代码里写出Graphics所属的完整命名空间,告诉编译器你要使用System.Drawing下的那个:

Rectangle rect = CvInvoke.BoundingRectangle(contours[largest_contour_index]); 
Bitmap target = new Bitmap(rect.Width, rect.Height); 
// 这里明确指定System.Drawing.Graphics
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(target)) { 
    g.DrawImage(imageInput, new Rectangle(0, 0, target.Width, target.Height), rect, System.Drawing.GraphicsUnit.Pixel); 
} 
imageBox2.Image = imageInput;

方法二:移除不必要的命名空间引用

如果你的项目根本不需要UnityEngine库的话,直接在代码顶部的using语句里删掉using UnityEngine;,或者在项目的引用列表中移除UnityEngine相关的引用。这样编译器就只会找到System.Drawing.Graphics,自然不会有歧义了。

方法三:给命名空间起别名

如果两个命名空间都需要保留,可以给其中一个起个别名,避免冲突:
在代码顶部添加别名声明:

using SDGraphics = System.Drawing.Graphics;
using SDUnit = System.Drawing.GraphicsUnit;

然后修改代码:

Rectangle rect = CvInvoke.BoundingRectangle(contours[largest_contour_index]); 
Bitmap target = new Bitmap(rect.Width, rect.Height); 
using (SDGraphics g = SDGraphics.FromImage(target)) { 
    g.DrawImage(imageInput, new Rectangle(0, 0, target.Width, target.Height), rect, SDUnit.Pixel); 
} 
imageBox2.Image = imageInput;

这三种方法都能解决你的问题,根据你的项目需求选一个最适合的就行~

内容的提问来源于stack exchange,提问作者Chaima Soltani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:15:48