Python 3.x 仅批处理读取/保存文件夹中的最后一幅图像

Python 3.x 仅批处理读取/保存文件夹中的最后一幅图像,python-3.x,opencv,photo,batching,Python 3.x,Opencv,Photo,Batching,我正在尝试将批处理添加到我正在制作的OpenCV python脚本中,我一辈子都看不出我做错了什么。我是这方面的初学者,所以这可能有点愚蠢。最后,我希望脚本读取脚本当前工作目录中的每个图像文件,然后根据openCV中的人脸检测进行裁剪,并将这些同名的裁剪图像输出到CWD中的文件夹中。现在它所做的只是将文件夹中的最后一个图像输出到输出文件夹中。知道自己在做什么的人有什么想法吗 import cv2 import sys import os.path import glob #Cascade pa

我正在尝试将批处理添加到我正在制作的OpenCV python脚本中,我一辈子都看不出我做错了什么。我是这方面的初学者,所以这可能有点愚蠢。最后,我希望脚本读取脚本当前工作目录中的每个图像文件,然后根据openCV中的人脸检测进行裁剪,并将这些同名的裁剪图像输出到CWD中的文件夹中。现在它所做的只是将文件夹中的最后一个图像输出到输出文件夹中。知道自己在做什么的人有什么想法吗

import cv2
import sys
import os.path
import glob

#Cascade path
cascPath = 'haarcascade_frontalface_default.xml'

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

# Read Images
images = glob.glob('*.jpg')
for i in images:
    image = cv2.imread(i,1)

#Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Find face(s) using cascade
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1, #size of groups
    minNeighbors=5, #How many groups around are detected as face for it to be valid
    minSize=(300, 300) #Min size in pixels for face
)

# Outputs number of faces found in image
print('Found {0} faces!'.format(len(faces)))

# Places a rectangle on face (For debugging, wont be in crop version)
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 255), 4)

# Resizes image to fit monitor and displayes it
imOut = cv2.resize(image, (750, 1142))
#cv2.imshow("Faces found", imS)
#cv2.waitKey(0)

#Saves image to output folder and creates folder if it doesnt exist
if not os.path.exists('output'):
    os.makedirs('output')
os.chdir('output')
cv2.imwrite(i, imOut)
您要做的是:逐个打开每个图像,当您到达最后一个图像时,对最后一个图像应用操作

如果只在第一个for循环下包含要应用于1个图像的所有操作,则可以轻松解决此问题。注意缩进,这就是你在这里做错的地方

images = glob.glob('*.jpg')
for i in images:
    image = cv2.imread(i,1)

    #Convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    #do all your operations here

我在代码中做了多次更正

  • 您需要提供
    haarcascade\u frontalface\u default.xml的完整路径
  • 例如:在Unix系统中:

    cascPath = 'opencv/data/haarcascades/haarcascade_frontalface_default.xml'
    
  • 您不应该在循环期间创建目录。您应该在循环之前创建它
  • 您无需更改目录即可保存图像。只需在图像之前添加路径
  • 缩进很重要,否则可能会有困难
示例代码:

import cv2
import os.path
import glob

# Cascade path
cascPath = '/opencv/data/haarcascades/haarcascade_frontalface_default.xml'

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

if not os.path.exists('output'):
    os.makedirs('output')

# Read Images
images = glob.glob('images/*.jpg')
for c, i in enumerate(images):
    image = cv2.imread(i, 1)

    # Convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Find face(s) using cascade
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,  # size of groups
        minNeighbors=5,  # How many groups around are detected as face for it to be valid
        minSize=(300, 300)  # Min size in pixels for face
    )

    # Outputs number of faces found in image
    print('Found {0} faces!'.format(len(faces)))

    # Places a rectangle on face (For debugging, wont be in crop version)
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 4)

    if len(faces) > 0:
        # Resizes image to fit monitor and displayes it
        imOut = cv2.resize(image, (750, 1142))
        # cv2.imshow("Faces found", imS)
        # cv2.waitKey(0)

        # Saves image to output folder and creates folder if it doesnt exist

        # os.chdir('output')
        img_name = "output/out_{}.png".format(c)
        cv2.imwrite(img_name, imOut)
示例输出:


有趣的是,我想知道这是否是问题所在,并尝试了它,但得到了以下错误:回溯(上次的最新调用):文件“C:\Users\Order Desk 2\Desktop\FaceDetect\Images\face\u detect\u cv3.py”,第18行,灰色=cv2.cvtColor(image,cv2.COLOR\u BGR2GRAY)cv2.error:OpenCV(3.4.11)C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-157r7wnb\opencv\modules\imgproc\src\color.cpp:182:错误:(-215:断言失败)_函数“cv::cvtColor”中的src.empty()通常是在无法读取文件时得到的。我是一次给它一个图像还是一次给它所有图像?更新:使用缩进,它运行一次循环并编辑第一张照片,然后抛出上述错误(-215断言失败)并停止。使用imread的ret参数并测试图像是否已成功加载。当然,跳过e上的循环,你可以打印i,看看哪个图像文件给出了这个问题。这个解决方案工作得很好。谢谢你的详细解释!
if not os.path.exists('output'):
  os.makedirs('output')
img_name = "output/out_{}.png".format(c) # c is the counter  
import cv2
import os.path
import glob

# Cascade path
cascPath = '/opencv/data/haarcascades/haarcascade_frontalface_default.xml'

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

if not os.path.exists('output'):
    os.makedirs('output')

# Read Images
images = glob.glob('images/*.jpg')
for c, i in enumerate(images):
    image = cv2.imread(i, 1)

    # Convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Find face(s) using cascade
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,  # size of groups
        minNeighbors=5,  # How many groups around are detected as face for it to be valid
        minSize=(300, 300)  # Min size in pixels for face
    )

    # Outputs number of faces found in image
    print('Found {0} faces!'.format(len(faces)))

    # Places a rectangle on face (For debugging, wont be in crop version)
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 4)

    if len(faces) > 0:
        # Resizes image to fit monitor and displayes it
        imOut = cv2.resize(image, (750, 1142))
        # cv2.imshow("Faces found", imS)
        # cv2.waitKey(0)

        # Saves image to output folder and creates folder if it doesnt exist

        # os.chdir('output')
        img_name = "output/out_{}.png".format(c)
        cv2.imwrite(img_name, imOut)