Untitled

 avatar
unknown
python
11 days ago
2.2 kB
2
Indexable
import cv2
import pytesseract
import tkinter as tk
from tkinter import filedialog, messagebox
import re

# Đặt đường dẫn Tesseract nếu cần
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

def extract_phone_numbers(text):
    """Tìm số điện thoại từ văn bản OCR"""
    phone_pattern = re.compile(r'(?:(?:\+84|84|0)?[-.\s]?)(\d{2,3})[-.\s]?(\d{3})[-.\s]?(\d{3,4})')
    matches = phone_pattern.findall(text)
    phone_numbers = []
    for match in matches:
        full_number = "0" + match[0] + match[1] + match[2] if not match[0].startswith("0") else match[0] + match[1] + match[2]
        phone_numbers.append(full_number)
    return phone_numbers

def select_image():
    """Chọn ảnh từ hộp thoại"""
    file_path = filedialog.askopenfilename(title="Chọn ảnh", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.bmp")])
    if file_path:
        process_image(file_path)

def process_image(image_path):
    """Nhận diện văn bản từ ảnh và trích xuất số điện thoại"""
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    text = pytesseract.image_to_string(gray, lang="vie")
    phone_numbers = extract_phone_numbers(text)
    
    result_text.delete("1.0", tk.END)  # Xóa nội dung cũ
    result_text.insert(tk.END, f"Văn bản nhận diện:\n{text.strip()}\n\n")
    
    phone_textbox.delete("1.0", tk.END)  # Xóa nội dung cũ của ô số điện thoại
    if phone_numbers:
        phone_textbox.insert(tk.END, "\n".join(phone_numbers))
    else:
        phone_textbox.insert(tk.END, "Không tìm thấy số điện thoại!")

# Tạo giao diện tkinter
root = tk.Tk()
root.title("Nhận diện số điện thoại từ ảnh")
root.geometry("600x500")

btn_select = tk.Button(root, text="Chọn ảnh", command=select_image)
btn_select.pack(pady=10)

result_text = tk.Text(root, height=10, width=70)
result_text.pack(pady=10)

label_phone = tk.Label(root, text="Số điện thoại nhận diện:")
label_phone.pack()

phone_textbox = tk.Text(root, height=5, width=70)
phone_textbox.pack(pady=10)

root.mainloop()
Editor is loading...
Leave a Comment