I'm currently working in a face recognition project using OpenCV and python. The thing is, that the accuracy of the face recognition is not so good, so I'm thinking about adding more images in the data path, with different lighting, backgrounds etc in order to improve it. The problem here is that whenever I use
cv2.imwrite("data/User."+str(face_ID)+"."+str(count)+".jpg", gray[y:y+h, x:x+w])
it overwrites the previous saved images in the path.
I works fine, but I just want to do something like appending the new images to the path, every time I run the function.
Here is the data generator section.
def data_generator():
count = 0
# asking user for data input
face_ID = input("[INFO] Please enter user ID and press <return> ")
print("[INFO] Thank you\n Now please look at the camera and wait.")
# start the video capture
cap = cv2.VideoCapture(0)
try:
while True:
# Here we detect the face
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detecting faces
faces = detector.detectMultiScale(gray,
scaleFactor = 1.3,
minNeighbors = 5,
minSize= (20, 20)
)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_img = img[y:y+h, x:x+w]
count += 1
cv2.imwrite("data/User."+str(face_ID)+"."+str(count)+".jpg", gray[y:y+h, x:x+w])
cv2.imshow('img', img)
k = cv2.waitKey(10) & 0xff
if k == 27:
break
elif count >= 30:
break
except KeyboardInterrupt:
pass
print("[INFO] Data gathered.")
print("[INFO] Saving Data.")
print("[INFO] Exiting program and cleanup stuff")
cap.release()
cv2.destroyAllWindows()
I think the problem is you have your cv2.imwrite("data/User."+str(face_ID)+"."+str(count)+".jpg", gray[y:y+h, x:x+w])
outside your while True:
loop.
I also use os.path.join
and .format
for saving images. So you can define a directory outside the loop and use .format
like this for better overview IMO:
cv2.imwrite(os.path.join(directory, 'User.{}.{}.jpg'.format(face_ID, count)), gray[y:y+h, x:x+w])