OpenCV 仅在 PyCharm 中接受我的路径字符串

OpenCV only accepts my path string in PyCharm

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

File "c:\Users\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\pip-req-build-kh7iq4w7\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

在 PyCharm 中不使用 VS Code 或不直接在 W10 中工作时,相同的代码 运行 没有与此行相关的错误或警告,这对我的理解是陌生的。

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

代码:

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\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\Desktop\ImagetoText\tempITT.png")

首先检查你是否真的有这张图片。

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

imread 找不到图像时不显示错误,但 returns None 和后来的代码 运行 cv.cvtColor(None, cv.COLOR_BGR2RGB) 会给出错误带文本 !_src.empty()

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

您应该在所有函数中使用完整路径

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

顺便说一句:

当您拥有代码 C:\Users\Desktop\ImagetoText 并且您 运行 来自此文件夹时

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

然后 presentItem.save("tempITT.png") 将文件保存在此文件夹 C:\Users\Desktop\ImagetoText 并且您有 C:\Users\Desktop\ImagetoText\tempITT.png,

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

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

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

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

中使用完整路径

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

查看它