首页 > 解决方案 > 电报机器人将文本从图像发送回用户

问题描述

使用计算机中的照片时,没有错误,尝试使用电报中发送的照片时,显示以下异常。这是机器人的完整代码,我怀疑一切都是由于变量指示不正确,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'

标签: pythontelegram-bot

解决方案


解决问题的方法是,用户发来的照片必须先下载到电脑上,经过文字处理和选择后,删除这张照片,以免占用空间。


推荐阅读