python - 以不同名称循环保存图像

标签 python opencv

我在循环保存裁剪图像时遇到问题。我的代码:

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

我对每一帧都有一个循环,在脸上进行裁剪。问题是,对于每张裁剪后的图像和图片,它都给出了相同的名称,最后我只有最后一帧的面孔。我应该如何修复此代码以保存所有裁剪的面孔和图像?

最佳答案

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

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

更改此行以在名称中添加随机字符串

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

您还需要在文件顶部import uuid

关于python - 以不同名称循环保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535290/

相关文章:

python - 如何在图像分割中将 tf.Dataset 与 TIFF 文件一起使用?

python - 霍夫变换检测较短的线

python - Ubuntu 16.04 Django 1.11.5 virtualenv opencv

python - 如何在新的 Python 进程中设置环境变量

python - 时间序列按周分组 python

python - 在 Pycaffe 中通过索引访问 blob

c - 使用 C 接口(interface)的 cvMerge 和 cvShowImage 错误

java - 在Android应用程序中使用OpenCV人脸识别算法

c++ - 即使在混合后也想要透明图像

Python 2.6 正则表达式机制?