python - 电报机器人将文本从图像发送回用户
问题描述
使用计算机中的照片时,没有错误,尝试使用电报中发送的照片时,显示以下异常。这是机器人的完整代码,我怀疑一切都是由于变量指示不正确,message.photo[0].file_id
但在互联网上我没有找到可以参考发送照片的确切路径。我是电报机器人的新手,所以我会问你细节和最简单的解释,如果可能的话。我很乐意接受任何批评。
bot = telebot.TeleBot(config.token)
@bot.message_handler(content_types= ["photo"])
def answer_to_photo(message):
image = message.photo[0].file_id
pytesseract.pytesseract.tesseract_cmd = r'C:\OCR\tesseract.exe'
preprocess = "thresh"
image = cv2.imread(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if preprocess == "tresh":
gray = cv2.threshold(gray, 0, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
elif preprocess == "blur":
gray = cv2.median.Blur(gray, 3)
filename = "{}.png".format(os.getpid())
cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open(filename))
os.remove(filename)
bot.send_message(message.chat.id, text)
抛出异常
Traceback (most recent call last):
File "shablon.py", line 58, in <module>
bot.polling(none_stop=True)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\telebot\__init__.py", line 427, in polling
self.__threaded_polling(none_stop, interval, timeout)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\telebot\__init__.py", line 451, in __threaded_polling
self.worker_pool.raise_exceptions()
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-
packages\telebot\util.py", line 111, in raise_exceptions
six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\six.py", line 703, in reraise
raise value
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\telebot\util.py", line 62, in run
task(*args, **kwargs)
File "shablon.py", line 25, in answer_to_photo
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182:
error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
解决方案
解决问题的方法是,用户发来的照片必须先下载到电脑上,经过文字处理和选择后,删除这张照片,以免占用空间。
推荐阅读
- javascript - Javascript:获取 BroadcastChannel 订阅者计数
- ios - 当 CAAnimationGroup 的执行完成时,它会回到初始动画序列并带有抽搐效果
- model-view-controller - ASP WebApi:服务层、业务层和数据访问层
- cqrs - Axon 框架:仅处理由同一 JVM 实例发布的事件?
- express - 我们可以在 AWS Amplify 中使用 Express JS 吗?
- javascript - 有没有办法将一个表单中的值与另一个表单结合起来?
- scala - 遇到死代码并出现 x 个致命警告
- android-emulator - 启动模拟器时 Android Studio 挂起
- java - 在 ImageView 中对齐位图图像 - CS50 Pokedex Android
- javascript - 如何缩放 three.js 精灵?