我正在嘗試創建一個排序系統,其中根據是否有臉對影像進行排序。它似乎并沒有像預期的那樣運行。對第一張影像進行排序后,回圈停止作業,我似乎無法弄清楚出了什么問題。(我知道它是多么低效)。總而言之,我希望得到一些關于為什么它可能不起作用的指示。
import cv2
import os
from PIL import Image
lst = [
file
for file in os.listdir("~/face detect")
if file.endswith(".jpg")
]
for image in lst:
face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades "haarcascade_frontalface_default.xml")
img = cv2.imread(image)
gray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img,
scaleFactor= 1.15,
minNeighbors= 15)
print("Found {0} faces!".format(len(faces)))
if len(faces) > 0:
directory = '~/Face'
os.chdir(directory)
output_filename = "".join(image.split('.')[:-1]) "_face.jpg" # Set output file name
cv2.imwrite(output_filename, img)
else:
directory = '~/No_face'
os.chdir(directory)
output_filename = "".join(image.split('.')[:-1]) "_no_face.jpg" # Set output file name
cv2.imwrite(output_filename, img )
print("image sorted")
# resized=cv2.resize(img,(int(img.shape[1]/3), int(img.shape[0]/3)))
# cv2.imshow("Deteced-face", resized)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
uj5u.com熱心網友回復:
您的主要問題是路徑。讓我猜猜你的 python 檔案在 '~/face detect' 檔案夾中,這就是讀取第一張影像的原因。然后os.chdir(directory)來了,找不到更多的影像。我以一種不那么天真的方式更正了使用檔案夾的路徑(正確的方法是使用 glob,但我不想使答案過于復雜)。另請注意,無需更改 dir 即可保存到它,事實上我cv2.CascadeClassifier在回圈外初始化了一次
import cv2
import os
INPUT_DIR = './input'
FACES_DIR = './out_faces'
NO_FACES_DIR = './out_no_faces'
images_names = [file for file in os.listdir(INPUT_DIR) if file.endswith(".jpg")]
print(images_names)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades "haarcascade_frontalface_default.xml") # init once
for image_name in images_names:
img = cv2.imread('{}/{}'.format(INPUT_DIR, image_name)) # notice the INPUT_DIR
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.15, minNeighbors=15)
print("Found {0} faces!".format(len(faces)))
if len(faces) > 0:
output_fp = '{}/{}'.format(FACES_DIR, image_name.replace('.jpg', '_face.jpg')) # notice the FACES_DIR
for (x, y, w, h) in faces: # if you want to add the face that was detected
cv2.rectangle(img, (x, y), (x w, y h), (0, 255, 0), 2)
else:
output_fp = '{}/{}'.format(NO_FACES_DIR, image_name.replace('.jpg', '_no_face.jpg')) # notice the NO_FACES_DIR
cv2.imwrite(output_fp, img)
print("image {} saved at {}".format(image_name, output_fp))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438420.html
