Python 그림 검색

검색 대기 그림
在这里插入图片描述
2.테스트 집합
在这里插入图片描述
3.newsimilarity_compare.py

# -*- encoding=utf-8 -*-

from image_similarity_function import *
import os
import shutil

#        
threshold1 = 0.70
#            
threshold2 = 0.95


#            
def calc_image_similarity(img1_path, img2_path):
    """
    :param img1_path: filepath+filename
    :param img2_path: filepath+filename
    :return:        
    """

    similary_ORB = float(ORB_img_similarity(img1_path, img2_path))
    similary_phash = float(phash_img_similarity(img1_path, img2_path))
    similary_hist = float(calc_similar_by_path(img1_path, img2_path))
    #                  0.7,       ,  ,   。
    max_three_similarity = max(similary_ORB, similary_phash, similary_hist)
    min_three_similarity = min(similary_ORB, similary_phash, similary_hist)
    if max_three_similarity > threshold1:
        result = max_three_similarity
    else:
        result = min_three_similarity

    return round(result, 3)


if __name__ == '__main__':

    #      
    filepath = r'D:\Dataset\cityscapes\leftImg8bit\val\frankfurt'

    #      
    searchpath = r'C:\Users\Administrator\Desktop\cityscapes_paper'

    #         
    newfilepath = r'C:\Users\Administrator\Desktop\result'

    for parent, dirnames, filenames in os.walk(searchpath):
        for srcfilename in filenames:
            img1_path = searchpath +"\\"+ srcfilename
            for parent, dirnames, filenames in os.walk(filepath):
                for i, filename in enumerate(filenames):
                    print("{}/{}: {} , {} ".format(i+1, len(filenames), srcfilename,filename))
                    img2_path = filepath + "\\" + filename
                    #   
                    kk = calc_image_similarity(img1_path, img2_path)
                    try:
                        if kk >= threshold2:
                            #               
                            shutil.copy(img2_path, os.path.join(newfilepath, srcfilename[:-4] + "_" + filename))
                    except Exception as e:
                        # print(e)
                        pass
4.imagesimilarity_function.py

# -*- encoding=utf-8 -*-

#    
import cv2
from functools import reduce
from PIL import Image


#            ORB  
def ORB_img_similarity(img1_path, img2_path):
    """
    :param img1_path:   1  
    :param img2_path:   2  
    :return:      
    """
    try:
        #     
        img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
        img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)

        #    ORB   
        orb = cv2.ORB_create()
        kp1, des1 = orb.detectAndCompute(img1, None)
        kp2, des2 = orb.detectAndCompute(img2, None)

        #         
        bf = cv2.BFMatcher(cv2.NORM_HAMMING)
        # knn    
        matches = bf.knnMatch(des1, trainDescriptors=des2, k=2)

        #          
        good = [m for (m, n) in matches if m.distance < 0.75 * n.distance]
        similary = len(good) / len(matches)
        return similary

    except:
        return '0'


#           --pHash
def phash(img):
    """
    :param img:   
    :return:        hash 
    """
    img = img.resize((8, 8), Image.ANTIALIAS).convert('L')
    avg = reduce(lambda x, y: x + y, img.getdata()) / 64.
    hash_value = reduce(lambda x, y: x | (y[1] << y[0]), enumerate(map(lambda i: 0 if i < avg else 1, img.getdata())),
                        0)
    return hash_value


#                    
def phash_img_similarity(img1_path, img2_path):
    """
    :param img1_path:   1  
    :param img2_path:   2  
    :return:      
    """
    #     
    img1 = Image.open(img1_path)
    img2 = Image.open(img2_path)

    #       
    distance = bin(phash(img1) ^ phash(img2)).count('1')
    similary = 1 - distance / max(len(bin(phash(img1))), len(bin(phash(img1))))
    return similary


#             
def make_regalur_image(img, size=(256, 256)):
    """                    ,        256x256    。"""
    return img.resize(size).convert('RGB')


def hist_similar(lh, rh):
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lh, rh)) / len(lh)


def calc_similar(li, ri):
    return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0


def calc_similar_by_path(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    return calc_similar(li, ri)


def split_image(img, part_size=(64, 64)):
    w, h = img.size
    pw, ph = part_size
    assert w % pw == h % ph == 0
    return [img.crop((i, j, i + pw, j + ph)).copy() for i in range(0, w, pw) \
            for j in range(0, h, ph)]

결과
在这里插入图片描述
파 이 썬 이미지 검색 을 위 한 그림 검색 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 파 이 썬 그림 검색 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기