我正在尝试从名为“Pic1”的附加图像中提取“915ml”。我的代码不起作用。我怎样才能做到这一点?该代码也应该应用于其他示例,例如 915 ml 而不是 915ml,或 915 cl、915l 等。
import cv2
import pytesseract
def extract_capacity(image_path):
# Load the image
image = cv2.imread(image_path)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Preprocess the image (optional)
gray = cv2.medianBlur(gray, 3)
# Perform text extraction using pytesseract
text = pytesseract.image_to_string(gray)
# Find capacity keywords
capacity_keywords = ["ml", "cl", "kg", "liter"]
# Extract capacity values from text
capacity_values = []
for keyword in capacity_keywords:
start_index = text.find(keyword)
if start_index != -1:
# Extract the numerical value before the keyword
value = ""
i = start_index - 1
while i >= 0 and text[i].isdigit():
value = text[i] + value
i -= 1
capacity_values.append((value, keyword))
return capacity_values
# Provide the path to your image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Users\\XXXX\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe'
image_path = "Pic1.jpg"
# Extract capacity values from the image
capacities = extract_capacity(image_path)
# Print the extracted capacity values
for capacity in capacities:
value, unit = capacity
print("Capacity:", value, unit)
嘿哥们,我想你必须幸运地进行预处理,库才能完成它的工作。这是我得到的:
从您的代码中,“text”变量没有输出任何内容。就像这样,没有任何内容被读取。只需打印(文本)即可检查是否如此。所以你不会得到任何输出。
我尝试了不同的设置,得到了这些:
1)
gfsinls MCROWA 圆碗圆形 Mlcmndes gtsm!
是
我T
和
2)
圆碗
i M 麦克罗波 O
Q\Iifii&\i&\”\i\“\ji\’\ii&\z\
@'U)
批号 15052023
都不起作用,但我可以向您提供我使用的设置。但从你的问题来看,你似乎正在使用人工智能,所以最好要求它提供替代的预处理步骤,直到text开始包含某些内容。
我的建议是还有一张更好的照片,放大文字。如果它清晰且定向良好,就不会造成伤害。 您可以使用更好的 OCR 服务。可能基于机器学习。