Извлеките изображения из одной папки, обработайте их и сохраните в другую папку с помощью python, opencv
Я пытаюсь извлечь файлы изображений из одной "входной" папки (10-я строка) и обработать их, а затем сохранить в другой "выходной" папке (10-я последняя строка), но обработанные файлы не сохраняются. Но если я возьму все файлы изображений из той же папки, в которой сохранен код (не записывая ввод в команду извлечения в 10-й строке), то, когда я сохраню его в подпапке "output", я добьюсь успеха. Просто запомните записку; в обоих случаях обработанные файлы отображаются одинаково, но не сохраняются ни в одном случае.
import glob
import cv2
import numpy as np
import matplotlib.pyplot as plt
# initialize data and target as lists
data = []
target = []
# find all bmp files in the current folder
Files = glob.glob("input/*.bmp")
# go through all files and fit contour
for f in Files:
img = 255-cv2.imread(f,0) #0 for grayscale
white=cv2.imread("white.bmp")
# add image to the list
data.append(img)
# make lines thicker
kernel = np.ones((5,5),np.uint8)
img = cv2.dilate(img,kernel,iterations = 1)
# contour application
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)
# sort contours by area
areas = [cv2.contourArea(cnt) for cnt in contours]
idx = np.argsort(areas)[::-1]
contours = np.asarray(contours)[idx]
for cnt in contours:
(x,y),radius = cv2.minEnclosingCircle(cnt)
if radius < img.shape[0]-10 and radius > 20:
cv2.circle(white,(int(x),int(y)),int(radius),0,4)
break
plt.imshow(white)
#save the files to output folder with the name "Image_x"
filename = "output/Image_%s" %f
plt.colorbar()
# live image display
plt.draw()
# need to add pause command, otherwise it does not work
plt.pause(.01)
# clear the figure to avoid memory issues
plt.clf()
#save these contours (outputs) as bmps with same file names
cv2.imwrite(filename,white)
1 ответ
Давайте сделаем небольшой эксперимент.
>>> import os, glob
>>> os.system("tree ./matcher")
matcher
├── matcher2.py
├── matcher.cpp
├── matcher.py
└── question.md
0 directories, 4 files
0
>>> glob.glob("matcher/*.py")
['matcher/matcher2.py', 'matcher/matcher.py']
Как видите, результаты glob.glob("matcher/*.py")
содержит корневой каталог "matcher/". Это так сказать, это неправильно писать filename = "output/Image_%s" %f
, Измените это на filename = "output/" + f.split("/")[-1]
или так.
## source bmps in "input/"
## processed bmps to "output"
for f in glob.glob("input/*.bmp"):
pass
filename = "output/" + f.split("/")[-1]
cv2.imwrite(filename, xxx)
Кажется, нам сначала нужно добавить matcher2.py и matcher.py. В противном случае возникает следующая ошибка.
>>> import os, glob
>>> os.system("tree ./matcher")
ш: 1: дерево: не найдено
32512