使用 python, opencv 从一个文件夹中提取图像,对其进行处理并保存到另一个文件夹中

Extract images from one folder, process it and save into another folder with python, opencv

我正在尝试从一个子文件夹 "input"(第 10 行)中提取图像文件并对其进行处理,然后将其保存到另一个子文件夹 "output"(最后第 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)

我们来做个小实验。

>>> 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")

sh: 1: 树: 未找到

32512