I am trying to use cv2.matchShapes where I am using dataset of images so when I compare their contours, then store all ret values in an float array and images in another one, so the final result that I want is sorted array of images depending on their ret values.
Tried if rets[i] < rets[i 1] but got an error TypeError: list indices must be integers or slices, not float, Googled about float comparison but didn't solve my problem.
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)
CodePudding user response:
You need to "pair" your 'ret' values with their associated images. Do this with a tuple and build a list of those tuples. You can then sort that list using the built-in. Here's your code edited appropriately:
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])
