Mattral commited on
Commit
cc3aad6
·
verified ·
1 Parent(s): 849cfbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -64
app.py CHANGED
@@ -1,79 +1,76 @@
1
- import streamlit as st
2
- import numpy as np
3
  import pandas as pd
 
 
4
  import easyocr
5
- from PIL import Image
 
6
  from streamlit_drawable_canvas import st_canvas
7
 
8
  def rectangle(image, result):
9
- """Draw rectangles on image based on predicted coordinates using PIL."""
10
- from PIL import ImageDraw
11
  draw = ImageDraw.Draw(image)
12
  for res in result:
13
- top_left = tuple(res[0][0])
14
- bottom_right = tuple(res[0][2])
15
  draw.rectangle((top_left, bottom_right), outline="blue", width=2)
16
- return image
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def main():
19
- # Set up Streamlit page
20
- st.set_page_config(
21
- page_title="OCR App",
22
- page_icon=":mag:",
23
- layout="centered",
24
- initial_sidebar_state="auto",
 
 
 
 
 
 
 
 
 
25
  )
26
 
27
- st.title("Optical Character Recognition (OCR) with EasyOCR")
28
-
29
- st.markdown("""
30
- Upload an image or use the canvas to draw, and the app will recognize and extract text from it.
31
- Supported languages for recognition include English and Japanese.
32
- """)
33
-
34
- # Upload image or draw
35
- col1, col2 = st.columns(2)
36
- with col1:
37
- file = st.file_uploader("Upload Image", type=['png', 'jpg', 'jpeg'])
38
- with col2:
39
- stroke_width = st.slider("Stroke Width: ", 1, 25, 3)
40
- canvas_result = st_canvas(
41
- fill_color="rgba(255, 165, 0, 0.3)",
42
- stroke_width=stroke_width,
43
- stroke_color="#ffffff",
44
- background_color="#000000",
45
- update_streamlit=True,
46
- width=400,
47
- height=400,
48
- drawing_mode="freedraw",
49
- key="canvas",
50
- )
51
 
52
- # Process uploaded image or drawing
53
- if file is not None:
54
- image = Image.open(file).convert('RGB')
55
- elif canvas_result.image_data is not None:
56
- image = Image.fromarray(np.array(canvas_result.image_data).astype('uint8'), 'RGBA').convert('RGB')
57
- else:
58
- st.warning("Please upload an image or use the canvas to draw.")
59
- st.stop()
60
 
61
- st.image(image, caption='Uploaded Image', use_column_width=True)
62
-
63
- # OCR
64
- reader = easyocr.Reader(['en', 'ja'], gpu=False)
65
- result = reader.readtext(np.array(image))
 
 
 
66
 
67
- # Display results
68
- if result:
69
- image = rectangle(image, result)
70
- st.image(image, caption='Processed Image with Detected Text', use_column_width=True)
71
-
72
- textdic_easyocr = {idx: {'text': res[1], 'confidence': res[2]} for idx, res in enumerate(result)}
73
- df = pd.DataFrame.from_dict(textdic_easyocr, orient='index')
74
- st.dataframe(df)
75
- else:
76
- st.info("No text detected.")
77
 
78
- if __name__ == "__main__":
79
- main()
 
 
 
1
  import pandas as pd
2
+ import numpy as np
3
+ import streamlit as st
4
  import easyocr
5
+ import PIL
6
+ from PIL import Image, ImageDraw
7
  from streamlit_drawable_canvas import st_canvas
8
 
9
  def rectangle(image, result):
10
+ """Draw rectangles on image based on predicted coordinates."""
 
11
  draw = ImageDraw.Draw(image)
12
  for res in result:
13
+ top_left = tuple(res[0][0]) # top left coordinates as tuple
14
+ bottom_right = tuple(res[0][2]) # bottom right coordinates as tuple
15
  draw.rectangle((top_left, bottom_right), outline="blue", width=2)
16
+ # Display image on streamlit
17
+ st.image(image)
18
+
19
+ # Main title
20
+ st.title("Get text from image with EasyOCR")
21
+
22
+ # Subtitle
23
+ st.markdown("## EasyOCR with Streamlit")
24
+
25
+ # Upload image file or draw
26
+ st.markdown("## Upload an Image or Draw")
27
+ col1, col2 = st.columns(2)
28
 
29
+ with col1:
30
+ file = st.file_uploader("Upload Here", type=['png', 'jpg', 'jpeg'])
31
+
32
+ with col2:
33
+ # Drawable canvas
34
+ canvas_result = st_canvas(
35
+ fill_color="rgba(255, 165, 0, 0.3)",
36
+ stroke_width=3,
37
+ stroke_color="#ffffff",
38
+ background_color="#000000",
39
+ background_image=None if file else st.session_state.get("background", None),
40
+ update_streamlit=True,
41
+ width=400,
42
+ height=400,
43
+ drawing_mode="freedraw",
44
+ key="canvas",
45
  )
46
 
47
+ # Process uploaded image or drawing
48
+ if file is not None:
49
+ image = Image.open(file) # Read image with PIL library
50
+ elif canvas_result.image_data is not None:
51
+ image = Image.fromarray(canvas_result.image_data.astype('uint8'), 'RGBA').convert('RGB')
52
+ else:
53
+ st.write("Please upload an image or use the canvas to draw.")
54
+ image = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ if image is not None:
57
+ st.image(image) # Display
 
 
 
 
 
 
58
 
59
+ # Only detect the English and Turkish part of the image as text
60
+ reader = easyocr.Reader(['en'], gpu=False)
61
+ result = reader.readtext(np.array(image)) # Turn image to numpy array
62
+
63
+ # Print all predicted text:
64
+ for idx, res in enumerate(result):
65
+ pred_text = res[1]
66
+ st.write(pred_text)
67
 
68
+ # Collect the results in the dictionary:
69
+ textdic_easyocr = {res[1]: {'pred_confidence': res[2]} for res in result}
70
+
71
+ # Create a data frame which shows the predicted text and prediction confidence
72
+ df = pd.DataFrame.from_dict(textdic_easyocr).T
73
+ st.table(df)
 
 
 
 
74
 
75
+ # Get boxes on the image
76
+ rectangle(image, result)