Следующее проверено и работает в Unix синтаксисе пути на моем Ma c в Python / OpenCV. И я не Windows пользователь. Так что вам нужно будет изменить пути соответствующим образом для вашей ОС и изменить мои "/" на "\", где они конкретно указаны в путях
. Вам нужно определить путь, куда вы хотите поместить вывод каталог для хранения созданных изображений. Я использовал in_dir и out_dir. каталог out_dir должен уже существовать.
Так что-то вроде следующего. Где я получаю порог OTSU вне l oop и сохраняю пороговое значение из вашего размытого изображения. Затем я * l oop поверх всех изображений во входном каталоге через ваш img_mask. Я порождаю каждое изображение, используя порог, который был сохранен, а затем записываю файл на диск внутри l oop.
from glob import glob
import os
import cv2
# read your one blurred image and convert to gray
im_gray = cv2.imread('test/lena.png', 0)
# threshold it with OTSU thresholding and get the threshold value
thresh, im_bw = cv2.threshold(im_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
print(thresh)
# define the paths to your input images and to where you want to put the output images
in_dir = 'test'
out_dir = 'test2'
# read the input image file names with paths into a list
infiles = in_dir + '/*.png'
img_names = glob(infiles)
print(img_names)
# loop over each input image in a for loop
for fn in img_names:
print('processing %s...' % fn)
# read an input image as gray
im_gray = cv2.imread(fn, 0)
# threshold it with your saved threshold
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
# write the result to disk in the previously created output directory
name = os.path.basename(fn)
outfile = out_dir + '/' + name
cv2.imwrite(outfile, im_bw)