美文网首页
图像相似度匹配

图像相似度匹配

作者: 快要没时间了 | 来源:发表于2016-09-25 14:46 被阅读0次

这个周末解决了一个实际问题。
硬盘里存有大量图片。(大约2万)
当需要找某一图片时,如何找出与之相似的呢。

在查资料的过程中。我知道可以使用
PIL(Python Image Library)或者是openCV。
对于学习来说,使用后者更好,因为opencv具有跨平台的特性,且支持多种语言的接口。而且在python上也不乏很多资料可查。

开发环境我选择了 opencv3.1 + pycharm
在python中图像使用numpy.ndarray表示,所以要提前装好numpy库。

下一步就是匹配算法了。
一开始我想用的是Template Matching
后来发现这种模式匹配的方式还需要涉及缩放问题。
于是,简单点的话还是使用直方图匹配的方式进行。
参考 pil的这个博客。不过我使用的是opencv。
opencv的直方图使用资料可以从readdoc网查到

好的。讲了这么多。还是直接贴代码吧~

import cv2
import numpy as np
import os
import os.path
from matplotlib import pyplot as plt

此处安装后,需要配置cv2的so库地址。报错不要紧,不影响调用。见我的安装笔记即可。

获取直方图算法:简单说一下,就是分别获取rgb三个通道的直方图,然后加在一起,成为一个768*1的数组。
返回的是一个元组。分别是直方图向量和图像的像素点总和。我利用这个比例缩放来进行图片的大小匹配。

def get_histGBR(path):
    img = cv2.imread(path)

    pixal = img.shape[0] * img.shape[1]
    # print(pixal)
    # scale = pixal/100000.0
    # print(scale)
    total = np.array([0])
    for i in range(3):
        histSingle = cv2.calcHist([img], [i], None, [256], [0, 256])
        total = np.vstack((total, histSingle))
    # plt.plot(total)
    # plt.xlim([0, 768])
    # plt.show()
    return (total, pixal)

相似度计算:

计算公式
def hist_similar(lhist, rhist, lpixal,rpixal):
    rscale = rpixal/lpixal
    rhist = rhist/rscale
    assert len(lhist) == len(rhist)
    likely =  sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lhist, rhist)) / len(lhist)
    if likely == 1.0:
        return [1.0]
    return likely

该算法反悔一个0到1的[float]相似度。来代表两个向量之间的几何距离。输入的4个参数分别为图像的直方图和图像的尺寸。

最后加上一些文件访问的代码和排序代码。即可给出
对于指定图片,在目标文件夹中的所有图片中相似度排名最高的N个图的路径和相似度。

import cv2
import numpy as np
import os
import os.path
from matplotlib import pyplot as plt


# 文件读取并显示
# img = cv2.imread("kitchen.jpeg")
# print("hello opencv "+ str(type(img)))
# # print(img)
# cv2.namedWindow("Image")
# cv2.imshow("Image",img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# img = cv2.imread('kitchen.jpeg', 1)
# temp = cv2.imread('Light.png', 1)
# w,h = temp.shape[::-1]
#
# print(w,h,sep="  ")
# # print(img)
# cv2.namedWindow("Image")
# cv2.imshow("Image", img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# img = cv2.imread('kitchen.jpeg', 0)
# img2 = img.copy()
# template = cv2.imread('Light.png', 0)
# w, h = template.shape[::-1]
# print(template.shape)
#
# # All the 6 methods for comparison in a list
# methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
#            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
#
# for meth in methods:
#     img = img2.copy()
#     method = eval(meth)
#
#     # Apply template Matching
#     res = cv2.matchTemplate(img, template, method)
#     min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
#
#     # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
#     if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
#         top_left = min_loc
#     else:
#         top_left = max_loc
#     bottom_right = (top_left[0] + w, top_left[1] + h)
#
#     cv2.rectangle(img, top_left, bottom_right, 255, 2)
#
#     plt.subplot(121), plt.imshow(res, cmap='gray')
#     plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
#     plt.subplot(122), plt.imshow(img, cmap='gray')
#     plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
#     plt.suptitle(meth)
#
#     plt.show()

