0

I tried running the code below, it runs successfully but the images are not saved anywhere on the system. Does anyone know where the problem is or the solution?

import cv2
import time

# open the default camera
cap = cv2.VideoCapture(0)

# set the width and height of the frame
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# set the start time
start_time = time.time()

# loop through the frames
print("looping through frames")
while True:
    # capture a frame
    ret, frame = cap.read()

    t = time.localtime()
    current_time = time.strftime("%H:%M:%S", t)

    # define the output file name and format
    output_file = f'/Frame_{current_time}.jpg'
    output_format = 'JPEG'

    # check if the frame is captured successfully
    if not ret:
        break

    # calculate the elapsed time
    elapsed_time = time.time() - start_time

    # check if 1 second has passed
    if elapsed_time >= 1:
        print("1 second passed")
        # save the frame as an image file
        cv2.imwrite(f'/TestFrames/{output_file}', frame)
        print(output_file)
        print("image saved")

        # reset the start time
        start_time = time.time()
        print("time reset")

    # display the frame
    cv2.imshow('frame', frame)

    # check for the 'q' key to quit
    if cv2.waitKey(1) == ord('q'):
        break

# release the camera and close all windows
cap.release()
cv2.destroyAllWindows()

I tried running the code below, it runs successfully but the images are not saved anywhere on the system.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Darsh. S.
  • 13
  • 3
  • 1
    If it doesn't do what it's supposed it, I wouldn't call it "successful". | Are the file names you generate valid? Is the path correct? Does the directory exist? (In this particular case, is there a directory named `TestFrames` at the root of your filesystem?) – Dan Mašek Apr 29 '23 at 18:29
  • does the `/TestFrames/` directory even exist? if not, why not? that's an absolute path. the directory would have to be in the root of the file system. – Christoph Rackwitz Apr 30 '23 at 10:33
  • Yes, the directory named `TestFrames` exists in the root directory. The main issue is with the saving of the image. – Darsh. S. May 01 '23 at 05:44
  • Okay so I tried changing the path for saving the image from `cv2.imwrite(f'/TestFrames/{output_file}', frame)` to `cv2.imwrite(output_file, frame)`. The images are getting saved but the only issue is that they are getting saved in `D:\pythonProject1\KnownFaces` instead of `D:\pythonProject1`. Can anyone explain this? – Darsh. S. May 01 '23 at 05:48

1 Answers1

1

The main issue is that the image file name contains colon (:) characters, and colon character is invalid character (at least for a Windows) file name.

For testing, we may check the returned status of cv2.imwrite (status is True for success and False for failure):

is_ok = cv2.imwrite(f'/TestFrames/{output_file}', frame)
print(output_file)

if is_ok:
    print("image saved")
else:
    print("Failed saving the image")

Assuming we are using Windows:

We may replace the : characters with _ for example:

output_file = f'Frame_{current_time}.jpg'
output_file = output_file.replace(":", "_")

The following answer recommends to replace the colon with a unicode character "" that looks like colon, but cv2.imwrite doesn't support unicode characters (at least not in Windows).

In case we want to use the '\ua789' unicode character we may use cv2.imencode and binary file writing:

with open(f'/TestFrames/{output_file}', 'wb') as f:  # Open image file as binary file for writing
    cv2.imencode('.'+output_format, frame)[1].tofile(f)  # encode the image as JPEG, and write the encoded image to the file (use [1] because cv2.imencode returns a tuple).

Code sample that uses the unicode character instead of colon:

import cv2
import time

# open the default camera
cap = cv2.VideoCapture(0)

# set the width and height of the frame
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# set the start time
start_time = time.time()

# loop through the frames
print("looping through frames")
while True:
    # capture a frame
    ret, frame = cap.read()

    t = time.localtime()
    current_time = time.strftime("%H:%M:%S", t)

    # define the output file name and format
    output_file = f'Frame_{current_time}.jpg'
    output_file = output_file.replace(":", "\ua789")  # Replace colon character with a character that looks like colon
    #output_file = output_file.replace(":", "_")  # Replace colon character with a underscore character
    output_format = 'JPEG'

    # check if the frame is captured successfully
    if not ret:
        break

    # calculate the elapsed time
    elapsed_time = time.time() - start_time

    # check if 1 second has passed
    if elapsed_time >= 1:
        print("1 second passed")

        # save the frame as an image file
        #is_ok = cv2.imwrite(f'/TestFrames/{output_file}', frame)

        with open(f'/TestFrames/{output_file}', 'wb') as f:  # Open image file as binary file for writing
            cv2.imencode('.'+output_format, frame)[1].tofile(f)  # encode the image as JPEG, and write the encoded image to the file (use [1] because cv2.imencode returns a tuple).

        print(output_file)
        print("image saved")

        # reset the start time
        start_time = time.time()
        print("time reset")

    # display the frame
    cv2.imshow('frame', frame)

    # check for the 'q' key to quit
    if cv2.waitKey(1) == ord('q'):
        break

# release the camera and close all windows
cap.release()

cv2.destroyAllWindows()
Rotem
  • 30,366
  • 4
  • 32
  • 65
  • I tried the above method but the image isn't getting saved in the system. I used the `if is_ok` block to detect it. Replacing the colon with underscore didn't allow the image to be saved. And I also tried the **wb** method but since the image is not saved, the **wb** method can't overwrite the `output_file`. Do you have any other solutions for this problem? – Darsh. S. May 01 '23 at 05:36
  • Are you using Windows or Linux or Mac (or other OS)? – Rotem May 01 '23 at 06:50
  • I'm using windows – Darsh. S. May 01 '23 at 15:49
  • According to your other comments, it looks like `TestFrames` is inside `D:\pythonProject1`, and not in the "root" (not in `D:\TestFrames`). What is the full path of `TestFrames`? Is it `D:\TestFrames` or `D:\pythonProject1\TestFrames` or somewhere else? – Rotem May 01 '23 at 18:38
  • The full path of `TestFrames` is `D:\pythonProject1\TestFrames`. – Darsh. S. May 02 '23 at 05:50
  • I looks like you intended to use **relative path** but used absolute path instead. Replace `cv2.imwrite(f'/TestFrames/{output_file}', frame)` with `cv2.imwrite(f'../TestFrames/{output_file}', frame)`. The `../` means going one level up from `D:\pythonProject1\KnownFaces` to `D:\pythonProject1`, and then from `D:\pythonProject1` to `D:\pythonProject1\TestFrames`. – Rotem May 02 '23 at 08:05