【发布时间】:2018-10-05 07:57:30
【问题描述】:
我用 Python 编写了一个运行良好的解决方案,但需要安装多个库和大量的官僚设置才能工作。我决定在 Visual Studio Community 2017 上使用 C# 中的 GUI 构建它,但在第一个成功的函数中,结果比 Python 慢得多。哪个 IMO 实际上应该更快。
代码本质上只是在大海捞针图像搜索中做一个针,通过从一个文件夹中获取所有图像并在大海捞针中测试每个针(总共 60 个图像),在 python 中我返回字符串,但在 C# 中我是仅打印。
我的 Python 代码如下:
def getImages(tela):
retorno = []
folder = 'Images'
img_rgb = cv2.imread(tela)
for filename in os.listdir(folder):
template = cv2.imread(os.path.join(folder,filename))
w, h = template.shape[:-1]
res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
threshold = .96
loc = np.where(res >= threshold)
if loc[0]>0:
retorno.append(filename[0]+filename[1].lower())
if len(retorno)> 1:
return retorno
在 C# 中:
Debug.WriteLine(ofd.FileName);
Image<Bgr, byte> source = new Image<Bgr, byte>(ofd.FileName);
string filepath = Directory.GetCurrentDirectory().ToString()+"\\Images";
DirectoryInfo d = new DirectoryInfo(filepath);
var files = d.GetFiles();
foreach (var fname in files){
Image<Bgr, byte> template = new Image<Bgr, byte>(fname.FullName);
Image<Gray, float> result = source.MatchTemplate(template, Emgu.CV.CvEnum.TemplateMatchingType.CcoeffNormed);
double[] minValues, maxValues;
Point[] minLocations, maxLocations;
result.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
if (maxValues[0] > 0.96) {
Debug.WriteLine(fname);
}
}
我没有测量每个之间经过的时间,但我可以说 C# 中的结果大约需要 3 秒,Python 中大约需要 100 毫秒。
还有优化的空间,如果有人想提出任何改进建议,欢迎提出。
【问题讨论】:
-
您想只查找一张图片还是所有张图片匹配? Python 代码仅找到一张图像。 C# 代码将找到所有匹配项
-
BTW Emgu 是 Python 使用的同一个 OpenCV 库的包装器。如果两个程序都执行相同的操作,您应该不会看到任何显着差异。如果在每种情况下都使用并行处理,您可以提高性能。在 C# 中,您可以使用例如 PLINQ 或 Parallel.ForEach
标签: c# python .net image-processing image-recognition