python 如何将列表索引转换为整数?

vwkv1x7d  于 2023-02-03  发布在  Python
关注(0)|答案(1)|浏览(208)

我是python的新手,我正在使用python和pytesseract创建一个文本检测应用程序。但是我收到了以下错误,因为我想删除空的'',但变量是一个列表,我试图将其转换为字典。
我已经尝试了不同的算法来将它转换回字典,但是它就是不起作用。下面是代码。

`import cv2
from PIL import Image
from pytesseract import pytesseract
from pytesseract import Output

pytesseract.tesseract_cmd = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe"

camera = cv2.VideoCapture(0)

while True:
    _, image = camera.read()
    cv2.imshow("Text detection", image)

    if cv2.waitKey(1) & 0xFF == ord("s"):
        cv2.imwrite("Capture.jpg", image)
        break

camera.release()
cv2.destroyAllWindows()

img = cv2.imread("Capture.jpg")

image_data = pytesseract.image_to_data(img, output_type=Output.DICT)

for i, word, in enumerate(image_data["text"]):
    if word != "":
        x, y, w, h = image_data["left"][i], image_data["top"][i], image_data["width"][i],        image_data["height"][i]
        cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 3)
        cv2.putText(img, word, (x,y-16), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)
    # REMOVING '' FROM THE DICTIONARY
    new_list = list(filter(lambda x: x != '', image_data))

if new_list != "":
    # BELOW LINE CAUSES AN ERROR SINCE IT IS NOT A DICTIONARY
    print(new_list["text"])

cv2.imshow("Window", img)
cv2.waitKey(0)`
bkkx9g8r

bkkx9g8r1#

您使用filter语句的方向是正确的。请尝试以下最小示例:

image_data = {'text': ['a', '', 'c']}
new_list = list(filter(lambda x: x != '', image_data['text']))
print(new_list)

它给出了

['a', 'c']

还要注意的是,你应该在for循环之外进行过滤,目前,你是在for循环之内进行过滤的,所以对tesseract找到的每个单词都要重复过滤。

相关问题