@JRBRO

Как упорядочить изображения из списка?

Есть скрипт, который режет и другой уже измеряет "цветастость". Тот, который измеряет цвет, отображает из хаотично, а хотелось бы по порядку как оно было до этого. Может есть какое либо решение?

Режем слайсером на 64 части, 8 на 8 чтобы было
import image_slicer

image_slicer.slice('/Users/User/Desktop/Test/test.png', 64)


И вот сам скрипт который измеряет цветастость. Я менял и разрешения, и саму сетку, но всегда отображение рандомное.
Скрипт в спойлере
from imutils import build_montages
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2

def image_colorfulness(image):
	# split the image into its respective RGB components
	(B, G, R) = cv2.split(image.astype("float"))
	# compute rg = R - G
	rg = np.absolute(R - G)
	# compute yb = 0.5 * (R + G) - B
	yb = np.absolute(0.5 * (R + G) - B)
	# compute the mean and standard deviation of both `rg` and `yb`
	(rbMean, rbStd) = (np.mean(rg), np.std(rg))
	(ybMean, ybStd) = (np.mean(yb), np.std(yb))
	# combine the mean and standard deviations
	stdRoot = np.sqrt((rbStd ** 2) + (ybStd ** 2))
	meanRoot = np.sqrt((rbMean ** 2) + (ybMean ** 2))
	# derive the "colorfulness" metric and return it
	return stdRoot + (0.3 * meanRoot)

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True,
	help="path to input directory of images")
args = vars(ap.parse_args())

# initialize the results list
print("[INFO] computing colorfulness metric for dataset...")
results = []
# loop over the image paths
for imagePath in paths.list_images(args["images"]):
	# load the image, resize it (to speed up computation), and
	# compute the colorfulness metric for the image
	image = cv2.imread(imagePath)
	image = imutils.resize(image, width=250)
	C = image_colorfulness(image)
	# display the colorfulness score on the image
	cv2.putText(image, "{:.2f}".format(C), (40, 40), 
		cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 255, 0), 3)
	# add the image and colorfulness metric to the results list
	results.append((image, C))

    # sort the results with more colorful images at the front of the
# list, then build the lists of the *most colorful* and *least
# colorful* images
print("[INFO] displaying results...")
allColors = results
allColor = [a[0] for a in allColors[:64]]
allColorMontage = build_montages(allColor, (150, 84), (8, 8))
results = sorted(results, key=lambda x: x[1], reverse=True)

cv2.imshow("ALL", allColorMontage[0])
cv2.waitKey(0)

Screenshot-2022-05-16-at-13-24-14.png
Screenshot-2022-05-16-at-13-23-24.png
  • Вопрос задан
  • 187 просмотров
Решения вопроса 1
Vindicar
@Vindicar
RTFM!
Ну насколько я понял, проблема в том, что paths.list_images(args["images"]) возвращает изображения в произвольном порядке (что неудивительно если оно основано на os.walk() или glob.glob(), файловые системы обычно не гарантируют порядок).
Так что засунь это в список: images = list(paths.list_images(args["images"]))
А потом отсортируй. Если у тебя имена файлов имеют вид чтото_строка_столбец.PNG, можно выкрутиться так:
from os import path

def filename_key(fname: str):
    fname = path.splitext(path.basename(fname))[0]  # убираем путь и расширение
    prefix, row, col = fname.rsplit('_', 2)  # делим имя на части
    return (int(row), int(col))  # возвращаем кортеж, по которому будут сравниваться файлы

images = list(paths.list_images(args["images"]))
images.sort(key=filename_key)  # сортируем по выбранному нами критерию
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
17 апр. 2024, в 00:13
800 руб./за проект
17 апр. 2024, в 00:06
240000 руб./за проект
17 апр. 2024, в 00:02
1000 руб./за проект