# image = cv2.imread("kitchen.jpeg", 0)
# hist = cv2.calcHist([image],
#                     [0],
#                     None,
#                     [256],
#                     [0, 256])
# plt.plot(hist),plt.xlim([0,256])
# plt.show()

# # hist = cv2.calcHist([image],[0,1,2],None,[256,256,256],[[0,255],[0,255],[0,255]])
# # cv2.imshow("img",image)
# cv2.imshow("hist", hist)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# image = cv2.imread("kitchen.jpeg", 0)
# hist = plt.hist(image.ravel(), 256, [0, 256])
# plt.show(hist)

def hist_similar(lhist, rhist, lpixal,rpixal):
    rscale = rpixal/lpixal
    rhist = rhist/rscale
    assert len(lhist) == len(rhist)
    likely =  sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lhist, rhist)) / len(lhist)
    if likely == 1.0:
        return [1.0]
    return likely


def get_histGBR(path):
    img = cv2.imread(path)

    pixal = img.shape[0] * img.shape[1]
    # print(pixal)
    # scale = pixal/100000.0
    # print(scale)
    total = np.array([0])
    for i in range(3):
        histSingle = cv2.calcHist([img], [i], None, [256], [0, 256])
        total = np.vstack((total, histSingle))
    # plt.plot(total)
    # plt.xlim([0, 768])
    # plt.show()
    return (total, pixal)


if __name__ == '__main__':
    targetHist, targetPixal = get_histGBR('test.jpg')
    rootdir = "/Users/YM/Desktop/DCIM"
    # aHist = get_histGBR('a.png')
    # bHist = get_histGBR('Light.png')
    #
    # print(hist_similar(aHist, bHist))
    resultDict = {}
    for parent, dirnames, filenames in os.walk(rootdir):
        # for dirname in dirnames:
        #     print("parent is: " + parent)
        #     print("dirname is: " + dirname)
        for filename in filenames:
            if (filename[-3:] == 'jpg'):
                jpgPath = os.path.join(parent, filename)
                testHist, testPixal = get_histGBR(jpgPath)
                # print(hist_similar(targetHist,testHist)[0])
                resultDict[jpgPath]=hist_similar(targetHist,testHist,targetPixal,testPixal)[0]

    # print(resultDict)
    # for each in resultDict:
    #     print(each, resultDict[each],sep="----")
    sortedDict = sorted(resultDict.items(), key=lambda asd: asd[1], reverse=True)
    for i in range(5):
        print(sortedDict[i])

相关文章

  • 图像相似度匹配

    这个周末解决了一个实际问题。硬盘里存有大量图片。(大约2万)当需要找某一图片时,如何找出与之相似的呢。 在查资料的...

  • 模式匹配

    模式匹配, 即寻找待匹配图像和全体图像中最相似的部分,用于物体检测任务。将图像A在图像B中匹配的图像框起来 算法基...

  • 图像相似度

  • 余弦相似度匹配

    今天的产品涉及到一个相似度匹配算法,上网查了这类算法很多。跟研发讨论,研发推荐使用余弦值相似度算法。 余弦...

  • 图像相似度计算

    利用直方图特征计算图像之间的相似度,得到相关矩阵

  • 图像相似度评价指标

    图像相似度评价指标 在图像处理中我们经常遇到需要评价两张图像是否相似,给出其相似度的指标,这里总结了三种评判指标均...

  • 图像搜索、图像相似度比较

    基于传统图像SIFT方法,基于卷积神经网络方法是两种代表。另外基于图像哈希算法,准确度都不太高。 SIFT方法比较...

  • 图片查重

    OpenCV—python 图像相似度算法(dHash,方差)

  • matchTemplate(模板匹配)

    概念 模板匹配就是在一幅图像中寻找与模板图像最相似的区域。 效果图对比 ●源图像 ●模板图像 函数讲解 ●函数原型...

  • Quora句子相似度匹配

    预备知识 NLP基础: 词袋模型(Bag-of-words model): TF-IDF算法(term frequ...

网友评论

      本文标题:图像相似度匹配

      本文链接:https://www.haomeiwen.com/subject/twjfyttx.html