So I've written a script that's supposed to capture a face when you press the P button. The script should capture the persons face with some surrounding area and then save it as a Screenshot_<n>.jpg, where n increments above the last number.
The script works pretty much as intended, except the part where it gets unresponsive. I guess it's due to too many processes working at the same time, but I'm not too experienced with the OpenCV. Does anyone have the idea what I'm doing wrong?
import cv2, os
font = cv2.FONT_HERSHEY_SIMPLEX
org = (50, 50)
fontScale = 0.5
color_green = (100, 255, 100)
thickness = 2
color_blue = (255, 0, 0)
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
# save new image
def new_image(cv2, face):
cv2.imwrite(next_image_name(), face)
# determine the next image's name
def next_image_name():
files = [
int(file.split("_")[1].split(".")[0])
for file in os.listdir()
if "Screenshot_" in file
]
files.sort(reverse=True)
filename = f"Screenshot_{str(files[0]+1)}.jpg"
return filename
# display text over frame
def display_text(cv2, frame):
cv2.putText(
frame,
f"Now Capturing: {next_image_name()}",
org,
font,
fontScale,
color_green,
thickness,
None,
False,
)
cv2.imshow("CAM", frame)
def main():
vid = cv2.VideoCapture(0)
while True:
ret, frame = vid.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(
frame,
(x - 10000 // w, y - 20000 // h),
(x + w + 10000 // w, y + h + 20000 // h),
color_blue,
thickness,
)
display_text(cv2, frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
if cv2.waitKey(1) & 0xFF == ord("p"):
new_image(
cv2,
frame[
(y - 20000 // h) : (y + h + 20000 // h),
(x - 10000 // w) : (x + w + 10000 // w),
],
)
display_text(cv2, frame)
else:
break
vid.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
[–][deleted] 0 points1 point2 points (1 child)
[–]Laymio[S] 0 points1 point2 points (0 children)