c# - 这个图像相似度代码线程安全吗?
问题描述
我正在寻求帮助检查 2 张图像之间的相似性,我遇到了这个 SO 帖子,它引用了这个 SO 帖子。虽然这两个帖子都有有用的信息,但我决定使用在此站点上找到的方法- 这非常简单。
考虑到这一背景,我决定使用以下方法来比较 2 张图像。我的问题是——这种方法应该很好地扩展吗?规模好我的意思是它是线程安全的吗?如果它不是线程安全的,我应该更改什么以使其线程安全?
using System;
using System.Drawing;
class Program
{
static void Main()
{
Bitmap img1 = new Bitmap("Lenna50.jpg");
Bitmap img2 = new Bitmap("Lenna100.jpg");
if (img1.Size != img2.Size)
{
Console.Error.WriteLine("Images are of different sizes");
return;
}
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
}
更新:这是带有线程代码的更新类。我没有太多使用线程。当我在本地测试时它工作正常。我想知道这是否是一种可以使用的方法。我也想知道我是否应该使用 Thread.Sleep 以便该线程不会阻塞其他线程。
using System;
using System.Drawing;
using System.Threading;
public class CompareImages
{
public static string statusmsg = string.Empty;
public static void CheckImages(string imagepath1, string imagepath2)
{
// Create thread
Thread thread = new Thread(() => CheckImageDiff(imagepath1, imagepath2));
thread.Start();
thread.Join(); // Does this mean I don't have to do Thread.Sleep(__)?
}
public static void CheckImageDiff(string path1, string path2)
{
Bitmap img1 = new Bitmap(path1);
Bitmap img2 = new Bitmap(path2);
if (img1.Size != img2.Size)
{
statusmsg = "Images are of different sizes. Images should be the same size.";
}
else
{
float diff = 0;
for (int y = 0; y < img1.Height; y++)
{
for (int x = 0; x < img1.Width; x++)
{
Color pixel1 = img1.GetPixel(x, y);
Color pixel2 = img2.GetPixel(x, y);
diff += Math.Abs(pixel1.R - pixel2.R);
diff += Math.Abs(pixel1.G - pixel2.G);
diff += Math.Abs(pixel1.B - pixel2.B);
}
}
statusmsg = "diff: {0} %";
statusmsg = string.Format(statusmsg, 100 * (diff / 255) / (img1.Width * img1.Height * 3));
}
// Write status msg to database or make available to other method...
}
}
解决方案
推荐阅读
- c# - 在 .NET Core 3 中获取嵌入式资源内容的类型安全方法
- android - 从使用 camera2API 拍摄的原始图像中检索数据
- c# - Asp.Net Mvc Core 中的无会话控制器
- reactjs - 如何通过 Reactjs 中的快速重定向方法发送上下文?
- mysql - 对有限制的 mysql 查询进行全表扫描
- sql - Postgres:是否可以在文本或 serach 中转换 bytea 类型(pdf)?
- javascript - 无法过滤类似数组的对象
- php - 如何在 cakephp 3.7 中检查数据库连接是否存在并关闭连接并重新连接到数据库
- git - git clone 时连接中出现未知的 SSL 协议错误
- javascript - 为什么创建空数组 Javascript 在输出中显示 [(...)] 而不是 (...)?