(-215:断言失败)在函数'cv::cvtColor'中的_src.empty()!与cv :: imread

17

我正在尝试从图像中识别文本,然后输出文本;然而,出现了以下错误:

Traceback (most recent call last): File "C:/Users/Benji's Beast/AppData/Local/Programs/Python/Python37-32/imageDet.py", line 41, in print(get_string(src_path + "cont.jpg") ) File "C:/Users/Benji's Beast/AppData/Local/Programs/Python/Python37-32/imageDet.py", line 15, in get_string img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(3.4.4) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

图像分辨率为1371x51。 我尝试将src_path上的“/”更改为“\”,但没有起作用。 有什么想法吗?

这是我的代码:

import cv2
import numpy as np
import pytesseract
from PIL import Image
from pytesseract import image_to_string

# Path of working folder on Disk
src_path = "C:/Users/Benji's Beast/Desktop/image.PNG"

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    #  Apply threshold to get image with only black and white
    #img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

    # Remove template file
    #os.remove(temp)

    return result


print('--- Start recognize text from image ---')
print(get_string(src_path + "cont.jpg") )

print("------ Done -------")

我不知道如何修复这个问题,谢谢。


1
你的绝对路径中有空格。尝试将此图像复制到与您的代码相同的目录中并删除绝对部分。 - Saransh Kejriwal
12个回答

20
这意味着您正在传递一个未初始化的变量给:
> cv2.cvtColor()

在这个语句之后:

# Read image with opencv
img = cv2.imread(img_path)

在将img变量传递给cv2.cvtColor()函数之前,您能尝试打印该变量吗?

> print(img) or print(img.shape)

确保读取图像的函数调用成功


没错。在我的情况下,我使用了错误的文件名,这里是png而不是jpg。谢谢你的提示。 - Semo
while True: success, img = cap.read() if img is None: break cv2.imshow("视频", img) if cv2.waitKey(10) & 0xFF == ord('q'): break - Nipun David

8

错误: 在函数'cv::cvtColor'中的'! _src.empty()'表示传递给函数cvtColor的对象为空或不存在。 这里,在下面一行中img是空的。

cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
是以下函数的结果 -
img = cv2.imread(img_path)

img可能为空对象的原因有:

  1. 图像路径不正确,请尝试绝对路径并检查图像文件扩展名。
  2. 图像文件不可访问。可能存在权限问题。

为避免此错误,请检查img对象是否为None,如果不为None,则将其传递给cvtColor函数。

img = cv2.imread(img_path)
if(img is not None):
    cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

5
如果有人通过谷歌搜索此错误信息,但您遇到的错误是针对视频而非图像,则可能的原因之一是您已经没有读取视频帧的帧数了。参考文献: reference
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

使用ret检查视频结尾是常见的做法,但你可能忘记在检查帧是否可用之前提到它或对帧进行操作(ret == True),就像我一样。干杯。


3
这个错误发生在图像格式与Python程序中指定的格式不一致时。 示例:
File Path= /home/user/image.jpg

但在Python程序中,您将图像读取为JPEG格式。

img = cv.imread("image.jpeg")

那么您将会面临这个错误。 在imread()方法中,也需要将文件格式更改为.jpg。


2
这个方法对我有用,谢谢Murali。我使用了.jpg而不是.jpeg,因为我习惯了它 :p - vrintle
好的。随时为您效劳 :) - Narmada Muralikrishnan

2
我认为你的源路径应该是:

我认为您的源路径应该是:

src_path = "C:/Users/Benji's Beast/Desktop/"

因为在这里,你已经将图像名称连接起来了:get_string(src_path + "cont.jpg")


1
这个错误发生在图像格式与Python程序指定的格式不一致时。因此,在导入和导出时,请确保文件扩展名相同并加以指定。这对我很有用。

当我在cv2.imread()中忘记指定文件扩展名时,出现了这个错误。 - Raisin

1
此错误可能是由于在 Windows 系统中使用了路径/文件名中的重音符号引起的。

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

1

这些问题是:

src_path = "C:/Users/Benji's Beast/Desktop/image.PNG"

and this one

print(get_string(src_path + "cont.jpg") )

你正在将图像输入文件名从 image.PNG 添加到 image.PNG.cont.jpg
如果你的输入图像文件名是 cont.jpg,并且它位于你的桌面上,请尝试使用以下代码进行替换:
src_path = "C:\Users\Benji's Beast\Desktop\"

并且

print(get_string(src_path + "cont.jpg") )

0
如果路径和图像名称已经验证并且正确,那么只需关闭Jupyter笔记本(或您正在使用的任何平台)并重新启动它。这对我有用。

0

在 Windows 10 64 位操作系统下,使用 Python 3.7.5,以下代码可以正常运行:

这段代码无法正常运行:image = cv2.imread('C:\ML\test.jpg')

这段代码可以正常运行:image = cv2.imread('C:\\ML\\test.jpg')


这个案例是极其常见的FAQ https://dev59.com/fnA85IYBdhLWcg3wEPVL 的简单重复。 - tripleee
我加了我的评论,以帮助未来的人们... - steve
似乎你的问题与这个特定的问题无关,但同样地,我添加的评论希望能帮助那些真正遇到这个问题的人。 - tripleee
实际上它是相关的,因为它涉及到与Windows相关的"C:/..."等内容。无论如何,如果能帮助到某个人,那就很好。 - steve
但是问题中的代码使用的是正斜杠,所以它们并没有遇到这个特定的问题。链接的问题解释了为什么正斜杠更可取,但这不是你将其作为答案发布的问题追溯的原因。 - tripleee
我觉得你没有理解我的意思,但没关系。祝你有美好的一天。 - steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接