scaner 6 months ago
parent aecd2576b5
commit e3f7d5b275

@ -1,5 +1,6 @@
from tkinter import * from tkinter import *
import tkinter as tk import tkinter as tk
import subprocess
from tkinter import filedialog from tkinter import filedialog
import pymysql import pymysql
from flask import Flask, render_template, request, redirect, url_for from flask import Flask, render_template, request, redirect, url_for
@ -31,7 +32,10 @@ def userinfo_query(username, password):
def user_register(): def user_register():
deng = Tk() deng = Tk()
deng.title("注册") deng.title("注册")
deng.geometry("300x200") deng.geometry("300x200+280+580")
# 在GUI中添加新的输入字段和按钮 # 在GUI中添加新的输入字段和按钮
label_new_username = Label(deng, text="新账号:") label_new_username = Label(deng, text="新账号:")
@ -43,17 +47,19 @@ def user_register():
entry_new_password = Entry(deng, show="*") entry_new_password = Entry(deng, show="*")
entry_new_password.pack() entry_new_password.pack()
btn_register = Button(deng, text="注册", command=lambda: register_action(entry_new_username, entry_new_password)) btn_register = Button(deng, text="注册", command=lambda: register_action(deng, entry_new_username, entry_new_password))
btn_register.pack(side='right', padx=50) btn_register.pack(side='right', padx=50)
def register_action(entry_new_username, entry_new_password): def register_action(deng, entry_new_username, entry_new_password):
cursor.execute("INSERT INTO user (`username`, `password`) VALUES (%s, %s)", cursor.execute("INSERT INTO user (`username`, `password`) VALUES (%s, %s)",
(entry_new_username.get(), entry_new_password.get())) (entry_new_username.get(), entry_new_password.get()))
conn.commit() conn.commit()
deng.destroy()
print("注册成功!") print("注册成功!")
def user_login(): def user_login():
global count global count
count = 2 count = 2
@ -68,31 +74,45 @@ def user_login():
label_message.config(text="账号错误!") label_message.config(text="账号错误!")
else: else:
if password_input in password_list: if password_input in password_list:
print("debug1")
windows.destroy()
def choose_folde(): def choose_folde():
print("debug2")
root.destroy() root.destroy()
root5 = tk.Tk() root5 = tk.Tk()
root5.title('选择图片') root5.title('选择图片')
root5.geometry('300x300') root5.geometry('300x300')
folder_path = filedialog.askdirectory() filename = filedialog.askopenfilename(
if folder_path: initialdir="/", # 设置对话框初始打开的目录
print(f"您选择了文件夹: {folder_path}") title="选择图片",
filetypes=(("图片文件", "*.jpg;*.png;*.gif"), ("所有文件", "*.*")) # 指定文件类型过滤器
root.mainloop() )
def callback(): if filename: # 如果用户选择了文件
rootback = tk.Tk() # 使用subprocess运行另一个Python脚本并将图片路径作为参数传递
rootback.title('用户界面') root5.destroy()
rootback.geometry('300x300') subprocess.run(["python", "scan.py", "-i", filename])
tk.Label(rootback, text='请选择你的功能').pack() exit()
tk.Button(rootback, text="选择需要扫描的图片", command=choose_folde).pack()
rootback.mainloop() # root.mainloop()
# def callback():
# rootback = tk.Tk()
# rootback.title('用户界面')
# rootback.geometry('300x300')
# tk.Label(rootback, text='请选择你的功能').pack()
# tk.Button(rootback, text="选择需要扫描的图片", command=choose_folde).pack()
# rootback.mainloop()
# windows.destroy() # windows.destroy()
root = tk.Tk() root = tk.Tk()
root.title('用户界面') root.title('用户界面')
root.geometry('300x300') root.geometry('300x300')
tk.Label(root, text='请选择你的功能').pack() tk.Label(root, text='请选择你的功能').pack()
tk.Button(root, text="选择需要扫描的图片", command=choose_folde).pack() tk.Button(root, text="选择需要扫描的图片", command=choose_folde).pack()
tk.mainloop() # tk.mainloop()
print("debug3")
else: else:
label_message.config(text="密码错误!还可以尝试{}".format(count)) label_message.config(text="密码错误!还可以尝试{}".format(count))
count += 1 count += 1
@ -104,6 +124,7 @@ def user_login():
windows = Tk() windows = Tk()
windows.title("登录") windows.title("登录")
windows.geometry("300x200") windows.geometry("300x200")
# windows.configure(bg='#3ffff3')
label_username = Label(windows, text="账号:") label_username = Label(windows, text="账号:")
label_username.pack() label_username.pack()
entry_username = Entry(windows) entry_username = Entry(windows)
@ -114,6 +135,7 @@ entry_password = Entry(windows, show="*")
entry_password.pack() entry_password.pack()
btn_login = Button(windows, text="登录", command=user_login) btn_login = Button(windows, text="登录", command=user_login)
print("debug0")
btn_login.pack(side='left', padx=50) btn_login.pack(side='left', padx=50)
entry_password.pack() entry_password.pack()
btn_login = Button(windows, text='注册', command=user_register) btn_login = Button(windows, text='注册', command=user_register)

