使用OpenCV和Python比较图像的相似性

lee*_*roo 33 python opencv computer-vision

我正在尝试将图像与其他图像列表进行比较,并返回此列表中的一系列图像(如Google搜索图像),其相似度高达70%.

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

# 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()
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何将图像与图像列表进行比较并获得相似的图像?有没有办法做到这一点?

Enr*_*eri 25

我建议你看看地球移动器在图像之间的距离(EMD).该度量标准给出了将标准化灰度图像转换为另一种灰度图像有多难的感觉,但可以概括为彩色图像.可以在以下文章中找到对此方法的非常好的分析:

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

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

唯一的问题是此方法不会定义相似性的百分比,而是可以过滤的距离.

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

编辑:

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

在数学术语中,流矩阵实际上是一个四维张量,它给出了从旧图像的点(i,j)到新图像的点(k,l)的流动,但如果你展平你的图像,你可以改变它到一个正常的矩阵,只是更难阅读.

此流矩阵有三个约束:每个项应为正,每行的总和应返回相同的desitnation像素值,每列的总和应返回起始像素的值.

鉴于此,您必须最小化转换成本,由(i,j)到(k,l)的每个流的乘积之和给出(i,j)和(k,l)之间的距离.

它看起来有点复杂,所以这里是测试代码.逻辑是正确的,我不确定为什么scipy solver抱怨它(你应该看看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)
Run Code Online (Sandbox Code Playgroud)

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

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


Pet*_*ete 11

您正在着手解决一个被称为"基于内容的图像检索"或CBIR的大问题.这是一个庞大而活跃的领域.虽然有很多技术都有不同程度的成功,但还没有完成的算法或标准方法.

甚至谷歌图像搜索也没有这样做(还) - 他们进行基于文本的图像搜索 - 例如,在页面中搜索与您搜索的文本类似的文本.(我相信他们正在努力使用CBIR;它是许多图像处理研究人员的圣杯)

如果你有一个紧迫的截止日期或需要完成这项工作并尽快工作......哎呀.

这里有很多关于这个主题的论文:

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

通常你需要做一些事情:

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

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


Sch*_*uki 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:-
Run Code Online (Sandbox Code Playgroud)

([0]in path[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])
Run Code Online (Sandbox Code Playgroud)

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

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

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

在GQView/Geeqie中还有一个非常好的"通过相似性找到"功能; 它的来源就在这里.


duh*_*ime 5

要在 Python 中更简单地实现地球移动器距离(又名 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)
Run Code Online (Sandbox Code Playgroud)