使用OpenCV和Python比较图像的相似性
我正在尝试将一张图片与其他图片列表进行比较,并返回该列表中具有最高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()
我的问题是,如何将图像与图像列表进行比较并仅获得相似图像?有什么方法可以做到这一点?
-
我建议您看一下图像之间推土机的距离(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包含最小化的结果…但是正如我所说,我不确定为什么它抱怨奇异矩阵。
该算法的唯一问题是速度不是很快,因此无法按需执行,但是您必须耐心执行该数据集的创建并将结果存储在某处