mohamed12ahmed commited on
Commit
6cca844
·
verified ·
1 Parent(s): fa26674

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -76
app.py CHANGED
@@ -1,80 +1,45 @@
1
- import cv2
2
- import numpy as np
3
  import gradio as gr
4
- import time
5
- import imutils
6
-
7
- def order_points(pts):
8
- rect = np.zeros((4, 2), dtype="float32")
9
- s = pts.sum(axis=1)
10
- rect[0] = pts[np.argmin(s)]
11
- rect[2] = pts[np.argmax(s)]
12
- diff = np.diff(pts, axis=1)
13
- rect[1] = pts[np.argmin(diff)]
14
- rect[3] = pts[np.argmax(diff)]
15
- return rect
16
-
17
- def four_point_transform(image, pts):
18
- rect = order_points(pts)
19
- (tl, tr, br, bl) = rect
20
- widthA = np.sqrt(((br[0]-bl[0])**2)+((br[1]-bl[1])**2))
21
- widthB = np.sqrt(((tr[0]-tl[0])**2)+((tr[1]-tl[1])**2))
22
- maxWidth = max(int(widthA), int(widthB))
23
- heightA = np.sqrt(((tr[0]-br[0])**2)+((tr[1]-br[1])**2))
24
- heightB = np.sqrt(((tl[0]-bl[0])**2)+((tl[1]-bl[1])**2))
25
- maxHeight = max(int(heightA), int(heightB))
26
- dst = np.array([[0,0],[maxWidth-1,0],[maxWidth-1,maxHeight-1],[0,maxHeight-1]],dtype="float32")
27
- M = cv2.getPerspectiveTransform(rect,dst)
28
- warped = cv2.warpPerspective(image,M,(maxWidth,maxHeight))
29
- return warped
30
-
31
- def document_scanner(image, threshold_block_size=21, threshold_C=10):
32
- start_time = time.time()
33
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
34
- blurred = cv2.GaussianBlur(gray,(5,5),0)
35
- edged = cv2.Canny(blurred,75,200)
36
-
37
- contours = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
38
- contours = imutils.grab_contours(contours)
39
- contours = sorted(contours,key=cv2.contourArea,reverse=True)
40
-
41
- document_contour = None
42
- for contour in contours:
43
- peri = cv2.arcLength(contour, True)
44
- approx = cv2.approxPolyDP(contour, 0.02*peri, True)
45
- if len(approx) == 4:
46
- document_contour = approx
47
- break
48
-
49
- if document_contour is None:
50
- print("Warning: Could not find 4 corner points. Returning thresholded image.")
51
- T = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,21,10)
52
- return cv2.cvtColor(T,cv2.COLOR_GRAY2BGR)
53
-
54
- pts = document_contour.reshape(4,2)
55
- warped = four_point_transform(image, pts)
56
- warped_gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
57
- if threshold_block_size % 2 == 0:
58
- threshold_block_size += 1
59
- T = cv2.adaptiveThreshold(warped_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,threshold_block_size,threshold_C)
60
-
61
- print(f"Processing time: {time.time()-start_time:.4f} seconds.")
62
- return cv2.cvtColor(T,cv2.COLOR_GRAY2BGR)
63
-
64
- input_image = gr.Image(type="numpy", label="📄 صورة المستند الأصلية (المائلة)")
65
- output_image = gr.Image(type="numpy", label="📘 المستند الممسوح ضوئيًا والمُصحَّح")
66
-
67
- iface = gr.Interface(
68
- fn=document_scanner,
69
- inputs=[input_image,
70
- gr.Slider(3,41,step=2,value=21,label="حجم الكتلة"),
71
- gr.Slider(0,50,step=1,value=10,label="قيمة C")],
72
- outputs=output_image,
73
- title="📄 ماسح ضوئي للمستندات بتقنية OpenCV",
74
- description="حوّل أي صورة مستند ملتقطة بالكاميرا إلى نسخة ممسوحة نظيفة ومستقيمة.",
75
- theme="soft",
76
- flagging_mode="never"
77
  )
78
 
79
  if __name__ == "__main__":
80
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
1
  import gradio as gr
2
+ import cv2
3
+ import os
4
+ from scan import DocScanner
5
+
6
+ OUTPUT_DIR = "output"
7
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
8
+
9
+ # دالة الفحص
10
+ def scan_document(image, interactive=False):
11
+ scanner = DocScanner(interactive)
12
+
13
+ # نحفظ الصورة مؤقتًا
14
+ temp_path = "temp_input.jpg"
15
+ cv2.imwrite(temp_path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
16
+
17
+ # نفذ عملية المسح
18
+ scanner.scan(temp_path)
19
+
20
+ # نحصل على اسم الملف الناتج
21
+ output_path = os.path.join(OUTPUT_DIR, os.path.basename(temp_path))
22
+
23
+ # نقرأ النتيجة لو الملف اتولد
24
+ if os.path.exists(output_path):
25
+ scanned = cv2.imread(output_path)
26
+ scanned = cv2.cvtColor(scanned, cv2.COLOR_BGR2RGB)
27
+ return scanned
28
+ else:
29
+ return None
30
+
31
+ # واجهة Gradio
32
+ app = gr.Interface(
33
+ fn=scan_document,
34
+ inputs=[
35
+ gr.Image(label="📸 ارفع الصورة", type="numpy"),
36
+ gr.Checkbox(label="تفعيل الوضع التفاعلي (تعديل الزوايا يدويًا)", value=False)
37
+ ],
38
+ outputs=gr.Image(label="📄 النتيجة بعد المسح"),
39
+ title="AI Document Scanner",
40
+ description="برنامج لمسح المستندات الورقية والمكتوبة بخط اليد (عربي/إنجليزي) باستخدام OpenCV + LSD + PyImageSearch",
41
+ examples=[["sample_images/desk.JPG", False]],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
43
 
44
  if __name__ == "__main__":
45
+ app.launch(server_name="0.0.0.0", server_port=7860)