2017-10-25 4 views
0

"input"(10行目)のサブフォルダから画像ファイルを抽出して処理し、別のサブフォルダに保存しようとしています "output "(最後の10行目)ですが、処理されたファイルは保存されません。しかし、コードが保存されている同じフォルダ(10行目の抽出コマンドには入力を書き込まない)からすべてのイメージファイルを取得すると、サブフォルダ "出力"に保存すると正常です。メモを覚えておいてください。どちらの場合も、処理されたファイルは表示されていて同じで、1つのケースに保存されません。あるフォルダから画像を抽出し、それを処理して別のフォルダに保存する、opencv

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) 
+0

出力ファイル名を印刷してみましたが、実際にどこに書き込もうとしていますか?私は "output/Image_input/foo.bmp"のように見えて、黙って存在しないディレクトリに書き込もうとしていても驚くことはありません( 'imwriteの結果をテストするのは気にしないので')。 –

答えて

0

小さな実験をしましょう。あなたが見ることができるように

>>> 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")の結果は、「/マッチャー」ルートディレクトリが含まれています。つまり、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) 
関連する問題