如何在 python 中使用强力算法对浮点数列表进行排序

How to sort list of floats using brute force algorithm in python

我正在尝试在使用图像数据集的地方使用 cv2.matchShapes,所以当我比较它们的轮廓时,然后将所有 ret 值存储在一个浮点数组中,将图像存储在另一个数组中,所以我想要的最终结果是根据图像的 ret 值对图像数组进行排序。 已尝试 if rets[i] < rets[i+1] 但出现错误 TypeError: list indices must be integers or slices, not float,用 Google 搜索了浮点数比较但没有解决我的问题。

import argparse
import pickle
import glob
import sys
from PIL import Image
import os


import cv2
import numpy as np

dataset = "dataset/*.jpg"


# print('image_array shape:', np.array(imageArray).shape)
# cv2.imshow('frame', imageArray[1])
# cv2.waitKey(0)


queryImage = cv2.imread("query/12034.jpg", 0)
ret, thresh = cv2.threshold(queryImage, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
queryContour = contours[0]


min_dist = sys.maxsize
images = []
rets = []

for imagePath in glob.glob(dataset):
    image = cv2.imread(imagePath, 0)
    ret, th2 = cv2.threshold(image, 127, 255, 0)
    contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    ret = cv2.matchShapes(queryContour, cnt, 1, 0.0)

    images.append(image)
    rets.append(ret)


    # if ret < min_dist:
    #     min_dist = ret
    #     images.append(image)
    print(ret)


for i in rets:
    if abs(rets[i] - rets[i+1]):
        tmp = images[i]
        images[i] = images[i+1]
        images[i+1] = tmp
        retTmp = rets[i]
        rets[i] = rets[i+1]
        rets[i+1] = retTmp

print(rets)

您需要将您的 'ret' 值与其相关图像“配对”。使用元组执行此操作并构建这些元组的列表。然后您可以使用 built-in 对该列表进行排序。这是您经过适当编辑的代码:

import glob
import sys
from PIL import Image
import cv2

dataset = "dataset/*.jpg"


queryImage = cv2.imread("query/12034.jpg", 0)
ret, thresh = cv2.threshold(queryImage, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
queryContour = contours[0]


min_dist = sys.maxsize
rets_images = []

for imagePath in glob.glob(dataset):
    image = cv2.imread(imagePath, 0)
    ret, th2 = cv2.threshold(image, 127, 255, 0)
    contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnt = contours[0]
    ret = cv2.matchShapes(queryContour, cnt, 1, 0.0)
    rets_images.append((ret, image))
    print(ret)


rets_images.sort(key=lambda x: x[0])