2017-06-14 15 views
0

ループ内に切り取った画像を保存する際に問題があります。私のコード:画像を異なる名前のループに保存する

def run(self, image_file): 
    print(image_file) 
    cap = cv2.VideoCapture(image_file) 
    while(cap.isOpened()): 
     ret, frame = cap.read() 
     if ret == True: 
      img = frame 
      min_h = int(max(img.shape[0]/self.min_height_dec, self.min_height_thresh)) 
      min_w = int(max(img.shape[1]/self.min_width_dec, self.min_width_thresh)) 
      gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
      faces = self.face_cascade.detectMultiScale(gray, 1.3, minNeighbors=5, minSize=(min_h, min_w)) 

      images = [] 
      for i, (x, y, w, h) in enumerate(faces): 
       images.append(self.sub_image('%s/%s-%d.jpg' % (self.tgtdir, self.basename, i + 1), img, x, y, w, h)) 
      print('%d faces detected' % len(images)) 

      for (x, y, w, h) in faces: 
       self.draw_rect(img, x, y, w, h) 
       # Fix in case nothing found in the image 
      outfile = '%s/%s.jpg' % (self.tgtdir, self.basename) 
      cv2.imwrite(outfile, img) 
      if cv2.waitKey(1) & 0xFF == ord('q'): 
       break 
     else: 
      break 
    cap.release() 
    cv2.destroyAllWindows() 
    return images, outfile 

私は顔にトリミングするすべてのフレームのループを持っています。問題は、切り取られたすべての画像と画像で同じ名前が付けられ、最後には最後のフレームからのみ顔があることです。すべての切り抜かれた顔や画像を保存するには、このコードを修正する必要がありますか?あなたはまた、他の技術を使用することができます

from datetime import datetime 

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename + str(datetime.now())) 
cv2.imwrite(outfile, img) 

:として

答えて

1

各ファイルを同じ名前で保存しています。したがって、あなたは、あなたがあまりにも

2

あなたは画像を保存する前に名前を割り当てるには、名前の衝突を避けることになる、ミリ秒単位の精度で現在の時間を取得するためにdatetimeモジュールを使用することができますuuid4として各フレームのユニークなランダムIDを取得しますが、名前がランダムなので、ソートされたオーダーで表示するのが面倒なプラットフォームもありますので、名前のタイムスタンプを使用すると作業が完了すると思います。

+0

ありがとう、それはうまくいきます! – GGzet

1
import numpy as np 
import cv2 

cap = cv2.VideoCapture(0) 
i = 0 

while(True): 
    # Capture frame-by-frame 
    i = i +1 
    ret, frame = cap.read() 

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 

# Display the resulting frame 
cv2.imshow('frame',frame) 
**cv2.imwrite("template {0}.jpg".format(i),gray)** 


if cv2.waitKey(0) & 0xFF == ord('q'): 
    break 

cap.release() 
cv2.destroyAllWindows() 
ファイルの先頭に import uuidにする必要があります名前に

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename + str(uuid.uuid4())) 

をランダムな文字列を追加するには、このに行以前保存した画像に

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename) 

の変更を上書きしています

---コードby rohbhot

関連する問題