@ -6,11 +6,21 @@ import pytesseract
import os import os
from PIL import Image from PIL import Image
# 设置参数 # def process_image(image_path):
ap = argparse.ArgumentParser() # try:
ap.add_argument("-i", "--image", required = True, # # 使用Pillow库打开并显示图片
help = "Path to the image to be scanned") # with Image.open(image_path) as img:
args = vars(ap.parse_args()) # img.show()
# # 在这里添加更多处理图片的代码...
# except IOError:
# print(f"无法打开图片: {image_path}")
def main():
parser = argparse.ArgumentParser(description="处理图片的脚本")
parser.add_argument("-i", "--image", required=True, help="指定要处理的图片的路径")
args = parser.parse_args()
# process_image(args.image)
print("main")
def order_points(pts): def order_points(pts):
# 一共4个坐标点 # 一共4个坐标点
@ -71,39 +81,48 @@ def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
resized = cv2.resize(image, dim, interpolation=inter) resized = cv2.resize(image, dim, interpolation=inter)
return resized return resized
# 设置参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to the image to be scanned")
args = vars(ap.parse_args())
print("arg")
print(__name__)
if __name__ == "__main__":
main()
# 读取输入 # 读取输入
image = cv2.imread(args["image"]) image = cv2.imread(args["image"])
#坐标也会相同变化 #坐标也会相同变化
ratio = image.shape[0] / 500.0 ratio = image.shape[0] / 500.0
orig = image.copy() orig = image.copy()
image = resize(orig, height = 500) image = resize(orig, height = 500)
# 预处理 # 预处理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 色彩空间转换
gray = cv2.GaussianBlur(gray, (5, 5), 0) gray = cv2.GaussianBlur(gray, (5, 5), 0) # 高斯模糊
edged = cv2.Canny(gray, 75, 200) edged = cv2.Canny(gray, 75, 200)
# 展示预处理结果 # 展示预处理结果
print("STEP 1: 边缘检测") print("STEP 1: 边缘检测")
cv2.imshow("Image", image) # cv2.imshow("Image", image)
cv2.imshow("Edged", edged) # cv2.imshow("Edged", edged)
cv2.waitKey(0) # cv2.waitKey(0)
cv2.destroyAllWindows() # cv2.destroyAllWindows()
# 轮廓检测 # 轮廓检测
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0] cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # 降序排列+切片
# 遍历轮廓 # 遍历轮廓
for c in cnts: for c in cnts:
# 计算轮廓近似 # 计算轮廓近似
peri = cv2.arcLength(c, True) peri = cv2.arcLength(c, True)
# C表示输入的点集 # C表示输入的点集(数组)
# epsilon表示从原始轮廓到近似轮廓的最大距离它是一个准确度参数 # epsilon表示从原始轮廓到近似轮廓的最大距离它是一个准确度参数
# True表示封闭的 # True表示封闭的
approx = cv2.approxPolyDP(c, 0.05 * peri, True) approx = cv2.approxPolyDP(c, 0.10 * peri, True) # 近似
# 4个点的时候就拿出来 # 4个点的时候就拿出来
if len(approx) == 4: if len(approx) == 4:
@ -113,9 +132,9 @@ for c in cnts:
# 展示结果 # 展示结果
print("STEP 2: 获取轮廓") print("STEP 2: 获取轮廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2) cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image) # cv2.imshow("Outline", image)
cv2.waitKey(0) # cv2.waitKey(0)
cv2.destroyAllWindows() # cv2.destroyAllWindows()
# 透视变换 # 透视变换
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio) warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
@ -124,27 +143,26 @@ warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1] ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('scan.jpg', ref) cv2.imwrite('scan.jpg', ref)
# 展示结果 # 展示结果
print("STEP 3: 变换") print("STEP 3: 变换")
cv2.imshow("Original", resize(orig, height = 650)) # cv2.imshow("Original", resize(orig, height = 650))
cv2.imshow("Scanned", resize(ref, height = 650)) # cv2.imshow("Scanned", resize(ref, height = 650))
cv2.waitKey(0) # cv2.waitKey(0)
cv2.destroyAllWindows() # cv2.destroyAllWindows()
''' # OCR扫描
OCR扫描
'''
preprocess = "blur" preprocess = "blur"
if preprocess == "thresh": if preprocess == "thresh":
gray = cv2.threshold(ref, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] gray = cv2.threshold(ref, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
if preprocess == "blur": if preprocess == "blur":
gray = cv2.medianBlur(ref, 3) gray = cv2.medianBlur(ref, 3)
cv2.imshow("Detect", gray) # cv2.imshow("Detect", gray)
filename = "{}.png".format(os.getpid()) filename = "{}.png".format(os.getpid())
cv2.imwrite(filename, gray) cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open(filename)) text = pytesseract.image_to_string(Image.open(filename)) # 调用Tesseract OCR引擎对保存的图像进行文本识别
os.remove(filename) os.remove(filename)
encodings = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252', 'gbk', 'big5'] encodings = ['utf-8', 'latin1', 'iso-8859-1', 'cp1252', 'gbk', 'big5']

Loading…
Cancel
Save