首页 > 解决方案 > 这个图像相似度代码线程安全吗?

问题描述

我正在寻求帮助检查 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#image-processingthread-safety

解决方案


推荐阅读