2017-06-14 105 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 

我有一个循环每个框架与裁剪脸上。问题是,对于每个裁剪后的图像和图片,它会给出相同的名称,最后我只有从最后一帧开始才有脸。我应该如何解决这个代码来保存所有裁剪后的面孔和图像?

回答

1

您正在使用相同的名称保存每个文件。因此,要覆盖以前保存的图像

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

行更改为这个在名称添加一个随机字符串

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

您需要import uuid在你的文件太多

2

您可以使用datetime模块来得到当前时间毫秒精度,这将避免名称冲突,指定名称的图像保存为前:

from datetime import datetime 

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

您也可以使用其他技术,例如作为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() 
顶部

--- rohbhot代码