【问题标题】:Compare similarity of images using OpenCV with Python使用 OpenCV 和 Python 比较图像的相似性
【发布时间】:2012-11-03 00:19:04
【问题描述】:

我正在尝试将一张图片与其他图片列表进行比较,并返回该列表中相似度高达 70% 的图片选择(如 Google 搜索图片)。

我在this post 中获取此代码并根据我的上下文进行更改

# Load the images
img =cv2.imread(MEDIA_ROOT + "/uploads/imagerecognize/armchair.jpg")

# Convert them to grayscale
imgg =cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# SURF extraction
surf = cv2.FeatureDetector_create("SURF")
surfDescriptorExtractor = cv2.DescriptorExtractor_create("SURF")
kp = surf.detect(imgg)
kp, descritors = surfDescriptorExtractor.compute(imgg,kp)

# Setting up samples and responses for kNN
samples = np.array(descritors)
responses = np.arange(len(kp),dtype = np.float32)

# kNN training
knn = cv2.KNearest()
knn.train(samples,responses)

modelImages = [MEDIA_ROOT + "/uploads/imagerecognize/1.jpg", MEDIA_ROOT + "/uploads/imagerecognize/2.jpg", MEDIA_ROOT + "/uploads/imagerecognize/3.jpg"]

for modelImage in modelImages:

    # Now loading a template image and searching for similar keypoints
    template = cv2.imread(modelImage)
    templateg= cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
    keys = surf.detect(templateg)

    keys,desc = surfDescriptorExtractor.compute(templateg, keys)

    for h,des in enumerate(desc):
        des = np.array(des,np.float32).reshape((1,128))

        retval, results, neigh_resp, dists = knn.find_nearest(des,1)
        res,dist =  int(results[0][0]),dists[0][0]


        if dist<0.1: # draw matched keypoints in red color
            color = (0,0,255)

        else:  # draw unmatched in blue color
            #print dist
            color = (255,0,0)

        #Draw matched key points on original image
        x,y = kp[res].pt
        center = (int(x),int(y))
        cv2.circle(img,center,2,color,-1)

        #Draw matched key points on template image
        x,y = keys[h].pt
        center = (int(x),int(y))
        cv2.circle(template,center,2,color,-1)



    cv2.imshow('img',img)
    cv2.imshow('tm',template)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

我的问题是,如何将图像与图像列表进行比较并仅获得相似的图像?有什么方法可以做到吗?

