首页 > 解决方案 > OpenCV 只接受我在 PyCharm 中的路径字符串

问题描述

当我尝试在 PyCharm 中运行我的代码时,它以代码 0 退出,并给出了所需的输出,但是当我尝试在 VS Code 中运行它时,它给出了以下错误:

File "c:\Users\1\Desktop\ImagetoText\ITT2.py", line 21, in <module> img = cv.cvtColor(img, cv.COLOR_BGR2RGB) cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-kh7iq4w7\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

在 VS Code 中或直接在 W10 中不工作时,相同的代码如何在 PyCharm 中运行而没有与此行相关的错误或警告,这与我的理解格格不入。

注意:我尝试调整路径但无济于事。

代码:

from glob import glob
from io import BytesIO
import pytesseract
import cv2 as cv
from tkinter import *
import pyperclip
import os

presentItem = ImageGrab.grabclipboard()

with BytesIO() as f:
    presentItem.save(f, format='PNG')
    presentItem.save('tempITT' + '.png', 'PNG')


pytesseract.pytesseract.tesseract_cmd = 'C:\\Users\\1\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'
img = cv.imread(r"C:\Users\1\Desktop\ImagetoText\tempITT.png")
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
imgtext = pytesseract.image_to_string(img)

pyperclip.copy(imgtext)

os.remove(r"C:\Users\1\Desktop\ImagetoText\tempITT.png")

标签: pythonvisual-studio-codepycharmtesseractpython-tesseract

解决方案


首先检查你是否真的有这个图像。

C:\Users\1\Desktop\ImagetoText\tempITT.png

imread找不到图像时不显示错误,但它会返回None并稍后运行代码,cv.cvtColor(None, cv.COLOR_BGR2RGB)这会导致文本错误!_src.empty()

我认为您的所有问题都始于presentItem.save(...)因为您使用的文件名没有完整路径-因此它可能将其保存在本地文件夹中,而不是保存在 中C:\Users\1\Desktop\ImagetoText,以后imread(r'C:\Users\1\Desktop\ImagetoText\...)找不到它。

您应该在所有功能中使用完整路径

presentItem.save(r'C:\Users\1\Desktop\ImagetoText\tempITT.png', 'PNG')

顺便提一句:

当您有代码C:\Users\1\Desktop\ImagetoText并从此文件夹运行它时

 cd C:\Users\1\Desktop\ImagetoText
 python script.py 

然后presentItem.save("tempITT.png")将文件保存在这个文件夹中C:\Users\1\Desktop\ImagetoText,你有C:\Users\1\Desktop\ImagetoText\tempITT.png

但是如果您为其他文件夹运行代码

 cd other folder 
 python C:\Users\1\Desktop\ImagetoText\script.py 

然后presentItem.save("tempITT.png")将文件保存在您拥有的其他文件夹中C:\other folder\tempITT.png

这可能发生在您的情况下。不同的工具可能以不同的方式运行它,以后presentItem.save(可能会将文件保存在不同的文件夹中 - 您应该使用完整路径presentItem.save()

调用执行代码的文件夹,Current Working Directory您可以使用print( os.getcwd() )


推荐阅读