[英]What is the fastest way to iterate over a list of items and group them to a dictionary with a similarity score
我有一个图像列表。 比较列表中具有similarity(imga,imgb)
分数的图像并将它们分组在一起的字典的最快方法是什么,将第一项作为键,返回的相似性阈值之后为键。
范例 :
ImgList = [img1, img2, img3,img4, img5,img6]
如果img1,img3具有相似度评分0.7(> 0.5)
如果img2,im4,img6具有相似度0.6(> 0.5)
Output = {img1:[img3], img2:[img4,img6], img5:[]}
我的方法(索引错误) :
for i in ImgList:
for j in ImgList:
#compare code here
ImgList.remove(j)
编辑 :
def get_sim(img1,img2):
(score, diff) = measure.compare_ssim(img1, img2, full=True)
return score
img1 = cv2.imread("1.png")
img2 = cv2.imread("2.png")
img3 = cv2.imread("3.png")
img4 = cv2.imread("4.png")
img5 = cv2.imread("5.png")
img6 = cv2.imread("6.png")
imgs = [img1,img2,img3,img4,img5,img6]
for i in imgs:
for j in imgs:
similarity = get_sim(i,j) # values in range 0 to 1
if(similarity>=0.5):
imgs.remove(j)
#Need to group i,j
我以前的答案可能没有满足您的要求,这可能会起作用:
res = {}
for i in range(len(ImgList)):
for j in ImgList[i:]:
res.setdefault(get_sim(ImgList[i],j), []).append(j)
res = {i.pop(0):i for i in res.values()}
您可以以列表理解的方式编写它
res = {}
_ = [res.setdefault(get_sim(ImgList[i],j), []).append(j) for i in range(len(ImgList)) for j in ImgList[i:]]
res = {i.pop(0):i for i in res.values()}
没有任何其他细节,
创建一个使用similarity
函数创建阈值以上列表的函数,然后在字典理解中使用该函数。 像这样:
def find_imgs_above_threshold(img, img_list, threshold=0.5):
img_list_without_img = img_list.remove(img)
sim_scores = [similarity(img, i) for i in img_list_without_img]
imgs_above_threshold= [score for score in sim_scores if score >= threshold]
return imgs_above_threshold
img_dict = {i: find_imgs_above_threshold(i, imgList) for i in imgList}
imgs = [cv2.imread(f"{i}.png") for i in range(1, 7)]
output = {}
score_img = {}
for img in imgs:
score = get_sim(img)
if score > 0.5:
if score not in score_img:
score_img[score] = img
output[img] = []
else:
output[score_img[score]].append(img)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.