Home > OS >  OpenCV not able to read/write a jpg image
OpenCV not able to read/write a jpg image

Time:02-18

I got this very simple code to iterate through a directory, apply canny edge detection on every single image and save every result to a different directory:

import cv2, os

directory = os.listdir('beard/')

for image in directory:
    cv2.imwrite('canny-esult/'   image   '_canny.jpg', cv2.Canny(cv2.imread('bear/'   image), 100, 200))

But this is the error I'm getting:

    cv2.imwrite('canny-esult/'   image   '_canny.jpg', cv2.Canny(cv2.imread('bear/'   image), 100, 200))
cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

CodePudding user response:

I found some errata

bear -> beard

cv2.imwrite('canny-esult/' image '_canny.jpg', cv2.Canny(cv2.imread('beard/' image), 100, 200))

CodePudding user response:

There's a simple typo in cv2.imread('bear/' image). I suppose You want to read file from cv2.imread('beard/' image). Also You might to want to trim extension part from filename with image[:-4] to avoid situation when Your file is named like file.jpg_canny.jpg.

Working code:

import cv2, os

directory = os.listdir('beard/')

for image in directory:
    cv2.imwrite('canny-esult/'   image[:-4]   '_canny.jpg', cv2.Canny(cv2.imread('beard/'   image), 100, 200))

CodePudding user response:

Assertion 215 states that the image size is 0. You've simply made a type in defining the image path which is why you are not able to read the image, and then you try to resize the image and it gives the error since there is no image. Just recheck your image path and once its correct, it should work.

  • Related