Home > Software engineering >  (-215:Assertion failed) !_src.empty() in cv2.cvtColor
(-215:Assertion failed) !_src.empty() in cv2.cvtColor

Time:07-30

I tried to use the following code to read the text on the image, but when I run it, I get error.

import cv2

image_file = "D:\try.png"
img = cv2.imread(image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
img_erode = cv2.erode(thresh, np.ones((3, 3), np.uint8), iterations=1)

contours, hierarchy = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

output = img.copy()

for idx, contour in enumerate(contours):
    (x, y, w, h) = cv2.boundingRect(contour)

    if hierarchy[0][idx][3] == 0:
        cv2.rectangle(output, (x, y), (x   w, y   h), (70, 0, 0), 1)

cv2.imshow("Input", img)
cv2.imshow("Enlarged", img_erode)
cv2.imshow("Output", output)
cv2.waitKey(0)

and error:

line 4, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv- 
python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() 
in function 'cv::cvtColor'

CodePudding user response:

In your code you say

image_file = "D:\try.png" # wrong!

\t is an escape sequence for a tabulator symbol. Any backslash in a regular string, combined with the following character, might be an escape sequence. \\ will cause a literal backslash. \" will cause a literal quote character. \n will cause a newline character. Some other combinations are not recognized escape sequences. They may be taken literally or they may cause the string to be rejected by the language parser or a following step.

You should use "raw" strings ("r-strings") instead:

image_file = r"D:\try.png"

CodePudding user response:

The image path seems to be the problem, it works fine if the image path is correct. but you may need to add a line import numpy as np to make it work.

import cv2
import numpy as np

image_file = "/home/pi/Desktop/output2.jpg"
img = cv2.imread(image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
img_erode = cv2.erode(thresh, np.ones((3, 3), np.uint8), iterations=1)

contours, hierarchy = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

output = img.copy()

for idx, contour in enumerate(contours):
    (x, y, w, h) = cv2.boundingRect(contour)

    if hierarchy[0][idx][3] == 0:
        cv2.rectangle(output, (x, y), (x   w, y   h), (70, 0, 0), 1)

cv2.imshow("Input", img)
cv2.imshow("Enlarged", img_erode)
cv2.imshow("Output", output)
cv2.waitKey(0)
  • Related