【问题讨论】:

    标签: python opencv computer-vision


    【解决方案1】:

    我建议您查看图像之间的推土机距离 (EMD)。 该指标让人感觉将标准化灰度图像转换为另一个灰度图像有多难,但可以推广到彩色图像。可以在以下论文中找到对该方法的非常好的分析:

    robotics.stanford.edu/~rubner/papers/rubnerIjcv00.pdf

    它既可以在整个图像上完成,也可以在直方图上完成(这确实比整个图像方法更快)。我不确定哪种方法可以进行完整的图像比较,但对于直方图比较,您可以使用 cv.CalcEMD2 函数。

    唯一的问题是这个方法没有定义相似度的百分比,而是一个你可以过滤的距离。

    我知道这不是一个完整的工作算法,但仍然是它的基础,所以我希望它有所帮助。

    编辑:

    这是对 EMD 原则上如何工作的恶搞。主要思想是有两个归一化矩阵(两个灰度图像除以它们的总和),并定义一个通量矩阵,描述如何将灰度从一个像素移动到另一个像素以获得第二个图像(甚至可以定义对于非标准化的,但更困难)。

    在数学术语中,流矩阵实际上是一个四维张量,它给出了从旧图像的点 (i,j) 到新图像的点 (k,l) 的流,但是如果您将图像展平,您可以将其转换为普通矩阵,只是更难阅读。

    这个流矩阵有三个约束:每一项都应该是正数,每行之和应该返回相同的目标像素值,每列之和应该返回起始像素的值。

    鉴于此,您必须最小化转换成本,该成本由 (i,j) 到 (k,l) 的每个流的乘积之和对于 (i,j) 和 (k, l)。

    文字看起来有点复杂,下面是测试代码。逻辑是正确的,我不确定为什么 scipy 求解器会抱怨它(你应该看看 openOpt 或类似的东西):

    #original data, two 2x2 images, normalized
    x = rand(2,2)
    x/=sum(x)
    y = rand(2,2)
    y/=sum(y)
    
    #initial guess of the flux matrix
    # just the product of the image x as row for the image y as column
    #This is a working flux, but is not an optimal one
    F = (y.flatten()*x.flatten().reshape((y.size,-1))).flatten()
    
    #distance matrix, based on euclidean distance
    row_x,col_x = meshgrid(range(x.shape[0]),range(x.shape[1]))
    row_y,col_y = meshgrid(range(y.shape[0]),range(y.shape[1]))
    rows = ((row_x.flatten().reshape((row_x.size,-1)) - row_y.flatten().reshape((-1,row_x.size)))**2)
    cols = ((col_x.flatten().reshape((row_x.size,-1)) - col_y.flatten().reshape((-1,row_x.size)))**2)
    D = np.sqrt(rows+cols)
    
    D = D.flatten()
    x = x.flatten()
    y = y.flatten()
    #COST=sum(F*D)
    
    #cost function
    fun = lambda F: sum(F*D)
    jac = lambda F: D
    #array of constraint
    #the constraint of sum one is implicit given the later constraints
    cons  = []
    #each row and columns should sum to the value of the start and destination array
    cons += [ {'type': 'eq', 'fun': lambda F:  sum(F.reshape((x.size,y.size))[i,:])-x[i]}     for i in range(x.size) ]
    cons += [ {'type': 'eq', 'fun': lambda F:  sum(F.reshape((x.size,y.size))[:,i])-y[i]} for i in range(y.size) ]
    #the values of F should be positive
    bnds = (0, None)*F.size
    
    from scipy.optimize import minimize
    res = minimize(fun=fun, x0=F, method='SLSQP', jac=jac, bounds=bnds, constraints=cons)
    

    变量 res 包含最小化的结果......但正如我所说,我不确定它为什么抱怨奇异矩阵。

    这个算法唯一的问题是速度不是很快,所以不可能按需做,但你必须耐心地在创建数据集时执行它并将结果存储在某个地方

    【讨论】:

    • 我会阅读这个文档,但对我来说,这些算法和图像处理对我来说是非常新的。我知道没有针对我的上下文指示比较直方图,我需要使用 SURF 或 SIFT 来执行此操作,但我希望看到一些代码以更清楚地理解这一点
    【解决方案2】:

    您正在着手处理一个大问题,称为“基于内容的图像检索”或 CBIR。这是一个庞大而活跃的领域。尽管有很多技术都取得了不同程度的成功,但目前还没有完成的算法或标准方法。

    即使是 Google 图片搜索(目前)还没有这样做 - 他们进行基于文本的图片搜索 - 例如,在页面中搜索与您搜索的文本类似的文本。 (而且我确信他们正在使用 CBIR;它是许多图像处理研究人员的圣杯)

    如果您的截止日期很紧,或者需要尽快完成这项工作......哎呀。

    这里有大量关于该主题的论文:

    http://scholar.google.com/scholar?q=content+based+image+retrieval

    通常你需要做几件事:

    1. 提取特征(在本地兴趣点,或全局,或以某种方式,SIFT、SURF、直方图等)
    2. 集群/构建图像分布模型

    这可能涉及feature descriptorsimage gistsmultiple instance learning。等等

    【讨论】:

      【解决方案3】:

      我可能在 2 年前使用 Python/Cython 编写了一个程序来做一些非常相似的事情。后来我将其重写为 Go 以获得更好的性能。基本思想来自findimagedupesIIRC。

      它基本上为每个图像计算一个“指纹”,然后比较这些指纹以匹配相似的图像。

      通过将图像大小调整为 160x160、将其转换为灰度、添加一些模糊、对其进行标准化,然后将其调整为 16x16 单色来生成指纹。最后你有 256 位的输出:那是你的指纹。使用convert 很容易做到这一点:

      convert path[0] -sample 160x160! -modulate 100,0 -blur 3x99 \
          -normalize -equalize -sample 16x16 -threshold 50% -monochrome mono:-
      

      path[0] 中的[0] 仅用于提取动画 GIF 的第一帧;如果您对此类图像不感兴趣,可以将其删除。)

      将此应用于 2 张图像后,您将拥有 2 个(256 位)指纹,fp1fp2

      然后通过对这两个值进行异或运算并对设置为 1 的位进行计数来计算这两个图像的相似度得分。要进行此位计数,您可以使用来自this answerbitsoncount() 函数:

      # fp1 and fp2 are stored as lists of 8 (32-bit) integers
      score = 0
      for n in range(8):
          score += bitsoncount(fp1[n] ^ fp2[n])
      

      score 将是一个介于 0 和 256 之间的数字,表示您的图像有多相似。在我的应用程序中,我将其除以 2.56(归一化为 0-100),我发现归一化分数为 20 或更低的图像通常是相同的。

      如果您想实现此方法并使用它来比较大量图像,我强烈建议您尽可能使用 Cython(或只是普通 C):XORing 和位计数非常慢使用纯 Python 整数。

      非常抱歉,我再也找不到我的 Python 代码了。现在我只有一个 Go 版本,但恐怕我不能在这里发布(紧密集成在其他一些代码中,可能有点难看,因为它是我在 Go 中的第一个严肃程序......)。

      GQView/Geeqie 中还有一个非常好的“相似查找”功能;它的来源是here

      【讨论】:

        【解决方案4】:

        要在 Python 中更简单地实现 Earth Mover 距离(又名 Wasserstein 距离),您可以使用 Scipy:

        from keras.preprocessing.image import load_img, img_to_array
        from scipy.stats import wasserstein_distance
        import numpy as np
        
        def get_histogram(img):
          '''
          Get the histogram of an image. For an 8-bit, grayscale image, the
          histogram will be a 256 unit vector in which the nth value indicates
          the percent of the pixels in the image with the given darkness level.
          The histogram's values sum to 1.
          '''
          h, w = img.shape[:2]
          hist = [0.0] * 256
          for i in range(h):
            for j in range(w):
              hist[img[i, j]] += 1
          return np.array(hist) / (h * w)
        
        a = img_to_array(load_img('a.jpg', grayscale=True))
        b = img_to_array(load_img('b.jpg', grayscale=True))
        a_hist = get_histogram(a)
        b_hist = get_histogram(b)
        dist = wasserstein_distance(a_hist, b_hist)
        print(dist)
        

        【讨论】:

        • 我可以知道如何将您的代码应用于普通彩色图像吗?以researchgate.net/profile/Tao_Chen15/publication/3935609/figure/… 为例,它在“h,w = img.shape”行中给出“ValueError: too many values to unpack”。谢谢。
        • 啊,在这种情况下,您可以使用imread('a.jpg', mode='L') 将图像读取为灰度
        • 太棒了!很多人将从这个答案中受益!
        • 我无法安装 from scipy.ndimage import imread 所以我尝试从 openCV 读取 imread。然后它在h, w = img.shape 给我一个错误,因为ValueError: too many values to unpack (expected 2)
        • @x89 是的,scipy imread 助手已被弃用。我刚刚更新了使用更现代的 keras 的答案。它是如何工作的?
        猜你喜欢
        • 2018-02-06
        • 1970-01-01
        • 2011-02-05
        • 1970-01-01
        • 2020-04-02
        • 2021-08-25
        • 2012-01-23
        • 2011-08-09
        • 2012-07-17
        相关资源
        最近更新 更多