0

I read an image with OpenCV for processing and copy that image to another directory folder. But I get following error. How can solve this and can copy it perfectly?

    image_file = os.path.join("<ROOT_PATH>", file_)
    image = cv2.imread(image_file, cv2.IMREAD_UNCHANGED)
    image = np.stack([image]*3, axis=-1)  # make image 3-channel
    crop_img = image[int(ymin):int(ymax), int(xmin):int(xmax)]
    plt.imshow(crop_img)
    shutil.copy2(crop_img, "<dst_folder>")

Error:

TypeError: expected str, bytes or os.PathLike object, not numpy.ndarray

Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
  • 3
    I believe you should just use cv2 save function rather than shutil, since you are 'cropping' the image which makes it a new image rather than just copying the file from A to B. If you were just planning to copy the image, you need to pass the source path rather than crop_img – Jason Chia Jan 22 '21 at 13:15
  • Possible duplicate of: https://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image – sagarr Jan 22 '21 at 13:19

1 Answers1

1

shutil copies file objects directly. Specifically, copy2 will copy the contents of a file directly, which can be in string, bytes, or os.PathLike form. Since you are modifying the image with opencv, and you have the numpy form, it might be easier to just call imsave:

cv2.imwrite(os.path.join("<dst_folder>", os.path.basename("<ROOT_PATH>")), crop_img)
M Z
  • 4,571
  • 2
  • 13
  • 27