OpenCV-Python: img is not a numpy array, neither a scalar

13,984

Well opencv is right, you save originalImage, but originalImage is a string (the filename, your first line).

You need to cv2.imread(..) your image into a numpy array first:

originalImage = cv2.imread("test-image.jpg")
savedImage = cv2.imwrite("saved-test-image.jpg",originalImage)

If you simply want to copy an image file however, there is no need to load it into memory, you can simply copy the file, without using opencv:

from shutil import copyfile

originalImage = "test-image.jpg"
copyfile(originalImage,"saved-test-image.jpg")

In this case, it will simply copy the file - regardless what its content is - so even if it is a corrupt image, or not an image at all, it will be copied.

Share:
13,984
Andrea
Author by

Andrea

Updated on June 29, 2022

Comments

  • Andrea
    Andrea almost 2 years

    I'm trying to write a save image function. The below code is expected to create a copy of the original image as saved-test-image.jpg.

    originalImage = "test-image.jpg"
    savedImage = cv2.imwrite("saved-test-image.jpg",originalImage)
    

    The execution of the lines gives the follwing back:

    Traceback (most recent call last):
      File "UnitTest.py", line 159, in test_save_and_delete_image
        savedImage = cv2.imwrite('unittest-images/saved-test-image.jpg', originalImage)
    TypeError: img is not a numpy array, neither a scalar
    

    What needs to be changed here?