36

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

我在这篇文章中得到了这段代码,并根据我的上下文进行了更改

# 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()

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

4

4 回答 4

29

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

robots.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 包含最小化的结果......但正如我所说,我不确定它为什么抱怨奇异矩阵。

该算法的唯一问题是速度不是很快,因此无法按需执行,但您必须在创建数据集时耐心执行它并将结果存储在某个地方

于 2012-11-20T23:13:00.767 回答
12

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

甚至谷歌图片搜索还没有这样做——他们做基于文本的图片搜索——例如,在页面中搜索与您搜索的文本相似的文本。(而且我确信他们正在使用 CBIR;它是许多图像处理研究人员的圣杯)

如果你有一个紧迫的最后期限或需要完成这项工作并尽快工作......哎呀。

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

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

一般来说,你需要做几件事:

  1. 提取特征(在局部兴趣点,或全局,或以某种方式,SIFT、SURF、直方图等)
  2. 聚类/建立图像分布模型

这可能涉及特征描述符图像要点多实例学习。等等

于 2012-11-22T02:34:45.240 回答
10

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

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

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

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

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

将其应用于 2 张图像后,您将拥有 2 个(256 位)指纹,fp1并且fp2.

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

# 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):纯 Python 整数的 XORing 和位计数非常慢。

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

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

于 2012-11-22T17:43:33.603 回答
5

为了在 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)
于 2018-03-31T21:18:57.797 回答