-3

I am using Jupyter Notebook for practicing coding (if it's relevant) and trying to use cv2 in order to take pictures using my webcam. However, whenever I take a picture and have that picture saved, the previous picture gets overwritten because of having the same file name. How do I keep this from not happening?

import cv2 
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
    try:
        check, frame = webcam.read()
        print(check) 
        print(frame) 
        cv2.imshow("Capturing", frame)
        key = cv2.waitKey(1)
        if key == ord('s'): 
            cv2.imwrite(filename='saved_img.jpg', img=frame)
            webcam.release()
            cv2.waitKey(1650)
            cv2.destroyAllWindows()
            break
        elif key == ord('q'):
            print("Turning off camera.")
            webcam.release()
            print("Camera off.")
            print("Program ended.")
            cv2.destroyAllWindows()
            break
        
    except(KeyboardInterrupt):
        print("Turning off camera.")
        webcam.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

'saved_img' image file always gets overwritten whenever I capture...

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • 2
    name differently ? increase a counter that you use in the name – azro May 21 '22 at 12:47
  • @azro yes, that's I'm asking, how do you add a counter to have the name change like saved_image1,saved_image2, etc...? – Sway the Destroyer 'STD' May 21 '22 at 12:56
  • Did you try a search for "how to add a number to a string"? https://stackoverflow.com/a/11999258/2393191 you could also use a generated GUID as your filename: https://stackoverflow.com/a/534847/2393191 – Micka May 21 '22 at 14:35
  • I can't understand how you reach to use such code (even if you copied it) and don't even know how to increase an int, and concat an int to a string, that is very basic. What exact thing don't you know in that ? – azro May 22 '22 at 07:16
  • @azro this is just a code given to us for our data science class, but personally I am just starting to learn programming itself. So please don't be disrespectful. – Sway the Destroyer 'STD' May 22 '22 at 15:04
  • @Micka my problem is that the program terminates once an image is captured and saved through imwrite() function. So using a counter to add a number to a string will be useless, I need something that checks if the file name already exists in the path then does something about it. – Sway the Destroyer 'STD' May 22 '22 at 15:08
  • Then use a counter and check for file existence until the counter reaches a value where no file exists. Or use a random name by GUID. Or use current system time utc timestamp in your filename, or... There are many options and basically it is about what kind of requirements you do have for the filenames. – Micka May 22 '22 at 15:48

2 Answers2

1

You can use the isfile function from the os module:

import os

if os.isfile("saved_img.jpg"):
    if input("do you want to overwrite saved_img.jpg? ") == "yes":
        cv2.imwrite(filename='saved_img.jpg', img=frame)
else:
    cv2.imwrite(filename='saved_img.jpg', img=frame)
Glitch__
  • 304
  • 1
  • 10
1

If you need to restart-proof, you can check how many files have been saved before, so that code allows (as you said in comment) one image per run of th program

nb_files = len(list(Path(".").glob("saved_img_*.jpg")))
filename = f"saved_img_{nb_files}.jpg"

import cv2
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
    try:
        check, frame = webcam.read()
        print(check)
        print(frame)
        cv2.imshow("Capturing", frame)
        key = cv2.waitKey(1)
        if key == ord('s'):
            cv2.imwrite(filename=filename, img=frame)
            webcam.release()
            cv2.waitKey(1650)
            cv2.destroyAllWindows()
            break

        ...

Here's a variation if one run of the program may create multiple images

nb_files = len(list(Path(".").glob("saved_img_*.jpg")))
i = 0

import cv2
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
    try:
        check, frame = webcam.read()
        print(check)
        print(frame)
        cv2.imshow("Capturing", frame)
        key = cv2.waitKey(1)
        if key == ord('s'):
            cv2.imwrite(filename=f"saved_img_{nb_files + i}.jpg", img=frame)
            i += 1
azro
  • 53,056
  • 7
  • 34
  • 70