import argparse
from PIL import Image
import pytesseract
import numpy as np
import json
def image_to_text(image):
pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
result = pytesseract.image_to_string(image, lang='eng')
return result
if __name__ == "__main__":
ap = argparse.ArgumentParser("Image content into text")
ap.add_argument("--input", required = True, help='path to input image')
args = ap.parse_args()
img = Image.open(args.input)
print(img.size)
xy_coords = np.flip(np.column_stack(np.where(np.array(img) >= 0)), axis = 1)
value = np.hstack([xy_coords])
print(value)
list = value
js = json.dumps(list)
jsonfile = open("coordinates.json","w")
jsonfile.write(js)
jsonfile.close()
print(image_to_text(img))
错误:
Traceback (most recent call last):
File "C:\Users\Chaitanya\Desktop\image\code.py", line 26, in <module>
js = json.dumps(list)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type ndarray is not JSON serializable
首先,永远不要使用函数名作为变量名。通过将变量分配为列表,您只需覆盖您需要的列表函数。所以使用一些更好的变量名。
问题:
错误说明了一切。
TypeError: Object of type ndarray is not JSON serializable
json 数据可以携带以下类型的值:
请参阅JSON 简介
在您的代码中,您尝试添加如下列表或数据:
value = np.hstack([xy_coords])
print(value)
list = value
js = json.dumps(list)
您正在尝试转储list
,它指向value
的numpy.ndarray
不是 a list
。Json 确实支持list
类型,但不支持numpy.ndarray
.
因此,将命名的变量类型更改list
为列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句