Upload 26 files
#6
by
Loren
- opened
- .gitattributes +13 -0
- Home.py +33 -17
- about.py +66 -0
- doc.png +0 -0
- enhance.py +874 -0
- fonts/arabic.ttf +3 -0
- fonts/chinese_cht.ttf +3 -0
- fonts/cyrillic.ttf +0 -0
- fonts/french.ttf +3 -0
- fonts/german.ttf +3 -0
- fonts/hindi.ttf +3 -0
- fonts/japan.ttc +3 -0
- fonts/kannada.ttf +3 -0
- fonts/korean.ttf +3 -0
- fonts/latin.ttf +0 -0
- fonts/marathi.ttf +0 -0
- fonts/nepali.ttf +3 -0
- fonts/persian.ttf +0 -0
- fonts/simfang.ttf +3 -0
- fonts/spanish.ttf +3 -0
- fonts/tamil.ttf +3 -0
- fonts/telugu.ttf +3 -0
- fonts/urdu.ttf +0 -0
- fonts/uyghur.ttf +0 -0
- img_demo_enhance.png +0 -0
- ocr_comparator.py +1301 -0
- requirements.txt +21 -22
.gitattributes
CHANGED
|
@@ -32,3 +32,16 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
fonts/arabic.ttf filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
fonts/chinese_cht.ttf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
fonts/french.ttf filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
fonts/german.ttf filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
fonts/hindi.ttf filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
fonts/japan.ttc filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
fonts/kannada.ttf filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
fonts/korean.ttf filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
fonts/nepali.ttf filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
fonts/simfang.ttf filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
fonts/spanish.ttf filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
fonts/tamil.ttf filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
fonts/telugu.ttf filter=lfs diff=lfs merge=lfs -text
|
Home.py
CHANGED
|
@@ -1,17 +1,33 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
from multipage import MultiPage
|
| 3 |
-
from app_pages import home, about, ocr_comparator
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
#from multipage import MultiPage
|
| 3 |
+
#from app_pages import home, about, ocr_comparator, enhance
|
| 4 |
+
#from mmocr.utils.ocr import MMOCR
|
| 5 |
+
import os
|
| 6 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 7 |
+
|
| 8 |
+
st.set_page_config(
|
| 9 |
+
page_title='OCR Comparator', layout ="wide",
|
| 10 |
+
initial_sidebar_state="expanded",
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
# https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded&selected=Material+Symbols+Rounded:info:FILL@0;wght@400;GRAD@0;opsz@24&icon.query=info&icon.size=24&icon.color=%235f6368
|
| 14 |
+
|
| 15 |
+
st.markdown("""
|
| 16 |
+
<style>
|
| 17 |
+
.block-container {
|
| 18 |
+
padding-top: 1rem;
|
| 19 |
+
padding-bottom: 1rem;
|
| 20 |
+
padding-left: 1rem;
|
| 21 |
+
padding-right: 2rem;
|
| 22 |
+
}
|
| 23 |
+
</style>
|
| 24 |
+
""", unsafe_allow_html=True)
|
| 25 |
+
|
| 26 |
+
page1 = st.Page("home_page.py", title="Home", icon=":material/home:")
|
| 27 |
+
page2 = st.Page("about.py", title="About", icon=":material/info:")
|
| 28 |
+
page3 = st.Page("enhance.py", title="Image processing", icon=":material/edit_square:")
|
| 29 |
+
page4 = st.Page("ocr_comparator.py", title="OCR Comparator", icon=":material/smart_display:")
|
| 30 |
+
|
| 31 |
+
pg = st.navigation([page1, page2, page3, page4])
|
| 32 |
+
|
| 33 |
+
pg.run()
|
about.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 4 |
+
|
| 5 |
+
st.markdown("""
|
| 6 |
+
<style>
|
| 7 |
+
.block-container {
|
| 8 |
+
padding-top: 1rem;
|
| 9 |
+
padding-bottom: 1rem;
|
| 10 |
+
padding-left: 1rem;
|
| 11 |
+
padding-right: 2rem;
|
| 12 |
+
}
|
| 13 |
+
</style>
|
| 14 |
+
""", unsafe_allow_html=True)
|
| 15 |
+
|
| 16 |
+
st.markdown('''#### :orange[OCR solutions comparator]''')
|
| 17 |
+
st.write("")
|
| 18 |
+
lib = "This application's tab allows you to compare, from a given image, the results of different solutions: \n*EasyOcr, PaddleOCR, MMOCR, Tesseract*"
|
| 19 |
+
st.markdown(lib)
|
| 20 |
+
|
| 21 |
+
with st.expander("See details:"):
|
| 22 |
+
st.markdown(''' The 1st step is to choose the language for the text recognition (not all solutions \
|
| 23 |
+
support the same languages), and then choose the picture to consider. It is possible to upload a file, \
|
| 24 |
+
to take a picture, or to use a demo file. \
|
| 25 |
+
It is then possible to change the default values for the text area detection process, \
|
| 26 |
+
before launching the detection task for each solution.\n
|
| 27 |
+
The different results are then presented.
|
| 28 |
+
|
| 29 |
+
The 2nd step is to choose one of these \
|
| 30 |
+
detection results, in order to carry out the text recognition process there. It is also possible to change \
|
| 31 |
+
the default settings for each solution.''')
|
| 32 |
+
st.write("")
|
| 33 |
+
st.markdown("###### The recognition results appear in 2 formats:")
|
| 34 |
+
st.markdown(''' - a visual format resumes the initial image, replacing the detected areas with \
|
| 35 |
+
the recognized text. The background is + or - strongly colored in green according to the \
|
| 36 |
+
confidence level of the recognition.
|
| 37 |
+
A slider allows you to change the font size, another \
|
| 38 |
+
allows you to modify the confidence threshold above which the text color changes: if it is at \
|
| 39 |
+
70% for example, then all the texts with a confidence threshold higher or equal to 70 will appear \
|
| 40 |
+
in white, in black otherwise.''')
|
| 41 |
+
st.markdown(" - a detailed format presents the results in a table, for each text box detected. \
|
| 42 |
+
It is possible to download this results in a local csv file.")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
st.markdown('-----')
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
lib = "But, :orange[before evaluating OCR solutions], you may want to verify that the image is \
|
| 49 |
+
of sufficient quality for an OCR task. And if it isn't, you might want to be able to \
|
| 50 |
+
improve its quality.\n This is what the application's tab 'Image processing' allows you to do."
|
| 51 |
+
st.markdown(lib)
|
| 52 |
+
|
| 53 |
+
st.markdown('''#### :orange[Image quality verification and improvement]''')
|
| 54 |
+
with st.expander("See details:", expanded=True):
|
| 55 |
+
st.write('''Here, you can run a recognition test with basic PPOCR. This displays the text areas \
|
| 56 |
+
detected in the image, along with their values and probabilities.''')
|
| 57 |
+
st.markdown('The **Image Processing** tab offers several operations: resize, rotate, filtering, \
|
| 58 |
+
morphological transformations, and thresholding.')
|
| 59 |
+
st.write('Special care has been taken to document the various operations, including links to \
|
| 60 |
+
documentation and explanatory pop-ups for the various parameters:')
|
| 61 |
+
st.image("doc.png", width=500)
|
| 62 |
+
st.markdown('For each operation, you can choose whether or not to apply the transformation \
|
| 63 |
+
to the image being processed using the **"Apply"** toggle.')
|
| 64 |
+
st.markdown('When the result is satisfactory, you can view a detailed list of the various \
|
| 65 |
+
operations performed on the original image using the **"List of operations"** button.')
|
| 66 |
+
st.markdown('Finally, you can download the resulting image.')
|
doc.png
ADDED
|
enhance.py
ADDED
|
@@ -0,0 +1,874 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import cv2
|
| 3 |
+
import imutils
|
| 4 |
+
from paddleocr import PaddleOCR, draw_ocr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
import ast
|
| 10 |
+
import operator
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 15 |
+
|
| 16 |
+
st.markdown("""
|
| 17 |
+
<style>
|
| 18 |
+
.main > div:first-of-type {
|
| 19 |
+
padding: 1em 2em 2em 2em;
|
| 20 |
+
}
|
| 21 |
+
</style>
|
| 22 |
+
""", unsafe_allow_html=True)
|
| 23 |
+
|
| 24 |
+
###################################################################################################
|
| 25 |
+
## INITIALISATIONS
|
| 26 |
+
###################################################################################################
|
| 27 |
+
###
|
| 28 |
+
@st.cache_data(show_spinner=True)
|
| 29 |
+
def initializations():
|
| 30 |
+
print("Initializations ...")
|
| 31 |
+
out_dict_lang_ppocr = {'Abaza': 'abq', 'Adyghe': 'ady', 'Afrikaans': 'af', 'Albanian': 'sq', \
|
| 32 |
+
'Angika': 'ang', 'Arabic': 'ar', 'Avar': 'ava', 'Azerbaijani': 'az', 'Belarusian': 'be', \
|
| 33 |
+
'Bhojpuri': 'bho','Bihari': 'bh','Bosnian': 'bs','Bulgarian': 'bg','Chinese & English': 'ch', \
|
| 34 |
+
'Chinese Traditional': 'chinese_cht', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', \
|
| 35 |
+
'Dargwa': 'dar', 'Dutch': 'nl', 'English': 'en', 'Estonian': 'et', 'French': 'fr', \
|
| 36 |
+
'German': 'german','Goan Konkani': 'gom','Hindi': 'hi','Hungarian': 'hu','Icelandic': 'is', \
|
| 37 |
+
'Indonesian': 'id', 'Ingush': 'inh', 'Irish': 'ga', 'Italian': 'it', 'Japan': 'japan', \
|
| 38 |
+
'Kabardian': 'kbd', 'Korean': 'korean', 'Kurdish': 'ku', 'Lak': 'lbe', 'Latvian': 'lv', \
|
| 39 |
+
'Lezghian': 'lez', 'Lithuanian': 'lt', 'Magahi': 'mah', 'Maithili': 'mai', 'Malay': 'ms', \
|
| 40 |
+
'Maltese': 'mt', 'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Nagpur': 'sck', \
|
| 41 |
+
'Nepali': 'ne', 'Newari': 'new', 'Norwegian': 'no', 'Occitan': 'oc', 'Persian': 'fa', \
|
| 42 |
+
'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', 'Russia': 'ru', 'Saudi Arabia': 'sa', \
|
| 43 |
+
'Serbian(cyrillic)': 'rs_cyrillic', 'Serbian(latin)': 'rs_latin', 'Slovak': 'sk', \
|
| 44 |
+
'Slovenian': 'sl', 'Spanish': 'es', 'Swahili': 'sw', 'Swedish': 'sv', 'Tabassaran': 'tab', \
|
| 45 |
+
'Tagalog': 'tl', 'Tamil': 'ta', 'Telugu': 'te', 'Turkish': 'tr', 'Ukranian': 'uk', \
|
| 46 |
+
'Urdu': 'ur', 'Uyghur': 'ug', 'Uzbek': 'uz', 'Vietnamese': 'vi', 'Welsh': 'cy'}
|
| 47 |
+
|
| 48 |
+
out_dict_interpolation = {"INTER_LINEAR": cv2.INTER_LINEAR,
|
| 49 |
+
"INTER_NEAREST": cv2.INTER_NEAREST,
|
| 50 |
+
# "INTER_LINEAR_EXACT": cv2.INTER_LINEAR_EXACT,
|
| 51 |
+
"INTER_AREA": cv2.INTER_AREA,
|
| 52 |
+
"INTER_CUBIC": cv2.INTER_CUBIC,
|
| 53 |
+
"INTER_LANCZOS4": cv2.INTER_LANCZOS4,
|
| 54 |
+
# "INTER_NEAREST_EXACT": cv2.INTER_NEAREST_EXACT,
|
| 55 |
+
# "INTER_MAX": cv2.INTER_MAX,
|
| 56 |
+
# "WARP_FILL_OUTLIERS": cv2.WARP_FILL_OUTLIERS,
|
| 57 |
+
# "WARP_INVERSE_MAP": cv2.WARP_INVERSE_MAP,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
out_dict_thresholding_type = {"THRESH_BINARY": cv2.THRESH_BINARY,
|
| 61 |
+
"THRESH_BINARY_INV": cv2.THRESH_BINARY_INV,
|
| 62 |
+
"THRESH_TRUNC": cv2.THRESH_TRUNC,
|
| 63 |
+
"THRESH_TOZERO": cv2.THRESH_TOZERO,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
out_dict_adaptative_method = {"ADAPTIVE_THRESH_MEAN_C": cv2.ADAPTIVE_THRESH_MEAN_C,
|
| 67 |
+
"ADAPTIVE_THRESH_GAUSSIAN_C": cv2.ADAPTIVE_THRESH_GAUSSIAN_C}
|
| 68 |
+
|
| 69 |
+
return out_dict_lang_ppocr, out_dict_interpolation, out_dict_thresholding_type, out_dict_adaptative_method
|
| 70 |
+
|
| 71 |
+
###################################################################################################
|
| 72 |
+
## FONTIONS
|
| 73 |
+
###################################################################################################
|
| 74 |
+
###
|
| 75 |
+
@st.cache_data(show_spinner=False)
|
| 76 |
+
def load_image(in_image_file):
|
| 77 |
+
"""Load input file and open it
|
| 78 |
+
Args:
|
| 79 |
+
in_image_file (string or Streamlit UploadedFile): image to consider
|
| 80 |
+
Returns:
|
| 81 |
+
matrix : input file opened with Opencv
|
| 82 |
+
"""
|
| 83 |
+
#if isinstance(in_image_file, str):
|
| 84 |
+
# out_image_path = "img."+in_image_file.split('.')[-1]
|
| 85 |
+
#else:
|
| 86 |
+
# out_image_path = "img."+in_image_file.name.split('.')[-1]
|
| 87 |
+
if isinstance(in_image_file, str):
|
| 88 |
+
out_image_path = "tmp_"+in_image_file
|
| 89 |
+
else:
|
| 90 |
+
out_image_path = "tmp_"+in_image_file.name
|
| 91 |
+
img = Image.open(in_image_file)
|
| 92 |
+
img_saved = img.save(out_image_path)
|
| 93 |
+
# Read image
|
| 94 |
+
# out_image_orig = Image.open(out_image_path)
|
| 95 |
+
out_image_cv2 = cv2.cvtColor(cv2.imread(out_image_path), cv2.COLOR_BGR2RGB)
|
| 96 |
+
|
| 97 |
+
st.session_state.resize = False
|
| 98 |
+
st.session_state.scaling_factor = None
|
| 99 |
+
st.session_state.interpolation = None
|
| 100 |
+
st.session_state.rotate = None
|
| 101 |
+
st.session_state.angle = None
|
| 102 |
+
st.session_state.convolution = None
|
| 103 |
+
st.session_state.text_convol = None
|
| 104 |
+
st.session_state.convol_kernel = None
|
| 105 |
+
st.session_state.averaging = None
|
| 106 |
+
st.session_state.averaging_kernel_size = None
|
| 107 |
+
st.session_state.gaussian_bluring = None
|
| 108 |
+
st.session_state.gb_kernel_size = None
|
| 109 |
+
st.session_state.sigmaX = None
|
| 110 |
+
st.session_state.sigmaY = None
|
| 111 |
+
st.session_state.median_bluring = None
|
| 112 |
+
st.session_state.mb_kernel_size = None
|
| 113 |
+
st.session_state.bilateral_filtering = None
|
| 114 |
+
st.session_state.d = None
|
| 115 |
+
st.session_state.sigma_color = None
|
| 116 |
+
st.session_state.sigma_space = None
|
| 117 |
+
st.session_state.erosion = None
|
| 118 |
+
st.session_state.erosion_kernel_size = None
|
| 119 |
+
st.session_state.nb_iter_erosion = None
|
| 120 |
+
st.session_state.dilation = None
|
| 121 |
+
st.session_state.dilation_kernel_size = None
|
| 122 |
+
st.session_state.nb_iter_dilation = None
|
| 123 |
+
st.session_state.binarization = None
|
| 124 |
+
st.session_state.bin_thresh = None
|
| 125 |
+
st.session_state.bin_thresh = None
|
| 126 |
+
st.session_state.bin_thresholding_type = None
|
| 127 |
+
st.session_state.bin_otsu = None
|
| 128 |
+
st.session_state.thresh_typ = None
|
| 129 |
+
st.session_state.adaptative_thresh = None
|
| 130 |
+
st.session_state.at_thresholding_type = None
|
| 131 |
+
st.session_state.at_max_value = None
|
| 132 |
+
st.session_state.at_adaptative_method = None
|
| 133 |
+
st.session_state.at_block_size = None
|
| 134 |
+
st.session_state.at_const = None
|
| 135 |
+
st.session_state.processed_image = None
|
| 136 |
+
|
| 137 |
+
return out_image_cv2, out_image_path
|
| 138 |
+
###
|
| 139 |
+
def eval_expr(expr):
|
| 140 |
+
"""Eval numeric expression
|
| 141 |
+
Args:
|
| 142 |
+
expr (string): numeric expression
|
| 143 |
+
Returns:
|
| 144 |
+
float: eval result
|
| 145 |
+
"""
|
| 146 |
+
result = 1.
|
| 147 |
+
# Dictionnary of authorized operators
|
| 148 |
+
operators = {
|
| 149 |
+
ast.Add: operator.add,
|
| 150 |
+
ast.Sub: operator.sub,
|
| 151 |
+
ast.Mult: operator.mul,
|
| 152 |
+
ast.Div: operator.truediv,
|
| 153 |
+
ast.Pow: operator.pow,
|
| 154 |
+
ast.USub: operator.neg,
|
| 155 |
+
}
|
| 156 |
+
def _eval(node):
|
| 157 |
+
if isinstance(node, ast.Expression):
|
| 158 |
+
return _eval(node.body)
|
| 159 |
+
elif isinstance(node, ast.Constant): # nombre
|
| 160 |
+
return node.value
|
| 161 |
+
elif isinstance(node, ast.BinOp): # opérations binaires
|
| 162 |
+
return operators[type(node.op)](_eval(node.left), _eval(node.right))
|
| 163 |
+
elif isinstance(node, ast.UnaryOp): # opérations unaires (-n)
|
| 164 |
+
return operators[type(node.op)](_eval(node.operand))
|
| 165 |
+
else:
|
| 166 |
+
raise TypeError(node)
|
| 167 |
+
try:
|
| 168 |
+
parsed = ast.parse(expr, mode='eval')
|
| 169 |
+
result = _eval(parsed.body)
|
| 170 |
+
except:
|
| 171 |
+
pass
|
| 172 |
+
return result
|
| 173 |
+
###
|
| 174 |
+
def text_kernel_to_latex(text_eval):
|
| 175 |
+
"""Try to parse a kernel text description like: 1/6 * [[1,1],[1,1]]
|
| 176 |
+
Args:
|
| 177 |
+
text_eval (string): the string with the kernel expression
|
| 178 |
+
Returns:
|
| 179 |
+
string: left part of input string before *
|
| 180 |
+
list: right part of input string after *
|
| 181 |
+
string: latex expression corresponding to the text kernel input
|
| 182 |
+
"""
|
| 183 |
+
list_eval = text_eval.split('*')
|
| 184 |
+
text_kernel = list_eval[-1].strip()
|
| 185 |
+
list_kernel = ast.literal_eval(text_kernel)
|
| 186 |
+
latex = "\\begin{bmatrix}\n"
|
| 187 |
+
for row in list_kernel:
|
| 188 |
+
latex += " & ".join(map(str, row)) + " \\\\\n"
|
| 189 |
+
latex += "\\end{bmatrix}"
|
| 190 |
+
text_coeff = 1.
|
| 191 |
+
latex_text = latex
|
| 192 |
+
if len(list_eval) > 1:
|
| 193 |
+
text_coeff = list_eval[0].strip()
|
| 194 |
+
latex_text = text_coeff + ' ' + latex
|
| 195 |
+
return text_coeff, list_kernel, latex_text
|
| 196 |
+
###
|
| 197 |
+
def get_img_fig(img):
|
| 198 |
+
"""Plot image with matplotlib, in order to have image size
|
| 199 |
+
Args:
|
| 200 |
+
img (Image): Image to show
|
| 201 |
+
Returns:
|
| 202 |
+
Matplotlib figure
|
| 203 |
+
"""
|
| 204 |
+
fig = plt.figure()
|
| 205 |
+
if len(img.shape) == 3:
|
| 206 |
+
plt.imshow(img, cmap=None)
|
| 207 |
+
else:
|
| 208 |
+
plt.imshow(img, cmap='gray')
|
| 209 |
+
return fig
|
| 210 |
+
|
| 211 |
+
@st.fragment
|
| 212 |
+
def show_latex(latex_code):
|
| 213 |
+
st.latex(latex_code)
|
| 214 |
+
###################################################################################################
|
| 215 |
+
## STREAMLIT APP
|
| 216 |
+
###################################################################################################
|
| 217 |
+
st.title(''':orange[Image check and enhance for OCR task]''')
|
| 218 |
+
st.write("")
|
| 219 |
+
st.write("")
|
| 220 |
+
st.write("")
|
| 221 |
+
st.set_option("client.showErrorDetails", False)
|
| 222 |
+
|
| 223 |
+
dict_lang_ppocr, dict_interpolation, dict_thresholding_type, dict_adaptative_method = initializations()
|
| 224 |
+
|
| 225 |
+
cols = st.columns([0.25, 0.25, 0.5])
|
| 226 |
+
cols[0].markdown("#### :orange[Choose picture:]")
|
| 227 |
+
img_typ = cols[0].radio("#### :orange[Choose picture type:]", ['Upload file', 'Take a picture', 'Use a demo file'], \
|
| 228 |
+
index=0)
|
| 229 |
+
if img_typ == 'Upload file':
|
| 230 |
+
image_file = cols[1].file_uploader("Upload a file:", type=["png","jpg","jpeg"])
|
| 231 |
+
|
| 232 |
+
if img_typ == 'Take a picture':
|
| 233 |
+
image_file = cols[1].camera_input("Take a picture:")
|
| 234 |
+
if img_typ == 'Use a demo file':
|
| 235 |
+
image_file = 'img_demo_enhance.png'
|
| 236 |
+
|
| 237 |
+
##----------- Process input image -----------------------------------------------------------------
|
| 238 |
+
if image_file is not None:
|
| 239 |
+
img_cv2, image_path = load_image(image_file)
|
| 240 |
+
|
| 241 |
+
cols[2].markdown('#### :orange[Original image]')
|
| 242 |
+
cnt_img_ori = cols[2].container(height=300, border=False)
|
| 243 |
+
#cnt_img_ori.image(img_cv2) #, use_container_width=True)
|
| 244 |
+
cnt_img_ori.pyplot(get_img_fig(img_cv2))
|
| 245 |
+
col1, col2 = st.columns([0.5, 0.5]) #gap="medium")
|
| 246 |
+
|
| 247 |
+
col1.markdown('#### :orange[Processed image]')
|
| 248 |
+
list_op = []
|
| 249 |
+
|
| 250 |
+
if col1.checkbox("GrayScale"):
|
| 251 |
+
try:
|
| 252 |
+
img_first = cv2.cvtColor(img_cv2.copy(), cv2.COLOR_BGR2GRAY)
|
| 253 |
+
list_op.append("Grayscale")
|
| 254 |
+
except Exception as e:
|
| 255 |
+
st.exception(e)
|
| 256 |
+
else:
|
| 257 |
+
img_first = img_cv2.copy()
|
| 258 |
+
|
| 259 |
+
if col1.checkbox("Bit-wise inversion"):
|
| 260 |
+
try:
|
| 261 |
+
img_first = cv2.bitwise_not(img_first)
|
| 262 |
+
list_op.append("Bit-wise inversion")
|
| 263 |
+
except Exception as e:
|
| 264 |
+
st.exception(e)
|
| 265 |
+
|
| 266 |
+
# Processed image construction
|
| 267 |
+
cnt_img_wrk = col1.container(height=500, border=False)
|
| 268 |
+
img_processed = cnt_img_wrk.empty()
|
| 269 |
+
img_wrk = img_first.copy()
|
| 270 |
+
|
| 271 |
+
if st.session_state.resize:
|
| 272 |
+
try:
|
| 273 |
+
img_wrk = cv2.resize(img_wrk, None, fx=st.session_state.scaling_factor,
|
| 274 |
+
fy=st.session_state.scaling_factor,
|
| 275 |
+
interpolation=dict_interpolation[st.session_state.interpolation])
|
| 276 |
+
list_op.append("Resize - fx="+str(st.session_state.scaling_factor)+", fy="+
|
| 277 |
+
str(st.session_state.scaling_factor)+", interpolation="+
|
| 278 |
+
st.session_state.interpolation)
|
| 279 |
+
except Exception as e:
|
| 280 |
+
st.exception(e)
|
| 281 |
+
|
| 282 |
+
if st.session_state.rotate:
|
| 283 |
+
try:
|
| 284 |
+
img_wrk = imutils.rotate(img_wrk, angle=st.session_state.angle)
|
| 285 |
+
list_op.append("Rotate - angle="+str(st.session_state.angle))
|
| 286 |
+
except Exception as e:
|
| 287 |
+
st.exception(e)
|
| 288 |
+
|
| 289 |
+
if st.session_state.convolution:
|
| 290 |
+
try:
|
| 291 |
+
img_wrk = cv2.filter2D(src=img_wrk, ddepth=-1, kernel=st.session_state.convol_kernel)
|
| 292 |
+
list_op.append("Filtering - Custom 2D Convolution - kernel="+ st.session_state.text_convol)
|
| 293 |
+
except Exception as e:
|
| 294 |
+
st.exception(e)
|
| 295 |
+
|
| 296 |
+
if st.session_state.averaging:
|
| 297 |
+
try:
|
| 298 |
+
img_wrk = cv2.blur(src=img_wrk, ksize=st.session_state.averaging_kernel_size)
|
| 299 |
+
list_op.append("Filtering - Averaging - kernel_size="+
|
| 300 |
+
str(st.session_state.averaging_kernel_size))
|
| 301 |
+
except Exception as e:
|
| 302 |
+
st.exception(e)
|
| 303 |
+
|
| 304 |
+
if st.session_state.gaussian_bluring:
|
| 305 |
+
try:
|
| 306 |
+
img_wrk = cv2.GaussianBlur(src=img_wrk, ksize=st.session_state.gb_kernel_size, \
|
| 307 |
+
sigmaX=st.session_state.sigmaX, sigmaY=st.session_state.sigmaY)
|
| 308 |
+
list_op.append("Filtering - Gaussian Blurring - ksize="+ \
|
| 309 |
+
str(st.session_state.gb_kernel_size)+", sigmaX="+
|
| 310 |
+
str(st.session_state.sigmaX)+", sigmaY="+str(st.session_state.sigmaY))
|
| 311 |
+
except Exception as e:
|
| 312 |
+
st.exception(e)
|
| 313 |
+
|
| 314 |
+
if st.session_state.median_bluring:
|
| 315 |
+
try:
|
| 316 |
+
img_wrk = cv2.medianBlur(img_wrk, st.session_state.mb_kernel_size)
|
| 317 |
+
list_op.append("Filtering - Median Blurring - kernel_size="+ \
|
| 318 |
+
str(st.session_state.mb_kernel_size))
|
| 319 |
+
except Exception as e:
|
| 320 |
+
st.exception(e)
|
| 321 |
+
|
| 322 |
+
if st.session_state.bilateral_filtering:
|
| 323 |
+
try:
|
| 324 |
+
img_wrk = cv2.bilateralFilter(img_wrk, st.session_state.d, st.session_state.sigma_color,
|
| 325 |
+
st.session_state.sigma_space)
|
| 326 |
+
list_op.append("Filtering - Bilateral Filtering - d="+ str(st.session_state.d)+
|
| 327 |
+
", sigma_color="+str(st.session_state.sigma_color)+ \
|
| 328 |
+
", sigma_space="+str(st.session_state.sigma_space))
|
| 329 |
+
except Exception as e:
|
| 330 |
+
st.exception(e)
|
| 331 |
+
|
| 332 |
+
if st.session_state.erosion:
|
| 333 |
+
try:
|
| 334 |
+
kernel = np.ones((st.session_state.erosion_kernel_size,
|
| 335 |
+
st.session_state.erosion_kernel_size),
|
| 336 |
+
np.uint8)
|
| 337 |
+
img_wrk = cv2.erode(img_wrk, kernel, iterations=st.session_state.nb_iter_erosion)
|
| 338 |
+
list_op.append("Erosion - kernel_size="+str(st.session_state.erosion_kernel_size)+ \
|
| 339 |
+
", iterations="+str(st.session_state.nb_iter_erosion))
|
| 340 |
+
except Exception as e:
|
| 341 |
+
st.exception(e)
|
| 342 |
+
|
| 343 |
+
if st.session_state.dilation:
|
| 344 |
+
try:
|
| 345 |
+
kernel = np.ones((st.session_state.dilation_kernel_size,
|
| 346 |
+
st.session_state.dilation_kernel_size),
|
| 347 |
+
np.uint8)
|
| 348 |
+
img_wrk = cv2.dilate(img_wrk, kernel, iterations=st.session_state.nb_iter_dilation)
|
| 349 |
+
list_op.append("Dilation - kernel_size="+str(st.session_state.dilation_kernel_size )+ \
|
| 350 |
+
", iterations="+str(st.session_state.nb_iter_dilation))
|
| 351 |
+
except Exception as e:
|
| 352 |
+
st.exception(e)
|
| 353 |
+
|
| 354 |
+
if st.session_state.binarization:
|
| 355 |
+
try:
|
| 356 |
+
ret, img_wrk = cv2.threshold(img_wrk, st.session_state.bin_thresh,
|
| 357 |
+
st.session_state.bin_value,
|
| 358 |
+
st.session_state.thresh_typ)
|
| 359 |
+
list_op.append("Thresholding - thresh="+str(st.session_state.bin_thresh)+ \
|
| 360 |
+
", maxval="+str(st.session_state.bin_value)+", type="+ \
|
| 361 |
+
st.session_state.bin_thresholding_type+", otsu="+ \
|
| 362 |
+
str(st.session_state.bin_otsu))
|
| 363 |
+
except Exception as e:
|
| 364 |
+
st.exception(e)
|
| 365 |
+
|
| 366 |
+
if st.session_state.adaptative_thresh:
|
| 367 |
+
try:
|
| 368 |
+
img_wrk = cv2.adaptiveThreshold(img_wrk, st.session_state.at_max_value,
|
| 369 |
+
dict_adaptative_method[st.session_state.at_adaptative_method],
|
| 370 |
+
dict_thresholding_type[st.session_state.at_thresholding_type],
|
| 371 |
+
st.session_state.at_block_size, st.session_state.at_const)
|
| 372 |
+
list_op.append("Adaptative thresholding - maxValue="+
|
| 373 |
+
str(st.session_state.at_max_value)+", adaptiveMethod="+
|
| 374 |
+
st.session_state.at_adaptative_method+", thresholdType"+
|
| 375 |
+
", thresholding_type="+st.session_state.at_thresholding_type+
|
| 376 |
+
", blockSize="+str(st.session_state.at_block_size)+", C="+
|
| 377 |
+
str(st.session_state.at_const))
|
| 378 |
+
except Exception as e:
|
| 379 |
+
st.exception(e)
|
| 380 |
+
|
| 381 |
+
# Show image
|
| 382 |
+
img_processed.pyplot(get_img_fig(img_wrk))
|
| 383 |
+
st.session_state.processed_image = img_wrk
|
| 384 |
+
|
| 385 |
+
# Process
|
| 386 |
+
col2.markdown('#### :orange[Check & enhance]')
|
| 387 |
+
|
| 388 |
+
with col2.expander(":blue[Image processing]", expanded=False):
|
| 389 |
+
tab1, tab2, tab3, tab4, tab5 = \
|
| 390 |
+
st.tabs(["Resize", "Rotate", "Filtering",
|
| 391 |
+
"Morphologie", "Thresholding"])
|
| 392 |
+
with tab1: # Resize
|
| 393 |
+
with tab1.form("Resize parameters"):
|
| 394 |
+
st.session_state.scaling_factor = st.slider("Scaling factor :", 0.1, 20., 1., 0.1)
|
| 395 |
+
cols_tab1 = st.columns([0.1, 0.9], gap="medium", vertical_alignment="center")
|
| 396 |
+
cols_tab1[0].markdown("💬", help="""An interpolation function’s goal is
|
| 397 |
+
to examine neighborhoods of pixels and use these neighborhoods to optically increase or decrease
|
| 398 |
+
the size of the image without introducing distortions (or at least as few distortions
|
| 399 |
+
as possible).\n
|
| 400 |
+
```cv2.INTER_LINEAR``` This option uses the bilinear interpolation algorithm. Unlike INTER_NEAREST,
|
| 401 |
+
this does the interpolation in two dimensions and predicts the function used to calculate the color
|
| 402 |
+
of a pixel. This algorithm is effective in handling visual distortions while zooming or
|
| 403 |
+
enlarging an image.\n
|
| 404 |
+
```cv2.INTER_NEAREST``` This option uses the nearest neighbor interpolation algorithm. It retains
|
| 405 |
+
the sharpness of the edges though the overall image may be blurred.\n
|
| 406 |
+
```cv2.INTER_LINEAR_EXACT```is a modification of ```INTER_LINEAR``` and both uses bilinear
|
| 407 |
+
interpolation algorithm. The only difference is that the calculations in ```INTER_LINEAR_EXACT```
|
| 408 |
+
are accurate to a bit.\n
|
| 409 |
+
```cv2.INTER_AREA``` option uses resampling using pixel area relation technique. While enlarging
|
| 410 |
+
images, INTER_AREA work same as INTER_NEAREST. In other cases, ```INTER_AREA works``` better in
|
| 411 |
+
image decimation and avoiding false inference patterns in images (moire pattern).\n
|
| 412 |
+
```cv2.INTER_CUBIC``` option uses bicubic interpolation technique. This is an extension of cubic
|
| 413 |
+
interpolation technique and is used for 2 dimension regular grid patterns.\n
|
| 414 |
+
```cv2.INTER_LANCZOS4``` option uses Lanczos interpolation over 8 x 8 pixel neighborhood technique.
|
| 415 |
+
It uses Fourier series and Chebyshev polynomials and is suited for images with large number of
|
| 416 |
+
small size details.\n
|
| 417 |
+
```cv2.INTER_NEAREST_EXACT ``` is a modification of INTER_NEAREST with bit level accuracy.\n
|
| 418 |
+
```cv2.INTER_MAX ``` option uses mask for interpolation codes.\n
|
| 419 |
+
```cv2.WARP_FILL_OUTLIERS ``` interpolation technique skips the outliers during interpolation calculations.\n
|
| 420 |
+
```cv2.WARP_INVERSE_MAP ``` option uses inverse transformation technique for interpolation.\n""")
|
| 421 |
+
cols_tab1[0].link_button("📚", "https://opencv.org/blog/resizing-and-rescaling-images-with-opencv/#h-resizing-with-different-interpolation-methods")
|
| 422 |
+
st.session_state.interpolation = cols_tab1[1].selectbox("Interpolation method:",
|
| 423 |
+
list(dict_interpolation.keys()))
|
| 424 |
+
c1, c2 = st.columns(2)
|
| 425 |
+
apply_tab1 = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=1)
|
| 426 |
+
with c2:
|
| 427 |
+
submit_tab1 = st.form_submit_button(":green[Confirm]")
|
| 428 |
+
|
| 429 |
+
if submit_tab1:
|
| 430 |
+
st.session_state.resize = apply_tab1
|
| 431 |
+
st.rerun()
|
| 432 |
+
|
| 433 |
+
with tab2: # Rotate
|
| 434 |
+
with tab2.form("Rotate parameters"):
|
| 435 |
+
st.session_state.angle = st.slider("Angle :", 0, 360, 0, step=10)
|
| 436 |
+
c1, c2 = st.columns(2)
|
| 437 |
+
apply_tab2 = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=2)
|
| 438 |
+
with c2:
|
| 439 |
+
submit_tab2 = st.form_submit_button(":green[Confirm]")
|
| 440 |
+
|
| 441 |
+
if submit_tab2:
|
| 442 |
+
st.session_state.rotate = apply_tab2
|
| 443 |
+
st.rerun()
|
| 444 |
+
|
| 445 |
+
with tab3: # Filtering
|
| 446 |
+
st.write("📚 :blue[*More about image filtering*] 👉 \
|
| 447 |
+
[here](https://learnopencv.com/image-filtering-using-convolution-in-opencv/)")
|
| 448 |
+
selection = st.segmented_control("Filtering type",
|
| 449 |
+
["Custom 2D Convolution", "Blurring"],
|
| 450 |
+
selection_mode="single")
|
| 451 |
+
match selection:
|
| 452 |
+
case "Custom 2D Convolution":
|
| 453 |
+
with st.form("tab3_1"):
|
| 454 |
+
st.write("📚 :blue[*More about convolution matrix*] 👉 \
|
| 455 |
+
[here](https://en.wikipedia.org/wiki/Kernel_(image_processing))")
|
| 456 |
+
text_convol = st.text_input("Write your custom kernel here (example : 1/9 * [[1,1,1], [1,1,1], [1,1,1]]):",
|
| 457 |
+
value=None)
|
| 458 |
+
kernel = None
|
| 459 |
+
if text_convol is not None:
|
| 460 |
+
try:
|
| 461 |
+
text_coeff, list_kernel, latex_code = text_kernel_to_latex(text_convol)
|
| 462 |
+
coeff = eval_expr(text_coeff)
|
| 463 |
+
kernel = coeff * np.array(list_kernel)
|
| 464 |
+
show_latex(latex_code)
|
| 465 |
+
except Exception as e:
|
| 466 |
+
st.exception(e)
|
| 467 |
+
text_convol = None
|
| 468 |
+
else:
|
| 469 |
+
text_coeff, list_kernel, latex_code = \
|
| 470 |
+
text_kernel_to_latex("1/9 * [[1,1,1], [1,1,1], [1,1,1]]")
|
| 471 |
+
show_latex(latex_code)
|
| 472 |
+
|
| 473 |
+
c1, c2 = st.columns(2)
|
| 474 |
+
apply_tab31 = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=3)
|
| 475 |
+
with c2:
|
| 476 |
+
submit_tab31 = st.form_submit_button(":green[Confirm]")
|
| 477 |
+
|
| 478 |
+
if submit_tab31:
|
| 479 |
+
st.session_state.convolution = apply_tab31
|
| 480 |
+
st.session_state.text_convol = text_convol
|
| 481 |
+
st.session_state.convol_kernel = kernel
|
| 482 |
+
st.rerun()
|
| 483 |
+
|
| 484 |
+
case "Blurring":
|
| 485 |
+
st.write("📚 :blue[*More about blurring techniques*] 👉 \
|
| 486 |
+
[here](https://docs.opencv.org/4.x/d4/d13/tutorial_py_filtering.html)")
|
| 487 |
+
b1, b2, b3, b4 = st.tabs(["Averaging", "Gaussian Blurring", "Median Blurring",
|
| 488 |
+
"Bilateral Filtering"])
|
| 489 |
+
# typ_blurring = st.segmented_control("Bluring type",
|
| 490 |
+
# ["Averaging", "Gaussian Blurring", "Median Blurring",
|
| 491 |
+
# "Bilateral Filtering"],
|
| 492 |
+
# selection_mode="multi")
|
| 493 |
+
|
| 494 |
+
with b1:
|
| 495 |
+
with st.form("tab_32a"):
|
| 496 |
+
st.markdown("💬 :green[Averaging?]",
|
| 497 |
+
help="This is done by convolving an image with a normalized box filter.\
|
| 498 |
+
It simply takes the average of all the pixels under the kernel \
|
| 499 |
+
area and replaces the central element."
|
| 500 |
+
)
|
| 501 |
+
kernel_width = st.slider("Kernel size width:", 2, 20, None, 1)
|
| 502 |
+
kernel_height = st.slider("Kernel size height:", 2, 20, None, 1)
|
| 503 |
+
|
| 504 |
+
c1, c2 = st.columns(2)
|
| 505 |
+
apply_tab32a = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=4)
|
| 506 |
+
with c2:
|
| 507 |
+
submit_tab32a = st.form_submit_button(":green[Confirm]")
|
| 508 |
+
|
| 509 |
+
if submit_tab32a:
|
| 510 |
+
st.session_state.averaging = apply_tab32a
|
| 511 |
+
st.session_state.averaging_kernel_size = (kernel_width, kernel_height)
|
| 512 |
+
st.rerun()
|
| 513 |
+
|
| 514 |
+
with b2:
|
| 515 |
+
with st.form("tab_32b"):
|
| 516 |
+
st.markdown("💬 :green[Gaussian Blurringing?]",
|
| 517 |
+
help="In this method, instead of a box filter, a Gaussian kernel is used. \
|
| 518 |
+
We should specify the width and height of the kernel which should be positive and odd. \
|
| 519 |
+
We also should specify the standard deviation in the X and Y directions, `sigmaX` and `sigmaY` respectively. \
|
| 520 |
+
If only `sigmaX` is specified, `sigmaY` is taken as the same as sigmaX. If both are given as zeros, they are \
|
| 521 |
+
calculated from the kernel size.\n \
|
| 522 |
+
Gaussian blurring is highly effective in removing Gaussian noise from an image.")
|
| 523 |
+
kernel_width = st.slider("Kernel size width:", 2, 20, None, 1,)
|
| 524 |
+
kernel_height = st.slider("Kernel size height:", 2, 20, None, 1)
|
| 525 |
+
st.markdown("Standard deviations of the Gaussian kernel:",
|
| 526 |
+
help="""The parameters `sigmaX` and `sigmaY` represent the standard deviations
|
| 527 |
+
of the Gaussian kernel in the horizontal (X) and vertical (Y) directions,
|
| 528 |
+
respectively. These values control the extent of blurring applied to the image.\n
|
| 529 |
+
**Typical Values for sigmaX and sigmaY:**
|
| 530 |
+
- Low values (e.g., 1–3): Apply a mild blur, useful for slight noise reduction while preserving image details.
|
| 531 |
+
- Moderate values (e.g., 5–10): Produce a more noticeable blur, helpful for reducing more significant noise or smoothing out textures.
|
| 532 |
+
- High values (e.g., >10): Result in a strong blur, which can be used for artistic effects or to obscure details.
|
| 533 |
+
It's common practice to set sigmaX and sigmaY to 0. In this case, OpenCV calculates the standard deviations based on the kernel size (ksize).
|
| 534 |
+
If only sigmaX is specified and sigmaY is set to 0, OpenCV uses the same value for both directions. \n
|
| 535 |
+
**Recommendations:**
|
| 536 |
+
- Specify sigmaX and sigmaY explicitly: For precise control over the blurring effect, define both parameters based on the desired outcome.
|
| 537 |
+
- Use sigmaX = 0 and sigmaY = 0: To allow OpenCV to compute the standard deviations automatically from the kernel size.
|
| 538 |
+
- Choose an appropriate kernel size: The ksize parameter should be a tuple of positive odd integers (e.g., (3, 3), (5, 5)).
|
| 539 |
+
""")
|
| 540 |
+
sigmaX = st.slider("sigmaX:", 0, 20, 0, 1)
|
| 541 |
+
sigmaY = st.slider("sigmaY:", 0, 20, 0, 1)
|
| 542 |
+
|
| 543 |
+
c1, c2 = st.columns(2)
|
| 544 |
+
apply_tab32b = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=5)
|
| 545 |
+
with c2:
|
| 546 |
+
submit_tab32b = st.form_submit_button(":green[Confirm]")
|
| 547 |
+
|
| 548 |
+
if submit_tab32b:
|
| 549 |
+
st.session_state.gaussian_bluring = apply_tab32b
|
| 550 |
+
st.session_state.gb_kernel_size = (kernel_width, kernel_height)
|
| 551 |
+
st.session_state.sigmaX = sigmaX
|
| 552 |
+
st.session_state.sigmaY = sigmaY
|
| 553 |
+
st.rerun()
|
| 554 |
+
|
| 555 |
+
with b3:
|
| 556 |
+
with st.form("tab_32c"):
|
| 557 |
+
st.markdown("💬 :green[Median Blurring?]",
|
| 558 |
+
help="It takes the median of all the pixels under the \
|
| 559 |
+
kernel area and the central element is replaced with this median value. Interestingly, in the above \
|
| 560 |
+
filters, the central element is a newly calculated value which may be a pixel value in the image or a new value. \
|
| 561 |
+
But in median blurring, the central element is always replaced by some pixel value in the image. \
|
| 562 |
+
It reduces the noise effectively. Its kernel size should be a positive odd integer.\n \
|
| 563 |
+
Median blurring is highly effective against salt-and-pepper noise in an image.")
|
| 564 |
+
kernel_size = st.slider("Kernel size:", 3, 15, None, 2, key=101)
|
| 565 |
+
|
| 566 |
+
c1, c2 = st.columns(2)
|
| 567 |
+
apply_tab32c = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=6)
|
| 568 |
+
with c2:
|
| 569 |
+
submit_tab32c = st.form_submit_button(":green[Confirm]")
|
| 570 |
+
|
| 571 |
+
if submit_tab32c:
|
| 572 |
+
st.session_state.median_bluring = apply_tab32c
|
| 573 |
+
st.session_state.mb_kernel_size = kernel_size
|
| 574 |
+
st.rerun()
|
| 575 |
+
|
| 576 |
+
with b4:
|
| 577 |
+
with st.form("tab_32d"):
|
| 578 |
+
st.markdown("💬 :green[Bilateral Filtering?]",
|
| 579 |
+
help="It is highly effective in noise removal while \
|
| 580 |
+
keeping edges sharp. But the operation is slower compared to other filters. We already saw that a \
|
| 581 |
+
Gaussian filter takes the neighbourhood around the pixel and finds its Gaussian weighted average. \
|
| 582 |
+
This Gaussian filter is a function of space alone, that is, nearby pixels are considered while \
|
| 583 |
+
filtering. It doesn't consider whether pixels have almost the same intensity. It doesn't consider \
|
| 584 |
+
whether a pixel is an edge pixel or not. So it blurs the edges also, which we don't want to do.\n \
|
| 585 |
+
Bilateral filtering also takes a Gaussian filter in space, but one more Gaussian filter which is \
|
| 586 |
+
a function of pixel difference. \
|
| 587 |
+
The Gaussian function of space makes sure that only nearby pixels are considered for blurring, \
|
| 588 |
+
while the Gaussian function of intensity difference makes sure that only those pixels with similar \
|
| 589 |
+
intensities to the central pixel are considered for blurring. \
|
| 590 |
+
So it preserves the edges since pixels at edges will have large intensity variation.")
|
| 591 |
+
st.markdown("Diameter of each pixel neighborhood that is used during filtering:",
|
| 592 |
+
help=""" **Effect:**\n
|
| 593 |
+
A larger `d` value means that more neighboring pixels are considered in the filtering process, leading to a more pronounced
|
| 594 |
+
blurring effect. Conversely, a smaller `d` focuses the filter on a tighter area, preserving more details.
|
| 595 |
+
**Automatic Calculation:**\n
|
| 596 |
+
If `d` is set to a non-positive value (e.g., 0 or negative), OpenCV automatically calculates it based on the sigmaSpace parameter.
|
| 597 |
+
Specifically, the radius is computed as `radius = cvRound(sigmaSpace * 1.5)`, and then `d = radius * 2 + 1` to ensure it's an odd
|
| 598 |
+
number. This ensures that the kernel has a central pixel.
|
| 599 |
+
**Typical Values for `d`:**\n
|
| 600 |
+
The choice of d depends on the desired balance between noise reduction and edge preservation:
|
| 601 |
+
- Small d (e.g., 5 to 9): Suitable for subtle smoothing while maintaining edge sharpness.
|
| 602 |
+
- Medium d (e.g., 9 to 15): Offers a balance between noise reduction and detail preservation.
|
| 603 |
+
- Large d (e.g., 15 and above): Provides stronger blurring, which may be useful for artistic effects but can lead to loss of
|
| 604 |
+
fine details.
|
| 605 |
+
**Recommendations:**\n
|
| 606 |
+
- Large filters (d > 5) are very slow, so it is recommended to use `d=5` for real-time applications, and perhaps
|
| 607 |
+
`d=9` for offline applications that need heavy noise filtering.
|
| 608 |
+
- Start with Moderate Values: Begin with `d=9`, `sigmaColor=75`, and `sigmaSpace=75` as a baseline. Adjust these values based on
|
| 609 |
+
the specific requirements of your application.
|
| 610 |
+
- Consider Image Size: For larger images, you might need to increase `d` to achieve a noticeable effect. Conversely,
|
| 611 |
+
for smaller images, a smaller `d` might suffice.
|
| 612 |
+
- Balance with `sigmaColor` and `sigmaSpace`: Ensure that `d` is appropriately balanced with `sigmaColor` and
|
| 613 |
+
`sigmaSpace`. An excessively large `sigmaSpace` with a small `d` might not utilize the full potential of the spatial filtering.
|
| 614 |
+
""")
|
| 615 |
+
d_value = st.slider("d:", 3, 15, None, 2)
|
| 616 |
+
st.markdown("`sigmaColor` and `sigmaSpace`:", help="""
|
| 617 |
+
`sigmaColor`: This parameter defines the filter sigma in the color space. A larger value means that pixels with more significant
|
| 618 |
+
color differences will be mixed together, resulting in areas of semi-equal color.
|
| 619 |
+
`sigmaSpace`: This parameter defines the filter sigma in the coordinate space. A larger value means that pixels farther apart
|
| 620 |
+
will influence each other as long as their colors are close enough.\n
|
| 621 |
+
These parameters work together to ensure that the filter smooths the image while preserving edges.
|
| 622 |
+
**Typical Values for `sigmaColor` and `sigmaSpace`:**\n
|
| 623 |
+
The choice of `sigmaColor` and `sigmaSpace` depends on the specific application and the desired effect.
|
| 624 |
+
However, some commonly used values are:
|
| 625 |
+
- `sigmaColor`: Values around 75 are often used for general smoothing while preserving edges.
|
| 626 |
+
- `sigmaSpace`: Similarly, values around 75 are typical for maintaining edge sharpness while reducing noise.
|
| 627 |
+
For example, applying the bilateral filter with `d=9`, `sigmaColor=75`, and `sigmaSpace=75` is a common practice.
|
| 628 |
+
**Recommendations:**`\n
|
| 629 |
+
- Start with Equal Values: Setting `sigmaColor` and `sigmaSpace` to the same value (e.g., 75) is a good starting point.
|
| 630 |
+
- Adjust Based on Results: If the image appears too blurred, reduce the values. If noise is still present, increase them.
|
| 631 |
+
- Consider Image Characteristics: For images with high noise, higher values may be necessary. For images where edge preservation
|
| 632 |
+
is critical, lower values are preferable.""")
|
| 633 |
+
sigma_color = st.slider("sigmaColor", 1, 255, None, 1)
|
| 634 |
+
sigma_space = st.slider("sigmaSpace", 1, 255, None, 1)
|
| 635 |
+
|
| 636 |
+
c1, c2 = st.columns(2)
|
| 637 |
+
apply_tab32d = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=7)
|
| 638 |
+
with c2:
|
| 639 |
+
submit_tab32d = st.form_submit_button(":green[Confirm]")
|
| 640 |
+
|
| 641 |
+
if submit_tab32d:
|
| 642 |
+
st.session_state.bilateral_filtering = apply_tab32d
|
| 643 |
+
st.session_state.d = d_value
|
| 644 |
+
st.session_state.sigma_color = sigma_color
|
| 645 |
+
st.session_state.sigma_space = sigma_space
|
| 646 |
+
st.rerun()
|
| 647 |
+
|
| 648 |
+
with tab4: # Morphologie
|
| 649 |
+
list_select = st.segmented_control("Morphological operation:",
|
| 650 |
+
["Erosion", 'Dilation'],
|
| 651 |
+
selection_mode="multi")
|
| 652 |
+
if "Erosion" in list_select:
|
| 653 |
+
with st.form("tab_4a"):
|
| 654 |
+
st.markdown("💬 :green[Erosion?]",
|
| 655 |
+
help="The basic idea of erosion is just like soil erosion only, it erodes \
|
| 656 |
+
away the boundaries of foreground object (Always try to keep foreground in white). \
|
| 657 |
+
So what it does? The kernel slides through the image (as in 2D convolution). A pixel in the \
|
| 658 |
+
original image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1, \
|
| 659 |
+
otherwise it is eroded (made to zero). \n \
|
| 660 |
+
So what happends is that, all the pixels near boundary will be discarded depending upon the \
|
| 661 |
+
size of kernel. So the thickness or size of the foreground object decreases or simply white region \
|
| 662 |
+
decreases in the image. \n\
|
| 663 |
+
It is useful for removing small white noises, detach two connected objects etc. \n \
|
| 664 |
+
:orange[**Best practice :** convert to grayscale before apply erosion.]")
|
| 665 |
+
kernel_size_ero = st.slider("Kernel size:", 3, 21, 3, 2, key=102)
|
| 666 |
+
nb_iter = st.slider('Iterations number:', 1, 7, 1, 1, key=201)
|
| 667 |
+
|
| 668 |
+
c1, c2 = st.columns(2)
|
| 669 |
+
apply_tab4a = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=8)
|
| 670 |
+
with c2:
|
| 671 |
+
submit_tab4a = st.form_submit_button(":green[Confirm]")
|
| 672 |
+
|
| 673 |
+
if submit_tab4a:
|
| 674 |
+
st.session_state.erosion = apply_tab4a
|
| 675 |
+
st.session_state.erosion_kernel_size = kernel_size_ero
|
| 676 |
+
st.session_state.nb_iter_erosion = nb_iter
|
| 677 |
+
st.rerun()
|
| 678 |
+
|
| 679 |
+
if "Dilation" in list_select:
|
| 680 |
+
with st.form("tab_4b"):
|
| 681 |
+
st.markdown("💬 :green[Dilation?]",
|
| 682 |
+
help="The opposite of an erosion is a dilation. Just like an \
|
| 683 |
+
erosion will eat away at the foreground pixels, a dilation will grow the foreground pixels. \
|
| 684 |
+
Dilations increase the size of foreground objects and are especially useful for joining broken \
|
| 685 |
+
parts of an image together. Dilations, just as an erosion, also utilize structuring elements \
|
| 686 |
+
— a center pixel p of the structuring element is set to white if ANY pixel in the structuring \
|
| 687 |
+
element is > 0. \n \
|
| 688 |
+
:orange[**Best practice :** convert to grayscale before apply dilation.]")
|
| 689 |
+
kernel_size_dil = st.slider("Kernel size:", 3, 21, 3, 2, key=103)
|
| 690 |
+
nb_iter = st.slider('Iterations number:', 1, 7, 1, 1, key=202)
|
| 691 |
+
kernel = np.ones((kernel_size_dil,kernel_size_dil),np.uint8)
|
| 692 |
+
|
| 693 |
+
c1, c2 = st.columns(2)
|
| 694 |
+
apply_tab4b = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=9)
|
| 695 |
+
with c2:
|
| 696 |
+
submit_tab4b = st.form_submit_button(":green[Confirm]")
|
| 697 |
+
|
| 698 |
+
if submit_tab4b:
|
| 699 |
+
st.session_state.dilation = apply_tab4b
|
| 700 |
+
st.session_state.dilation_kernel_size = kernel_size_dil
|
| 701 |
+
st.session_state.nb_iter_dilation = nb_iter
|
| 702 |
+
st.rerun()
|
| 703 |
+
|
| 704 |
+
with tab5: # Thresholding
|
| 705 |
+
selection = st.segmented_control("Type:", ["Binarization", "Adaptative thresholding"])
|
| 706 |
+
match selection:
|
| 707 |
+
case "Binarization":
|
| 708 |
+
with st.form("tab5_a"):
|
| 709 |
+
st.markdown("💬 :green[What is thresholding?]",
|
| 710 |
+
help='''Thresholding is the binarization of an image. In general, we seek to
|
| 711 |
+
convert a grayscale image to a binary image, where the pixels are either
|
| 712 |
+
0 or 255.
|
| 713 |
+
A simple thresholding example would be selecting a threshold value T,
|
| 714 |
+
and then setting all pixel intensities less than T to 0, and all pixel
|
| 715 |
+
values greater than T to 255. In this way, we are able to create a binary
|
| 716 |
+
representation of the image.''')
|
| 717 |
+
st.markdown("*:orange[⚠ Image must be in gray scale]*")
|
| 718 |
+
cols_tab1 = st.columns([0.1, 0.9], gap="medium", vertical_alignment="center")
|
| 719 |
+
with cols_tab1[1]:
|
| 720 |
+
thresholding_type = cols_tab1[1].selectbox("Thresholding type:",
|
| 721 |
+
list(dict_thresholding_type.keys()))
|
| 722 |
+
with cols_tab1[0].popover(":material/info:", help="Help on thresholding type",
|
| 723 |
+
use_container_width=False):
|
| 724 |
+
st.link_button("📚:blue[cf. OpenCV documentation :]",
|
| 725 |
+
"https://docs.opencv.org/3.0-beta/modules/imgproc/doc/miscellaneous_transformations.html#threshold")
|
| 726 |
+
|
| 727 |
+
thresh = st.slider("Thresh :", 0, 255, 255, 1)
|
| 728 |
+
if thresholding_type in ["cv.THRESH_BINARY", "cv.THRESH_BINARY_INV"]:
|
| 729 |
+
value = st.slider("Value :", 0, 255, 255, 1)
|
| 730 |
+
else:
|
| 731 |
+
value = 255
|
| 732 |
+
|
| 733 |
+
cols_tab3 = st.columns(2, gap="medium", vertical_alignment="center")
|
| 734 |
+
otsu = cols_tab3[0].checkbox("Optimum Global Thresholding using Otsu’s Method?",
|
| 735 |
+
help='''Otsu’s method tries to find a threshold value
|
| 736 |
+
which minimizes the weighted within-class variance.
|
| 737 |
+
Since Variance is the spread of the distribution
|
| 738 |
+
about the mean. Thus, minimizing the within-class
|
| 739 |
+
variance will tend to make the classes compact.''')
|
| 740 |
+
cols_tab3[1].link_button("📚:blue[Documentation]",
|
| 741 |
+
"https://theailearner.com/2019/07/19/optimum-global-thresholding-using-otsus-method/")
|
| 742 |
+
|
| 743 |
+
thresh_typ = dict_thresholding_type[thresholding_type]
|
| 744 |
+
|
| 745 |
+
c1, c2 = st.columns(2)
|
| 746 |
+
apply_tab5a = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=10)
|
| 747 |
+
with c2:
|
| 748 |
+
submit_tab5a = st.form_submit_button(":green[Confirm]")
|
| 749 |
+
|
| 750 |
+
if submit_tab5a:
|
| 751 |
+
if otsu:
|
| 752 |
+
thresh_typ = thresh_typ+cv2.THRESH_OTSU
|
| 753 |
+
st.session_state.binarization = apply_tab5a
|
| 754 |
+
st.session_state.bin_thresh = thresh
|
| 755 |
+
st.session_state.bin_value = value
|
| 756 |
+
st.session_state.bin_thresholding_type = thresholding_type
|
| 757 |
+
st.session_state.bin_otsu = otsu
|
| 758 |
+
st.session_state.thresh_typ = thresh_typ
|
| 759 |
+
st.rerun()
|
| 760 |
+
|
| 761 |
+
case "Adaptative thresholding":
|
| 762 |
+
with st.form("tab5_b"):
|
| 763 |
+
st.markdown("💬 :green[What is adaptative thresholding?]",
|
| 764 |
+
help='''This is a usefull technique when dealing with images having non-uniform illumination.
|
| 765 |
+
In this, the threshold value is calculated separately for each pixel using
|
| 766 |
+
some statistics obtained from its neighborhood. This way we will get different thresholds
|
| 767 |
+
for different image regions and thus tackles the problem of varying illumination.''')
|
| 768 |
+
st.markdown("*:orange[⚠ Image must be in gray scale]*")
|
| 769 |
+
thresholding_type = st.selectbox("Thresholding type:",
|
| 770 |
+
list(dict_thresholding_type.keys())[:2])
|
| 771 |
+
max_value = st.slider("Max value :", 0, 255, 255, 1,
|
| 772 |
+
help="""This is the value assigned to the pixels after thresholding.
|
| 773 |
+
This depends on the thresholding type. If the type is cv2.THRESH_BINARY,
|
| 774 |
+
all the pixels greater than the threshold are assigned this maxValue.""")
|
| 775 |
+
adaptative_method = st.selectbox("Adaptative method:",
|
| 776 |
+
list(dict_adaptative_method.keys()),
|
| 777 |
+
help="""This tells us how the threshold is calculated from the pixel neighborhood.
|
| 778 |
+
This currently supports two methods:
|
| 779 |
+
- cv2.ADAPTIVE_THRESH_MEAN_C: In this, the threshold value is the mean of the neighborhood area.\n
|
| 780 |
+
- cv2.ADAPTIVE_THRESH_GAUSSIAN_C: In this, the threshold value is the weighted sum of the
|
| 781 |
+
neighborhood area. This uses Gaussian weights computed using getGaussiankernel() method.""")
|
| 782 |
+
block_size = st.slider("Block size:", 3, 21, 3, 2,
|
| 783 |
+
help='''**🔍 What is blockSize?**\n
|
| 784 |
+
In adaptive thresholding, the threshold for each pixel is determined based on a local neighborhood around it.
|
| 785 |
+
The blockSize parameter specifies the size of this neighborhood.
|
| 786 |
+
Specifically, it defines the dimensions of the square region (of size blockSize × blockSize) centered on the pixel being processed.
|
| 787 |
+
The threshold is then calculated based on the pixel values within this region.\n
|
| 788 |
+
**✅ Acceptable Values for blockSize**\n
|
| 789 |
+
Must be an odd integer greater than 1: This ensures that the neighborhood has a central pixel.
|
| 790 |
+
Common choices: 3, 5, 7, 9, 11, 13, 15, etc.
|
| 791 |
+
Even numbers are invalid: Using an even blockSize (e.g., 2, 4, 6) would result in an error because
|
| 792 |
+
there would be no central pixel in the neighborhood.\n
|
| 793 |
+
**🎯 Impact of blockSize on Thresholding**\n
|
| 794 |
+
Smaller blockSize (e.g., 3 or 5):\n
|
| 795 |
+
- Captures fine details and small variations in illumination.
|
| 796 |
+
- May be more sensitive to noise.\n
|
| 797 |
+
Larger blockSize (e.g., 15 or 21):\n
|
| 798 |
+
- Provides smoother thresholding, reducing the effect of noise.
|
| 799 |
+
- Might overlook small features or details.
|
| 800 |
+
|
| 801 |
+
Choosing the appropriate blockSize depends on the specific characteristics of your image and the details you wish to preserve or suppress.''')
|
| 802 |
+
const = st.slider("C:", -10, 20, 0, 1,
|
| 803 |
+
help='''The parameter C serves as a constant subtracted from the computed mean or weighted mean of the
|
| 804 |
+
neighborhood pixels. This subtraction fine-tunes the thresholding process, allowing for better control
|
| 805 |
+
over the binarization outcome.
|
| 806 |
+
**🎯 Typical Values for C**
|
| 807 |
+
The optimal value for C varies depending on the image's characteristics, such as lighting conditions and noise levels. Commonly used values include:
|
| 808 |
+
- 2 to 10: These values are often effective for standard images with moderate lighting variations.
|
| 809 |
+
- Higher values (e.g., 15 or 20): Useful for images with significant noise or when a more aggressive thresholding is needed.
|
| 810 |
+
- Negative values: Occasionally used to make the thresholding more lenient, capturing lighter details that might otherwise be missed.
|
| 811 |
+
|
| 812 |
+
It's advisable to experiment with different C values to determine the most suitable one for your specific application. ''')
|
| 813 |
+
|
| 814 |
+
c1, c2 = st.columns(2)
|
| 815 |
+
apply_tab5b = c1.toggle("Apply", help="Click here to indicate whether the operation should be carried out or not, then validate with Confirm.", key=11)
|
| 816 |
+
with c2:
|
| 817 |
+
submit_tab5b = st.form_submit_button(":green[Confirm]")
|
| 818 |
+
|
| 819 |
+
if submit_tab5b:
|
| 820 |
+
st.session_state.adaptative_thresh = apply_tab5b
|
| 821 |
+
st.session_state.at_max_value = max_value
|
| 822 |
+
st.session_state.at_adaptative_method = adaptative_method
|
| 823 |
+
st.session_state.at_thresholding_type = thresholding_type
|
| 824 |
+
st.session_state.at_block_size = block_size
|
| 825 |
+
st.session_state.at_const = const
|
| 826 |
+
st.rerun()
|
| 827 |
+
|
| 828 |
+
col1_a, col1_b = col1.columns(2)
|
| 829 |
+
if col1_a.button("📃 :blue[List of operations]"):
|
| 830 |
+
col1_a.write(list_op)
|
| 831 |
+
|
| 832 |
+
if col1_b.button("Prepare download"):
|
| 833 |
+
if len(img_wrk.shape) == 2:
|
| 834 |
+
pil_img = Image.fromarray(img_wrk).convert("L")
|
| 835 |
+
else:
|
| 836 |
+
img_rgb = cv2.cvtColor(img_wrk, cv2.COLOR_BGR2RGB)
|
| 837 |
+
pil_img = Image.fromarray(img_rgb)
|
| 838 |
+
img_bytes = io.BytesIO()
|
| 839 |
+
pil_img.save(img_bytes, format='PNG')
|
| 840 |
+
img_bytes.seek(0)
|
| 841 |
+
col1_b.download_button(
|
| 842 |
+
label="Download processed image",
|
| 843 |
+
data=img_bytes,
|
| 844 |
+
file_name="processed_image.png",
|
| 845 |
+
on_click="ignore",
|
| 846 |
+
icon=":material/download:",
|
| 847 |
+
mime="image/png"
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
with col2.expander(":blue[Quick overview of OCR recognition (with PPOCR)]", expanded=True):
|
| 851 |
+
with st.form("form1"):
|
| 852 |
+
key_ppocr_lang = st.selectbox("Choose language: :", dict_lang_ppocr.keys(), 20)
|
| 853 |
+
res_cnt = st.empty()
|
| 854 |
+
submit_detect = st.form_submit_button("Launch overview")
|
| 855 |
+
|
| 856 |
+
##----------- Process OCR --------------------------------------------------------------
|
| 857 |
+
if submit_detect:
|
| 858 |
+
with res_cnt, st.spinner("PPOCR initialization ..."):
|
| 859 |
+
ocr = PaddleOCR(lang=dict_lang_ppocr[key_ppocr_lang]) #, show_log=False)
|
| 860 |
+
with res_cnt, st.spinner("OCR process ..."):
|
| 861 |
+
result = ocr.ocr(img_wrk)
|
| 862 |
+
# draw result
|
| 863 |
+
result = result[0]
|
| 864 |
+
if len(img_wrk.shape) == 3:
|
| 865 |
+
image = img_wrk.copy()
|
| 866 |
+
else:
|
| 867 |
+
image = cv2.cvtColor(img_wrk, cv2.COLOR_GRAY2RGB)
|
| 868 |
+
boxes = [line[0] for line in result]
|
| 869 |
+
|
| 870 |
+
txts = [line[1][0] for line in result]
|
| 871 |
+
scores = [line[1][1] for line in result]
|
| 872 |
+
im_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/french.ttf')
|
| 873 |
+
im_show = Image.fromarray(im_show)
|
| 874 |
+
res_cnt.image(im_show, use_container_width=True)
|
fonts/arabic.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd25bfc3c6d745a8a4b4d415321aa5b43d99b61744b50d20e32931811ec7e268
|
| 3 |
+
size 102000
|
fonts/chinese_cht.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5ce814960d0cdea1dd647180636babc1cf6a0acf0a9a9019424f4689acedd9ea
|
| 3 |
+
size 7376416
|
fonts/cyrillic.ttf
ADDED
|
Binary file (56.2 kB). View file
|
|
|
fonts/french.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9
|
| 3 |
+
size 773236
|
fonts/german.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9
|
| 3 |
+
size 773236
|
fonts/hindi.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d519981fc26e2fe934bd25ec9dfe478e082c99063d868008b20996809e13ccc
|
| 3 |
+
size 222356
|
fonts/japan.ttc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11122490a5e3a862015c8894183750de59abf95c3936d63d5978293d92f23dba
|
| 3 |
+
size 3478068
|
fonts/kannada.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b337386a8e853ccba53c0c248bd06f025d7667b800ba74c72c66040d67315c6e
|
| 3 |
+
size 797016
|
fonts/korean.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0897316bdb2e308cea2841c54940f2ef5707856000aa07910c8bff39a47e40bd
|
| 3 |
+
size 1222780
|
fonts/latin.ttf
ADDED
|
Binary file (54.9 kB). View file
|
|
|
fonts/marathi.ttf
ADDED
|
Binary file (68.7 kB). View file
|
|
|
fonts/nepali.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d519981fc26e2fe934bd25ec9dfe478e082c99063d868008b20996809e13ccc
|
| 3 |
+
size 222356
|
fonts/persian.ttf
ADDED
|
Binary file (31.6 kB). View file
|
|
|
fonts/simfang.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:521c6f7546b4eb64fa4b0cd604bbd36333a20a57e388c8e2ad2ad07b9e593864
|
| 3 |
+
size 10576012
|
fonts/spanish.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3a3e632f80a2918e0536585ce52ecf2f379dc0f6b65b5b88d731ae52f9ac0d54
|
| 3 |
+
size 336452
|
fonts/tamil.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b771ac413157f6b1f1a52fb8ff1b56057f4b492fcce385ddd32ca12eee0c73b0
|
| 3 |
+
size 142512
|
fonts/telugu.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f82ab141b77d263f9ea9b31b47faf50c11310f42fce6d9dffeaaa334909bbf9
|
| 3 |
+
size 990048
|
fonts/urdu.ttf
ADDED
|
Binary file (38.8 kB). View file
|
|
|
fonts/uyghur.ttf
ADDED
|
Binary file (38.8 kB). View file
|
|
|
img_demo_enhance.png
ADDED
|
ocr_comparator.py
ADDED
|
@@ -0,0 +1,1301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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7.1,<1.1.0'])
|
| 8 |
+
#mim.install(['mmcv>=2.0.0rc4,<2.1.0'])
|
| 9 |
+
#mim.install(['mmdet>=3.0.rc5,<3.2.0'])
|
| 10 |
+
#mim.install(['mmocr'])
|
| 11 |
+
|
| 12 |
+
import streamlit as st
|
| 13 |
+
import plotly.express as px
|
| 14 |
+
import numpy as np
|
| 15 |
+
import math
|
| 16 |
+
import pandas as pd
|
| 17 |
+
from time import sleep
|
| 18 |
+
|
| 19 |
+
import cv2
|
| 20 |
+
from PIL import Image, ImageColor
|
| 21 |
+
import PIL
|
| 22 |
+
import easyocr
|
| 23 |
+
from paddleocr import PaddleOCR
|
| 24 |
+
#from mmocr.utils.ocr import MMOCR
|
| 25 |
+
import pytesseract
|
| 26 |
+
from pytesseract import Output
|
| 27 |
+
import os
|
| 28 |
+
from mycolorpy import colorlist as mcp
|
| 29 |
+
|
| 30 |
+
import os
|
| 31 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 32 |
+
###################################################################################################
|
| 33 |
+
## MAIN
|
| 34 |
+
###################################################################################################
|
| 35 |
+
#def app():
|
| 36 |
+
|
| 37 |
+
###################################################################################################
|
| 38 |
+
## FUNCTIONS
|
| 39 |
+
###################################################################################################
|
| 40 |
+
@st.cache_data
|
| 41 |
+
def convert_df(in_df):
|
| 42 |
+
"""Convert data frame function, used by download button
|
| 43 |
+
Args:
|
| 44 |
+
in_df (data frame): data frame to convert
|
| 45 |
+
Returns:
|
| 46 |
+
data frame: converted data frame
|
| 47 |
+
"""
|
| 48 |
+
# IMPORTANT: Cache the conversion to prevent computation on every rerun
|
| 49 |
+
return in_df.to_csv().encode('utf-8')
|
| 50 |
+
###
|
| 51 |
+
def easyocr_coord_convert(in_list_coord):
|
| 52 |
+
"""Convert easyocr coordinates to standard format used by others functions
|
| 53 |
+
Args:
|
| 54 |
+
in_list_coord (list of numbers): format [x_min, x_max, y_min, y_max]
|
| 55 |
+
Returns:
|
| 56 |
+
list of lists: format [ [x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max] ]
|
| 57 |
+
"""
|
| 58 |
+
coord = in_list_coord
|
| 59 |
+
return [[coord[0], coord[2]], [coord[1], coord[2]], [coord[1], coord[3]], [coord[0], coord[3]]]
|
| 60 |
+
###
|
| 61 |
+
@st.cache_data
|
| 62 |
+
def initializations():
|
| 63 |
+
"""Initializations for the app
|
| 64 |
+
Returns:
|
| 65 |
+
list of strings : list of OCR solutions names
|
| 66 |
+
(['EasyOCR', 'PPOCR', 'MMOCR', 'Tesseract'])
|
| 67 |
+
dict : names and indices of the OCR solutions
|
| 68 |
+
({'EasyOCR': 0, 'PPOCR': 1, 'MMOCR': 2, 'Tesseract': 3})
|
| 69 |
+
list of dicts : list of languages supported by each OCR solution
|
| 70 |
+
list of int : columns for recognition details results
|
| 71 |
+
dict : confidence color scale
|
| 72 |
+
plotly figure : confidence color scale figure
|
| 73 |
+
"""
|
| 74 |
+
# the readers considered
|
| 75 |
+
#out_reader_type_list = ['EasyOCR', 'PPOCR', 'MMOCR', 'Tesseract']
|
| 76 |
+
#out_reader_type_dict = {'EasyOCR': 0, 'PPOCR': 1, 'MMOCR': 2, 'Tesseract': 3}
|
| 77 |
+
out_reader_type_list = ['EasyOCR', 'PPOCR', 'Tesseract']
|
| 78 |
+
out_reader_type_dict = {'EasyOCR': 0, 'PPOCR': 1, 'Tesseract': 2}
|
| 79 |
+
# Columns for recognition details results
|
| 80 |
+
out_cols_size = [2] + [2,1]*(len(out_reader_type_list)-1) # Except Tesseract
|
| 81 |
+
# Dicts of laguages supported by each reader
|
| 82 |
+
out_dict_lang_easyocr = {'Abaza': 'abq', 'Adyghe': 'ady', 'Afrikaans': 'af', 'Angika': 'ang', \
|
| 83 |
+
'Arabic': 'ar', 'Assamese': 'as', 'Avar': 'ava', 'Azerbaijani': 'az', 'Belarusian': 'be', \
|
| 84 |
+
'Bulgarian': 'bg', 'Bihari': 'bh', 'Bhojpuri': 'bho', 'Bengali': 'bn', 'Bosnian': 'bs', \
|
| 85 |
+
'Simplified Chinese': 'ch_sim', 'Traditional Chinese': 'ch_tra', 'Chechen': 'che', \
|
| 86 |
+
'Czech': 'cs', 'Welsh': 'cy', 'Danish': 'da', 'Dargwa': 'dar', 'German': 'de', \
|
| 87 |
+
'English': 'en', 'Spanish': 'es', 'Estonian': 'et', 'Persian (Farsi)': 'fa', 'French': 'fr', \
|
| 88 |
+
'Irish': 'ga', 'Goan Konkani': 'gom', 'Hindi': 'hi', 'Croatian': 'hr', 'Hungarian': 'hu', \
|
| 89 |
+
'Indonesian': 'id', 'Ingush': 'inh', 'Icelandic': 'is', 'Italian': 'it', 'Japanese': 'ja', \
|
| 90 |
+
'Kabardian': 'kbd', 'Kannada': 'kn', 'Korean': 'ko', 'Kurdish': 'ku', 'Latin': 'la', \
|
| 91 |
+
'Lak': 'lbe', 'Lezghian': 'lez', 'Lithuanian': 'lt', 'Latvian': 'lv', 'Magahi': 'mah', \
|
| 92 |
+
'Maithili': 'mai', 'Maori': 'mi', 'Mongolian': 'mn', 'Marathi': 'mr', 'Malay': 'ms', \
|
| 93 |
+
'Maltese': 'mt', 'Nepali': 'ne', 'Newari': 'new', 'Dutch': 'nl', 'Norwegian': 'no', \
|
| 94 |
+
'Occitan': 'oc', 'Pali': 'pi', 'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', \
|
| 95 |
+
'Russian': 'ru', 'Serbian (cyrillic)': 'rs_cyrillic', 'Serbian (latin)': 'rs_latin', \
|
| 96 |
+
'Nagpuri': 'sck', 'Slovak': 'sk', 'Slovenian': 'sl', 'Albanian': 'sq', 'Swedish': 'sv', \
|
| 97 |
+
'Swahili': 'sw', 'Tamil': 'ta', 'Tabassaran': 'tab', 'Telugu': 'te', 'Thai': 'th', \
|
| 98 |
+
'Tajik': 'tjk', 'Tagalog': 'tl', 'Turkish': 'tr', 'Uyghur': 'ug', 'Ukranian': 'uk', \
|
| 99 |
+
'Urdu': 'ur', 'Uzbek': 'uz', 'Vietnamese': 'vi'}
|
| 100 |
+
out_dict_lang_ppocr = {'Abaza': 'abq', 'Adyghe': 'ady', 'Afrikaans': 'af', 'Albanian': 'sq', \
|
| 101 |
+
'Angika': 'ang', 'Arabic': 'ar', 'Avar': 'ava', 'Azerbaijani': 'az', 'Belarusian': 'be', \
|
| 102 |
+
'Bhojpuri': 'bho','Bihari': 'bh','Bosnian': 'bs','Bulgarian': 'bg','Chinese & English': 'ch', \
|
| 103 |
+
'Chinese Traditional': 'chinese_cht', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', \
|
| 104 |
+
'Dargwa': 'dar', 'Dutch': 'nl', 'English': 'en', 'Estonian': 'et', 'French': 'fr', \
|
| 105 |
+
'German': 'german','Goan Konkani': 'gom','Hindi': 'hi','Hungarian': 'hu','Icelandic': 'is', \
|
| 106 |
+
'Indonesian': 'id', 'Ingush': 'inh', 'Irish': 'ga', 'Italian': 'it', 'Japan': 'japan', \
|
| 107 |
+
'Kabardian': 'kbd', 'Korean': 'korean', 'Kurdish': 'ku', 'Lak': 'lbe', 'Latvian': 'lv', \
|
| 108 |
+
'Lezghian': 'lez', 'Lithuanian': 'lt', 'Magahi': 'mah', 'Maithili': 'mai', 'Malay': 'ms', \
|
| 109 |
+
'Maltese': 'mt', 'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Nagpur': 'sck', \
|
| 110 |
+
'Nepali': 'ne', 'Newari': 'new', 'Norwegian': 'no', 'Occitan': 'oc', 'Persian': 'fa', \
|
| 111 |
+
'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', 'Russia': 'ru', 'Saudi Arabia': 'sa', \
|
| 112 |
+
'Serbian(cyrillic)': 'rs_cyrillic', 'Serbian(latin)': 'rs_latin', 'Slovak': 'sk', \
|
| 113 |
+
'Slovenian': 'sl', 'Spanish': 'es', 'Swahili': 'sw', 'Swedish': 'sv', 'Tabassaran': 'tab', \
|
| 114 |
+
'Tagalog': 'tl', 'Tamil': 'ta', 'Telugu': 'te', 'Turkish': 'tr', 'Ukranian': 'uk', \
|
| 115 |
+
'Urdu': 'ur', 'Uyghur': 'ug', 'Uzbek': 'uz', 'Vietnamese': 'vi', 'Welsh': 'cy'}
|
| 116 |
+
#out_dict_lang_mmocr = {'English & Chinese': 'en'}
|
| 117 |
+
out_dict_lang_tesseract = {'Afrikaans': 'afr','Albanian': 'sqi','Amharic': 'amh', \
|
| 118 |
+
'Arabic': 'ara', 'Armenian': 'hye','Assamese': 'asm','Azerbaijani - Cyrilic': 'aze_cyrl', \
|
| 119 |
+
'Azerbaijani': 'aze', 'Basque': 'eus','Belarusian': 'bel','Bengali': 'ben','Bosnian': 'bos', \
|
| 120 |
+
'Breton': 'bre', 'Bulgarian': 'bul','Burmese': 'mya','Catalan; Valencian': 'cat', \
|
| 121 |
+
'Cebuano': 'ceb', 'Central Khmer': 'khm','Cherokee': 'chr','Chinese - Simplified': 'chi_sim', \
|
| 122 |
+
'Chinese - Traditional': 'chi_tra','Corsican': 'cos','Croatian': 'hrv','Czech': 'ces', \
|
| 123 |
+
'Danish':'dan','Dutch; Flemish':'nld','Dzongkha':'dzo','English, Middle (1100-1500)':'enm', \
|
| 124 |
+
'English': 'eng','Esperanto': 'epo','Estonian': 'est','Faroese': 'fao', \
|
| 125 |
+
'Filipino (old - Tagalog)': 'fil','Finnish': 'fin','French, Middle (ca.1400-1600)': 'frm', \
|
| 126 |
+
'French': 'fra','Galician': 'glg','Georgian - Old': 'kat_old','Georgian': 'kat', \
|
| 127 |
+
'German - Fraktur': 'frk','German': 'deu','Greek, Modern (1453-)': 'ell','Gujarati': 'guj', \
|
| 128 |
+
'Haitian; Haitian Creole': 'hat','Hebrew': 'heb','Hindi': 'hin','Hungarian': 'hun', \
|
| 129 |
+
'Icelandic': 'isl','Indonesian': 'ind','Inuktitut': 'iku','Irish': 'gle', \
|
| 130 |
+
'Italian - Old': 'ita_old','Italian': 'ita','Japanese': 'jpn','Javanese': 'jav', \
|
| 131 |
+
'Kannada': 'kan','Kazakh': 'kaz','Kirghiz; Kyrgyz': 'kir','Korean (vertical)': 'kor_vert', \
|
| 132 |
+
'Korean': 'kor','Kurdish (Arabic Script)': 'kur_ara','Lao': 'lao','Latin': 'lat', \
|
| 133 |
+
'Latvian':'lav','Lithuanian':'lit','Luxembourgish':'ltz','Macedonian':'mkd','Malay':'msa', \
|
| 134 |
+
'Malayalam': 'mal','Maltese': 'mlt','Maori': 'mri','Marathi': 'mar','Mongolian': 'mon', \
|
| 135 |
+
'Nepali': 'nep','Norwegian': 'nor','Occitan (post 1500)': 'oci', \
|
| 136 |
+
'Orientation and script detection module':'osd','Oriya':'ori','Panjabi; Punjabi':'pan', \
|
| 137 |
+
'Persian':'fas','Polish':'pol','Portuguese':'por','Pushto; Pashto':'pus','Quechua':'que', \
|
| 138 |
+
'Romanian; Moldavian; Moldovan': 'ron','Russian': 'rus','Sanskrit': 'san', \
|
| 139 |
+
'Scottish Gaelic': 'gla','Serbian - Latin': 'srp_latn','Serbian': 'srp','Sindhi': 'snd', \
|
| 140 |
+
'Sinhala; Sinhalese': 'sin','Slovak': 'slk','Slovenian': 'slv', \
|
| 141 |
+
'Spanish; Castilian - Old': 'spa_old','Spanish; Castilian': 'spa','Sundanese': 'sun', \
|
| 142 |
+
'Swahili': 'swa','Swedish': 'swe','Syriac': 'syr','Tajik': 'tgk','Tamil': 'tam', \
|
| 143 |
+
'Tatar':'tat','Telugu':'tel','Thai':'tha','Tibetan':'bod','Tigrinya':'tir','Tonga':'ton', \
|
| 144 |
+
'Turkish': 'tur','Uighur; Uyghur': 'uig','Ukrainian': 'ukr','Urdu': 'urd', \
|
| 145 |
+
'Uzbek - Cyrilic': 'uzb_cyrl','Uzbek': 'uzb','Vietnamese': 'vie','Welsh': 'cym', \
|
| 146 |
+
'Western Frisian': 'fry','Yiddish': 'yid','Yoruba': 'yor'}
|
| 147 |
+
out_list_dict_lang = [out_dict_lang_easyocr, out_dict_lang_ppocr, \
|
| 148 |
+
#out_dict_lang_mmocr, \
|
| 149 |
+
out_dict_lang_tesseract]
|
| 150 |
+
# Initialization of detection form
|
| 151 |
+
if 'columns_size' not in st.session_state:
|
| 152 |
+
st.session_state.columns_size = [2] + [1 for x in out_reader_type_list[1:]]
|
| 153 |
+
if 'column_width' not in st.session_state:
|
| 154 |
+
st.session_state.column_width = [400] + [300 for x in out_reader_type_list[1:]]
|
| 155 |
+
if 'columns_color' not in st.session_state:
|
| 156 |
+
st.session_state.columns_color = ["rgb(228,26,28)"] + \
|
| 157 |
+
["rgb(79, 43, 255)" for x in out_reader_type_list[1:]]
|
| 158 |
+
if 'list_coordinates' not in st.session_state:
|
| 159 |
+
st.session_state.list_coordinates = []
|
| 160 |
+
# Confidence color scale
|
| 161 |
+
out_list_confid = list(np.arange(0,101,1))
|
| 162 |
+
out_list_grad = mcp.gen_color_normalized(cmap="Greens",data_arr=np.array(out_list_confid))
|
| 163 |
+
out_dict_back_colors = {out_list_confid[i]: out_list_grad[i] \
|
| 164 |
+
for i in range(len(out_list_confid))}
|
| 165 |
+
list_y = [1 for i in out_list_confid]
|
| 166 |
+
df_confid = pd.DataFrame({'% confidence scale': out_list_confid, 'y': list_y})
|
| 167 |
+
out_fig = px.scatter(df_confid, x='% confidence scale', y='y', \
|
| 168 |
+
hover_data={'% confidence scale': True, 'y': False},
|
| 169 |
+
color=out_dict_back_colors.values(), range_y=[0.9,1.1], range_x=[0,100],
|
| 170 |
+
color_discrete_map="identity",height=50,symbol='y',symbol_sequence=['square'])
|
| 171 |
+
out_fig.update_xaxes(showticklabels=False)
|
| 172 |
+
out_fig.update_yaxes(showticklabels=False, range=[0.1, 1.1], visible=False)
|
| 173 |
+
out_fig.update_traces(marker_size=50)
|
| 174 |
+
out_fig.update_layout(paper_bgcolor="white", margin=dict(b=0,r=0,t=0,l=0), xaxis_side="top", \
|
| 175 |
+
showlegend=False)
|
| 176 |
+
return out_reader_type_list, out_reader_type_dict, out_list_dict_lang, \
|
| 177 |
+
out_cols_size, out_dict_back_colors, out_fig
|
| 178 |
+
###
|
| 179 |
+
@st.cache_data
|
| 180 |
+
def init_easyocr(in_params):
|
| 181 |
+
"""Initialization of easyOCR reader
|
| 182 |
+
Args:
|
| 183 |
+
in_params (list): list with the language
|
| 184 |
+
Returns:
|
| 185 |
+
easyocr reader: the easyocr reader instance
|
| 186 |
+
"""
|
| 187 |
+
out_ocr = easyocr.Reader(in_params)
|
| 188 |
+
return out_ocr
|
| 189 |
+
###
|
| 190 |
+
|
| 191 |
+
def init_ppocr(in_params):
|
| 192 |
+
"""Initialization of PPOCR reader
|
| 193 |
+
Args:
|
| 194 |
+
in_params (dict): dict with parameters
|
| 195 |
+
Returns:
|
| 196 |
+
ppocr reader: the ppocr reader instance
|
| 197 |
+
"""
|
| 198 |
+
out_ocr = PaddleOCR(lang=in_params[0], **in_params[1])
|
| 199 |
+
return out_ocr
|
| 200 |
+
###
|
| 201 |
+
#@st.cache_data(show_spinner=False)
|
| 202 |
+
#def init_mmocr(in_params):
|
| 203 |
+
# """Initialization of MMOCR reader
|
| 204 |
+
|
| 205 |
+
# Args:
|
| 206 |
+
# in_params (dict): dict with parameters
|
| 207 |
+
|
| 208 |
+
# Returns:
|
| 209 |
+
# mmocr reader: the ppocr reader instance
|
| 210 |
+
# """
|
| 211 |
+
# out_ocr = MMOCR(recog=None, **in_params[1])
|
| 212 |
+
# return out_ocr
|
| 213 |
+
###
|
| 214 |
+
def init_readers(in_list_params):
|
| 215 |
+
"""Initialization of the readers, and return them as list
|
| 216 |
+
Args:
|
| 217 |
+
in_list_params (list): list of dicts of parameters for each reader
|
| 218 |
+
Returns:
|
| 219 |
+
list: list of the reader's instances
|
| 220 |
+
"""
|
| 221 |
+
# Instantiations of the readers :
|
| 222 |
+
# - EasyOCR
|
| 223 |
+
with st.spinner("EasyOCR reader initialization in progress ..."):
|
| 224 |
+
reader_easyocr = init_easyocr([in_list_params[0][0]])
|
| 225 |
+
# - PPOCR
|
| 226 |
+
# Paddleocr
|
| 227 |
+
with st.spinner("PPOCR reader initialization in progress ..."):
|
| 228 |
+
reader_ppocr = init_ppocr(in_list_params[1])
|
| 229 |
+
# - MMOCR
|
| 230 |
+
#with st.spinner("MMOCR reader initialization in progress ..."):
|
| 231 |
+
# reader_mmocr = init_mmocr(in_list_params[2])
|
| 232 |
+
out_list_readers = [reader_easyocr, reader_ppocr] #, reader_mmocr]
|
| 233 |
+
return out_list_readers
|
| 234 |
+
###
|
| 235 |
+
def load_image(in_image_file):
|
| 236 |
+
"""Load input file and open it
|
| 237 |
+
Args:
|
| 238 |
+
in_image_file (string or Streamlit UploadedFile): image to consider
|
| 239 |
+
Returns:
|
| 240 |
+
string : locally saved image path (img.)
|
| 241 |
+
PIL.Image : input file opened with Pillow
|
| 242 |
+
matrix : input file opened with Opencv
|
| 243 |
+
"""
|
| 244 |
+
#if isinstance(in_image_file, str):
|
| 245 |
+
# out_image_path = "img."+in_image_file.split('.')[-1]
|
| 246 |
+
#else:
|
| 247 |
+
# out_image_path = "img."+in_image_file.name.split('.')[-1]
|
| 248 |
+
if isinstance(in_image_file, str):
|
| 249 |
+
out_image_path = "tmp_"+in_image_file
|
| 250 |
+
else:
|
| 251 |
+
out_image_path = "tmp_"+in_image_file.name
|
| 252 |
+
img = Image.open(in_image_file)
|
| 253 |
+
img_saved = img.save(out_image_path)
|
| 254 |
+
# Read image
|
| 255 |
+
out_image_orig = Image.open(out_image_path)
|
| 256 |
+
out_image_cv2 = cv2.cvtColor(cv2.imread(out_image_path), cv2.COLOR_BGR2RGB)
|
| 257 |
+
return out_image_path, out_image_orig, out_image_cv2
|
| 258 |
+
###
|
| 259 |
+
@st.cache_data(show_spinner=False)
|
| 260 |
+
def easyocr_detect(_in_reader, in_image_path, in_params):
|
| 261 |
+
"""Detection with EasyOCR
|
| 262 |
+
Args:
|
| 263 |
+
_in_reader (EasyOCR reader) : the previously initialized instance
|
| 264 |
+
in_image_path (string ) : locally saved image path
|
| 265 |
+
in_params (list) : list with the parameters for detection
|
| 266 |
+
Returns:
|
| 267 |
+
list : list of the boxes coordinates
|
| 268 |
+
exception on error, string 'OK' otherwise
|
| 269 |
+
"""
|
| 270 |
+
try:
|
| 271 |
+
dict_param = in_params[1]
|
| 272 |
+
detection_result = _in_reader.detect(in_image_path,
|
| 273 |
+
#width_ths=0.7,
|
| 274 |
+
#mag_ratio=1.5
|
| 275 |
+
**dict_param
|
| 276 |
+
)
|
| 277 |
+
easyocr_coordinates = detection_result[0][0]
|
| 278 |
+
# The format of the coordinate is as follows: [x_min, x_max, y_min, y_max]
|
| 279 |
+
# Format boxes coordinates for draw
|
| 280 |
+
out_easyocr_boxes_coordinates = list(map(easyocr_coord_convert, easyocr_coordinates))
|
| 281 |
+
out_status = 'OK'
|
| 282 |
+
except Exception as e:
|
| 283 |
+
out_easyocr_boxes_coordinates = []
|
| 284 |
+
out_status = e
|
| 285 |
+
return out_easyocr_boxes_coordinates, out_status
|
| 286 |
+
###
|
| 287 |
+
@st.cache_data(show_spinner=False)
|
| 288 |
+
def ppocr_detect(_in_reader, in_image_path):
|
| 289 |
+
"""Detection with PPOCR
|
| 290 |
+
Args:
|
| 291 |
+
_in_reader (PPOCR reader) : the previously initialized instance
|
| 292 |
+
in_image_path (string ) : locally saved image path
|
| 293 |
+
Returns:
|
| 294 |
+
list : list of the boxes coordinates
|
| 295 |
+
exception on error, string 'OK' otherwise
|
| 296 |
+
"""
|
| 297 |
+
# PPOCR detection method
|
| 298 |
+
try:
|
| 299 |
+
out_ppocr_boxes_coordinates = _in_reader.ocr(in_image_path, rec=False)
|
| 300 |
+
out_status = 'OK'
|
| 301 |
+
except Exception as e:
|
| 302 |
+
out_ppocr_boxes_coordinates = []
|
| 303 |
+
out_status = e
|
| 304 |
+
return out_ppocr_boxes_coordinates, out_status
|
| 305 |
+
###
|
| 306 |
+
#@st.cache_data(show_spinner=False)
|
| 307 |
+
#def mmocr_detect(_in_reader, in_image_path):
|
| 308 |
+
# """Detection with MMOCR
|
| 309 |
+
|
| 310 |
+
# Args:
|
| 311 |
+
# _in_reader (MMOCR reader) : the previously initialized instance
|
| 312 |
+
# in_image_path (string) : locally saved image path
|
| 313 |
+
# in_params (list) : list with the parameters
|
| 314 |
+
|
| 315 |
+
# Returns:
|
| 316 |
+
# list : list of the boxes coordinates
|
| 317 |
+
# exception on error, string 'OK' otherwise
|
| 318 |
+
# """
|
| 319 |
+
# # MMOCR detection method
|
| 320 |
+
# out_mmocr_boxes_coordinates = []
|
| 321 |
+
# try:
|
| 322 |
+
# det_result = _in_reader.readtext(in_image_path, details=True)
|
| 323 |
+
# bboxes_list = [res['boundary_result'] for res in det_result]
|
| 324 |
+
# for bboxes in bboxes_list:
|
| 325 |
+
# for bbox in bboxes:
|
| 326 |
+
# if len(bbox) > 9:
|
| 327 |
+
# min_x = min(bbox[0:-1:2])
|
| 328 |
+
# min_y = min(bbox[1:-1:2])
|
| 329 |
+
# max_x = max(bbox[0:-1:2])
|
| 330 |
+
# max_y = max(bbox[1:-1:2])
|
| 331 |
+
# #box = [min_x, min_y, max_x, min_y, max_x, max_y, min_x, max_y]
|
| 332 |
+
# else:
|
| 333 |
+
# min_x = min(bbox[0:-1:2])
|
| 334 |
+
# min_y = min(bbox[1::2])
|
| 335 |
+
# max_x = max(bbox[0:-1:2])
|
| 336 |
+
# max_y = max(bbox[1::2])
|
| 337 |
+
# box4 = [ [min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y] ]
|
| 338 |
+
# out_mmocr_boxes_coordinates.append(box4)
|
| 339 |
+
# out_status = 'OK'
|
| 340 |
+
# except Exception as e:
|
| 341 |
+
# out_status = e
|
| 342 |
+
|
| 343 |
+
# return out_mmocr_boxes_coordinates, out_status
|
| 344 |
+
###
|
| 345 |
+
def cropped_1box(in_box, in_img):
|
| 346 |
+
"""Construction of an cropped image corresponding to an area of the initial image
|
| 347 |
+
Args:
|
| 348 |
+
in_box (list) : box with coordinates
|
| 349 |
+
in_img (matrix) : image
|
| 350 |
+
Returns:
|
| 351 |
+
matrix : cropped image
|
| 352 |
+
"""
|
| 353 |
+
box_ar = np.array(in_box).astype(np.int64)
|
| 354 |
+
x_min = box_ar[:, 0].min()
|
| 355 |
+
x_max = box_ar[:, 0].max()
|
| 356 |
+
y_min = box_ar[:, 1].min()
|
| 357 |
+
y_max = box_ar[:, 1].max()
|
| 358 |
+
out_cropped = in_img[y_min:y_max, x_min:x_max]
|
| 359 |
+
return out_cropped
|
| 360 |
+
###
|
| 361 |
+
@st.cache_data(show_spinner=False)
|
| 362 |
+
def tesserocr_detect(in_image_path, _in_img, in_params):
|
| 363 |
+
"""Detection with Tesseract
|
| 364 |
+
Args:
|
| 365 |
+
in_image_path (string) : locally saved image path
|
| 366 |
+
_in_img (PIL.Image) : image to consider
|
| 367 |
+
in_params (list) : list with the parameters for detection
|
| 368 |
+
Returns:
|
| 369 |
+
list : list of the boxes coordinates
|
| 370 |
+
exception on error, string 'OK' otherwise
|
| 371 |
+
"""
|
| 372 |
+
try:
|
| 373 |
+
dict_param = in_params[1]
|
| 374 |
+
df_res = pytesseract.image_to_data(_in_img, **dict_param, output_type=Output.DATAFRAME)
|
| 375 |
+
df_res['box'] = df_res.apply(lambda d: [[d['left'], d['top']], \
|
| 376 |
+
[d['left'] + d['width'], d['top']], \
|
| 377 |
+
[d['left'] + d['width'], d['top'] + d['height']], \
|
| 378 |
+
[d['left'], d['top'] + d['height']], \
|
| 379 |
+
], axis=1)
|
| 380 |
+
out_tesserocr_boxes_coordinates = df_res[df_res.word_num > 0]['box'].to_list()
|
| 381 |
+
out_status = 'OK'
|
| 382 |
+
except Exception as e:
|
| 383 |
+
out_tesserocr_boxes_coordinates = []
|
| 384 |
+
out_status = e
|
| 385 |
+
return out_tesserocr_boxes_coordinates, out_status
|
| 386 |
+
###
|
| 387 |
+
@st.cache_data(show_spinner=False)
|
| 388 |
+
def process_detect(in_image_path, _in_list_images, _in_list_readers, in_list_params, in_color):
|
| 389 |
+
"""Detection process for each OCR solution
|
| 390 |
+
Args:
|
| 391 |
+
in_image_path (string) : locally saved image path
|
| 392 |
+
_in_list_images (list) : list of original image
|
| 393 |
+
_in_list_readers (list) : list with previously initialized reader's instances
|
| 394 |
+
in_list_params (list) : list with dict parameters for each OCR solution
|
| 395 |
+
in_color (tuple) : color for boxes around text
|
| 396 |
+
Returns:
|
| 397 |
+
list: list of detection results images
|
| 398 |
+
list: list of boxes coordinates
|
| 399 |
+
"""
|
| 400 |
+
## ------- EasyOCR Text detection
|
| 401 |
+
with st.spinner('EasyOCR Text detection in progress ...'):
|
| 402 |
+
easyocr_boxes_coordinates,easyocr_status = easyocr_detect(_in_list_readers[0], \
|
| 403 |
+
in_image_path, in_list_params[0])
|
| 404 |
+
# Visualization
|
| 405 |
+
if easyocr_boxes_coordinates:
|
| 406 |
+
easyocr_image_detect = draw_detected(_in_list_images[0], easyocr_boxes_coordinates, \
|
| 407 |
+
in_color, 'None', 3)
|
| 408 |
+
else:
|
| 409 |
+
easyocr_boxes_coordinates = easyocr_status
|
| 410 |
+
##
|
| 411 |
+
## ------- PPOCR Text detection
|
| 412 |
+
with st.spinner('PPOCR Text detection in progress ...'):
|
| 413 |
+
list_ppocr_boxes_coordinates, ppocr_status = ppocr_detect(_in_list_readers[1], in_image_path)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# Visualization
|
| 417 |
+
try:
|
| 418 |
+
ppocr_boxes_coordinates = list_ppocr_boxes_coordinates[0]
|
| 419 |
+
ppocr_image_detect = draw_detected(_in_list_images[0], ppocr_boxes_coordinates, \
|
| 420 |
+
in_color, 'None', 3)
|
| 421 |
+
except:
|
| 422 |
+
ppocr_boxes_coordinates = []
|
| 423 |
+
ppocr_image_detect = ppocr_status
|
| 424 |
+
##
|
| 425 |
+
## ------- MMOCR Text detection
|
| 426 |
+
#with st.spinner('MMOCR Text detection in progress ...'):
|
| 427 |
+
# mmocr_boxes_coordinates, mmocr_status = mmocr_detect(_in_list_readers[2], in_image_path)
|
| 428 |
+
# # Visualization
|
| 429 |
+
# if mmocr_boxes_coordinates:
|
| 430 |
+
# mmocr_image_detect = draw_detected(_in_list_images[0], mmocr_boxes_coordinates, \
|
| 431 |
+
# in_color, 'None', 3)
|
| 432 |
+
# else:
|
| 433 |
+
# mmocr_image_detect = mmocr_status
|
| 434 |
+
##
|
| 435 |
+
## ------- Tesseract Text detection
|
| 436 |
+
with st.spinner('Tesseract Text detection in progress ...'):
|
| 437 |
+
tesserocr_boxes_coordinates, tesserocr_status = tesserocr_detect(in_image_path, \
|
| 438 |
+
_in_list_images[0], \
|
| 439 |
+
in_list_params[2]) #in_list_params[3]
|
| 440 |
+
# Visualization
|
| 441 |
+
if tesserocr_status == 'OK':
|
| 442 |
+
tesserocr_image_detect = draw_detected(_in_list_images[0],tesserocr_boxes_coordinates,\
|
| 443 |
+
in_color, 'None', 3)
|
| 444 |
+
else:
|
| 445 |
+
tesserocr_image_detect = tesserocr_status
|
| 446 |
+
##
|
| 447 |
+
#
|
| 448 |
+
out_list_images = _in_list_images + [easyocr_image_detect, ppocr_image_detect, \
|
| 449 |
+
# mmocr_image_detect, \
|
| 450 |
+
tesserocr_image_detect]
|
| 451 |
+
out_list_coordinates = [easyocr_boxes_coordinates, ppocr_boxes_coordinates, \
|
| 452 |
+
# mmocr_boxes_coordinates, \
|
| 453 |
+
tesserocr_boxes_coordinates]
|
| 454 |
+
#
|
| 455 |
+
return out_list_images, out_list_coordinates
|
| 456 |
+
###
|
| 457 |
+
def draw_detected(in_image, in_boxes_coordinates, in_color, posit='None', in_thickness=4):
|
| 458 |
+
"""Draw boxes around detected text
|
| 459 |
+
Args:
|
| 460 |
+
in_image (PIL.Image) : original image
|
| 461 |
+
in_boxes_coordinates (list) : boxes coordinates, from top to bottom and from left to right
|
| 462 |
+
[ [ [x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max] ],
|
| 463 |
+
[ ... ]
|
| 464 |
+
]
|
| 465 |
+
in_color (tuple) : color for boxes around text
|
| 466 |
+
posit (str, optional) : position for text. Defaults to 'None'.
|
| 467 |
+
in_thickness (int, optional): thickness of the box. Defaults to 4.
|
| 468 |
+
Returns:
|
| 469 |
+
PIL.Image : original image with detected areas
|
| 470 |
+
"""
|
| 471 |
+
work_img = in_image.copy()
|
| 472 |
+
if in_boxes_coordinates:
|
| 473 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 474 |
+
for ind_box, box in enumerate(in_boxes_coordinates):
|
| 475 |
+
box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
|
| 476 |
+
work_img = cv2.polylines(np.array(work_img), [box], True, in_color, in_thickness)
|
| 477 |
+
if posit != 'None':
|
| 478 |
+
if posit == 'top_left':
|
| 479 |
+
pos = tuple(box[0][0])
|
| 480 |
+
elif posit == 'top_right':
|
| 481 |
+
pos = tuple(box[1][0])
|
| 482 |
+
work_img = cv2.putText(work_img, str(ind_box+1), pos, font, 5.5, color, \
|
| 483 |
+
in_thickness,cv2.LINE_AA)
|
| 484 |
+
out_image_drawn = Image.fromarray(work_img)
|
| 485 |
+
else:
|
| 486 |
+
out_image_drawn = work_img
|
| 487 |
+
return out_image_drawn
|
| 488 |
+
###
|
| 489 |
+
@st.cache_data(show_spinner=False)
|
| 490 |
+
def get_cropped(in_boxes_coordinates, in_image_cv):
|
| 491 |
+
"""Construct list of cropped images corresponding of the input boxes coordinates list
|
| 492 |
+
Args:
|
| 493 |
+
in_boxes_coordinates (list) : list of boxes coordinates
|
| 494 |
+
in_image_cv (matrix) : original image
|
| 495 |
+
Returns:
|
| 496 |
+
list : list with cropped images
|
| 497 |
+
"""
|
| 498 |
+
out_list_images = []
|
| 499 |
+
for box in in_boxes_coordinates:
|
| 500 |
+
cropped = cropped_1box(box, in_image_cv)
|
| 501 |
+
out_list_images.append(cropped)
|
| 502 |
+
return out_list_images
|
| 503 |
+
###
|
| 504 |
+
def process_recog(in_list_readers, in_image_cv, in_boxes_coordinates, in_list_dict_params):
|
| 505 |
+
"""Recognition process for each OCR solution
|
| 506 |
+
Args:
|
| 507 |
+
in_list_readers (list) : list with previously initialized reader's instances
|
| 508 |
+
in_image_cv (matrix) : original image
|
| 509 |
+
in_boxes_coordinates (list) : list of boxes coordinates
|
| 510 |
+
in_list_dict_params (list) : list with dict parameters for each OCR solution
|
| 511 |
+
Returns:
|
| 512 |
+
data frame : results for each OCR solution, except Tesseract
|
| 513 |
+
data frame : results for Tesseract
|
| 514 |
+
list : status for each recognition (exception or 'OK')
|
| 515 |
+
"""
|
| 516 |
+
out_df_results = pd.DataFrame([])
|
| 517 |
+
list_text_easyocr = []
|
| 518 |
+
list_confidence_easyocr = []
|
| 519 |
+
list_text_ppocr = []
|
| 520 |
+
list_confidence_ppocr = []
|
| 521 |
+
#list_text_mmocr = []
|
| 522 |
+
#list_confidence_mmocr = []
|
| 523 |
+
# Create cropped images from detection
|
| 524 |
+
list_cropped_images = get_cropped(in_boxes_coordinates, in_image_cv)
|
| 525 |
+
# Recognize with EasyOCR
|
| 526 |
+
with st.spinner('EasyOCR Text recognition in progress ...'):
|
| 527 |
+
list_text_easyocr, list_confidence_easyocr, status_easyocr = \
|
| 528 |
+
easyocr_recog(list_cropped_images, in_list_readers[0], in_list_dict_params[0])
|
| 529 |
+
##
|
| 530 |
+
# Recognize with PPOCR
|
| 531 |
+
with st.spinner('PPOCR Text recognition in progress ...'):
|
| 532 |
+
list_text_ppocr, list_confidence_ppocr, status_ppocr = \
|
| 533 |
+
ppocr_recog(list_cropped_images, in_list_dict_params[1])
|
| 534 |
+
##
|
| 535 |
+
# Recognize with MMOCR
|
| 536 |
+
#with st.spinner('MMOCR Text recognition in progress ...'):
|
| 537 |
+
# list_text_mmocr, list_confidence_mmocr, status_mmocr = \
|
| 538 |
+
# mmocr_recog(list_cropped_images, in_list_dict_params[2])
|
| 539 |
+
##
|
| 540 |
+
# Recognize with Tesseract
|
| 541 |
+
with st.spinner('Tesseract Text recognition in progress ...'):
|
| 542 |
+
out_df_results_tesseract, status_tesseract = \
|
| 543 |
+
tesserocr_recog(in_image_cv, in_list_dict_params[2], len(list_cropped_images))
|
| 544 |
+
#tesserocr_recog(in_image_cv, in_list_dict_params[3], len(list_cropped_images))
|
| 545 |
+
##
|
| 546 |
+
# Create results data frame
|
| 547 |
+
out_df_results = pd.DataFrame({'cropped_image': list_cropped_images,
|
| 548 |
+
'text_easyocr': list_text_easyocr,
|
| 549 |
+
'confidence_easyocr': list_confidence_easyocr,
|
| 550 |
+
'text_ppocr': list_text_ppocr,
|
| 551 |
+
'confidence_ppocr': list_confidence_ppocr,
|
| 552 |
+
#'text_mmocr': list_text_mmocr,
|
| 553 |
+
#'confidence_mmocr': list_confidence_mmocr
|
| 554 |
+
}
|
| 555 |
+
)
|
| 556 |
+
#out_list_reco_status = [status_easyocr, status_ppocr, status_mmocr, status_tesseract]
|
| 557 |
+
out_list_reco_status = [status_easyocr, status_ppocr, status_tesseract]
|
| 558 |
+
return out_df_results, out_df_results_tesseract, out_list_reco_status
|
| 559 |
+
###
|
| 560 |
+
@st.cache_data
|
| 561 |
+
def easyocr_recog(in_list_images, _in_reader_easyocr, in_params):
|
| 562 |
+
"""Recognition with EasyOCR
|
| 563 |
+
Args:
|
| 564 |
+
in_list_images (list) : list of cropped images
|
| 565 |
+
_in_reader_easyocr (EasyOCR reader) : the previously initialized instance
|
| 566 |
+
in_params (dict) : parameters for recognition
|
| 567 |
+
Returns:
|
| 568 |
+
list : list of recognized text
|
| 569 |
+
list : list of recognition confidence
|
| 570 |
+
string/Exception : recognition status
|
| 571 |
+
"""
|
| 572 |
+
progress_bar = st.progress(0)
|
| 573 |
+
out_list_text_easyocr = []
|
| 574 |
+
out_list_confidence_easyocr = []
|
| 575 |
+
## ------- EasyOCR Text recognition
|
| 576 |
+
try:
|
| 577 |
+
step = 0*len(in_list_images) # first recognition process
|
| 578 |
+
#nb_steps = 4 * len(in_list_images)
|
| 579 |
+
nb_steps = 3 * len(in_list_images)
|
| 580 |
+
for ind_img, cropped in enumerate(in_list_images):
|
| 581 |
+
result = _in_reader_easyocr.recognize(cropped, **in_params)
|
| 582 |
+
try:
|
| 583 |
+
out_list_text_easyocr.append(result[0][1])
|
| 584 |
+
out_list_confidence_easyocr.append(np.round(100*result[0][2], 1))
|
| 585 |
+
except:
|
| 586 |
+
out_list_text_easyocr.append('Not recognize')
|
| 587 |
+
out_list_confidence_easyocr.append(100.)
|
| 588 |
+
progress_bar.progress((step+ind_img+1)/nb_steps)
|
| 589 |
+
out_status = 'OK'
|
| 590 |
+
except Exception as e:
|
| 591 |
+
out_status = e
|
| 592 |
+
progress_bar.empty()
|
| 593 |
+
return out_list_text_easyocr, out_list_confidence_easyocr, out_status
|
| 594 |
+
###
|
| 595 |
+
@st.cache_data
|
| 596 |
+
def ppocr_recog(in_list_images, in_params):
|
| 597 |
+
"""Recognition with PPOCR
|
| 598 |
+
Args:
|
| 599 |
+
in_list_images (list) : list of cropped images
|
| 600 |
+
in_params (dict) : parameters for recognition
|
| 601 |
+
Returns:
|
| 602 |
+
list : list of recognized text
|
| 603 |
+
list : list of recognition confidence
|
| 604 |
+
string/Exception : recognition status
|
| 605 |
+
"""
|
| 606 |
+
## ------- PPOCR Text recognition
|
| 607 |
+
out_list_text_ppocr = []
|
| 608 |
+
out_list_confidence_ppocr = []
|
| 609 |
+
try:
|
| 610 |
+
reader_ppocr = PaddleOCR(**in_params)
|
| 611 |
+
step = 1*len(in_list_images) # second recognition process
|
| 612 |
+
#nb_steps = 4 * len(in_list_images)
|
| 613 |
+
nb_steps = 3 * len(in_list_images)
|
| 614 |
+
progress_bar = st.progress(step/nb_steps)
|
| 615 |
+
for ind_img, cropped in enumerate(in_list_images):
|
| 616 |
+
list_result = reader_ppocr.ocr(cropped, det=False, cls=False)
|
| 617 |
+
result = list_result[0]
|
| 618 |
+
try:
|
| 619 |
+
out_list_text_ppocr.append(result[0][0])
|
| 620 |
+
out_list_confidence_ppocr.append(np.round(100*result[0][1], 1))
|
| 621 |
+
except:
|
| 622 |
+
out_list_text_ppocr.append('Not recognize')
|
| 623 |
+
out_list_confidence_ppocr.append(100.)
|
| 624 |
+
progress_bar.progress((step+ind_img+1)/nb_steps)
|
| 625 |
+
out_status = 'OK'
|
| 626 |
+
except Exception as e:
|
| 627 |
+
out_status = e
|
| 628 |
+
progress_bar.empty()
|
| 629 |
+
return out_list_text_ppocr, out_list_confidence_ppocr, out_status
|
| 630 |
+
###
|
| 631 |
+
#@st.cache_data(suppress_st_warning=True, show_spinner=False)
|
| 632 |
+
#def mmocr_recog(in_list_images, in_params):
|
| 633 |
+
# """Recognition with MMOCR
|
| 634 |
+
|
| 635 |
+
# Args:
|
| 636 |
+
# in_list_images (list) : list of cropped images
|
| 637 |
+
# in_params (dict) : parameters for recognition
|
| 638 |
+
|
| 639 |
+
# Returns:
|
| 640 |
+
# list : list of recognized text
|
| 641 |
+
# list : list of recognition confidence
|
| 642 |
+
# string/Exception : recognition status
|
| 643 |
+
# """
|
| 644 |
+
# ## ------- MMOCR Text recognition
|
| 645 |
+
# out_list_text_mmocr = []
|
| 646 |
+
# out_list_confidence_mmocr = []
|
| 647 |
+
# try:
|
| 648 |
+
# reader_mmocr = MMOCR(det=None, **in_params)
|
| 649 |
+
# step = 2*len(in_list_images) # third recognition process
|
| 650 |
+
# nb_steps = 4 * len(in_list_images)
|
| 651 |
+
# progress_bar = st.progress(step/nb_steps)
|
| 652 |
+
|
| 653 |
+
# for ind_img, cropped in enumerate(in_list_images):
|
| 654 |
+
# result = reader_mmocr.readtext(cropped, details=True)
|
| 655 |
+
# try:
|
| 656 |
+
# out_list_text_mmocr.append(result[0]['text'])
|
| 657 |
+
# out_list_confidence_mmocr.append(np.round(100* \
|
| 658 |
+
# (np.array(result[0]['score']).mean()), 1))
|
| 659 |
+
# except:
|
| 660 |
+
# out_list_text_mmocr.append('Not recognize')
|
| 661 |
+
# out_list_confidence_mmocr.append(100.)
|
| 662 |
+
# progress_bar.progress((step+ind_img+1)/nb_steps)
|
| 663 |
+
# out_status = 'OK'
|
| 664 |
+
# except Exception as e:
|
| 665 |
+
# out_status = e
|
| 666 |
+
# progress_bar.empty()
|
| 667 |
+
|
| 668 |
+
# return out_list_text_mmocr, out_list_confidence_mmocr, out_status
|
| 669 |
+
|
| 670 |
+
###
|
| 671 |
+
@st.cache_data
|
| 672 |
+
def tesserocr_recog(in_img, in_params, in_nb_images):
|
| 673 |
+
"""Recognition with Tesseract
|
| 674 |
+
Args:
|
| 675 |
+
in_image_cv (matrix) : original image
|
| 676 |
+
in_params (dict) : parameters for recognition
|
| 677 |
+
in_nb_images : nb cropped images (used for progress bar)
|
| 678 |
+
Returns:
|
| 679 |
+
Pandas data frame : recognition results
|
| 680 |
+
string/Exception : recognition status
|
| 681 |
+
"""
|
| 682 |
+
## ------- Tesseract Text recognition
|
| 683 |
+
step = 3*in_nb_images # fourth recognition process
|
| 684 |
+
#nb_steps = 4 * in_nb_images
|
| 685 |
+
nb_steps = 3 * in_nb_images
|
| 686 |
+
progress_bar = st.progress(step/nb_steps)
|
| 687 |
+
try:
|
| 688 |
+
out_df_result = pytesseract.image_to_data(in_img, **in_params,output_type=Output.DATAFRAME)
|
| 689 |
+
out_df_result['box'] = out_df_result.apply(lambda d: [[d['left'], d['top']], \
|
| 690 |
+
[d['left'] + d['width'], d['top']], \
|
| 691 |
+
[d['left']+d['width'], d['top']+d['height']], \
|
| 692 |
+
[d['left'], d['top'] + d['height']], \
|
| 693 |
+
], axis=1)
|
| 694 |
+
out_df_result['cropped'] = out_df_result['box'].apply(lambda b: cropped_1box(b, in_img))
|
| 695 |
+
out_df_result = out_df_result[(out_df_result.word_num > 0) & (out_df_result.text != ' ')] \
|
| 696 |
+
.reset_index(drop=True)
|
| 697 |
+
out_status = 'OK'
|
| 698 |
+
except Exception as e:
|
| 699 |
+
out_df_result = pd.DataFrame([])
|
| 700 |
+
out_status = e
|
| 701 |
+
progress_bar.progress(1.)
|
| 702 |
+
return out_df_result, out_status
|
| 703 |
+
###
|
| 704 |
+
def draw_reco_images(in_image, in_boxes_coordinates, in_list_texts, in_list_confid, \
|
| 705 |
+
in_dict_back_colors, in_df_results_tesseract, in_reader_type_list, \
|
| 706 |
+
in_font_scale=1, in_conf_threshold=65):
|
| 707 |
+
"""Draw recognized text on original image, for each OCR solution used
|
| 708 |
+
Args:
|
| 709 |
+
in_image (matrix) : original image
|
| 710 |
+
in_boxes_coordinates (list) : list of boxes coordinates
|
| 711 |
+
in_list_texts (list): list of recognized text for each recognizer (except Tesseract)
|
| 712 |
+
in_list_confid (list): list of recognition confidence for each recognizer (except Tesseract)
|
| 713 |
+
in_df_results_tesseract (Pandas data frame): Tesseract recognition results
|
| 714 |
+
in_font_scale (int, optional): text font scale. Defaults to 3.
|
| 715 |
+
Returns:
|
| 716 |
+
shows the results container
|
| 717 |
+
"""
|
| 718 |
+
img = in_image.copy()
|
| 719 |
+
nb_readers = len(in_reader_type_list)
|
| 720 |
+
list_reco_images = [img.copy() for i in range(nb_readers)]
|
| 721 |
+
for num, box_ in enumerate(in_boxes_coordinates):
|
| 722 |
+
box = np.array(box_).astype(np.int64)
|
| 723 |
+
# For each box : draw the results of each recognizer
|
| 724 |
+
for ind_r in range(nb_readers-1):
|
| 725 |
+
confid = np.round(in_list_confid[ind_r][num], 0)
|
| 726 |
+
rgb_color = ImageColor.getcolor(in_dict_back_colors[confid], "RGB")
|
| 727 |
+
if confid < in_conf_threshold:
|
| 728 |
+
text_color = (0, 0, 0)
|
| 729 |
+
else:
|
| 730 |
+
text_color = (255, 255, 255)
|
| 731 |
+
if in_font_scale < 1.:
|
| 732 |
+
thickness = 1
|
| 733 |
+
else:
|
| 734 |
+
thickness = 2
|
| 735 |
+
list_reco_images[ind_r] = cv2.rectangle(list_reco_images[ind_r], \
|
| 736 |
+
(box[0][0], box[0][1]), \
|
| 737 |
+
(box[2][0], box[2][1]), rgb_color, -1)
|
| 738 |
+
list_reco_images[ind_r] = cv2.putText(list_reco_images[ind_r], \
|
| 739 |
+
in_list_texts[ind_r][num], \
|
| 740 |
+
(box[0][0],int(np.round((box[0][1]+box[2][1])/2,0))), \
|
| 741 |
+
cv2.FONT_HERSHEY_DUPLEX, in_font_scale, text_color, thickness)
|
| 742 |
+
# Add Tesseract process
|
| 743 |
+
if not in_df_results_tesseract.empty:
|
| 744 |
+
ind_tessocr = nb_readers-1
|
| 745 |
+
for num, box_ in enumerate(in_df_results_tesseract['box'].to_list()):
|
| 746 |
+
box = np.array(box_).astype(np.int64)
|
| 747 |
+
confid = np.round(in_df_results_tesseract.iloc[num]['conf'], 0)
|
| 748 |
+
rgb_color = ImageColor.getcolor(in_dict_back_colors[confid], "RGB")
|
| 749 |
+
if confid < in_conf_threshold:
|
| 750 |
+
text_color = (0, 0, 0)
|
| 751 |
+
else:
|
| 752 |
+
text_color = (255, 255, 255)
|
| 753 |
+
list_reco_images[ind_tessocr] = \
|
| 754 |
+
cv2.rectangle(list_reco_images[ind_tessocr], (box[0][0], box[0][1]), \
|
| 755 |
+
(box[2][0], box[2][1]), rgb_color, -1)
|
| 756 |
+
try:
|
| 757 |
+
list_reco_images[ind_tessocr] = \
|
| 758 |
+
cv2.putText(list_reco_images[ind_tessocr], \
|
| 759 |
+
in_df_results_tesseract.iloc[num]['text'], \
|
| 760 |
+
(box[0][0],int(np.round((box[0][1]+box[2][1])/2,0))), \
|
| 761 |
+
cv2.FONT_HERSHEY_DUPLEX, in_font_scale, text_color, 2)
|
| 762 |
+
except:
|
| 763 |
+
pass
|
| 764 |
+
with show_reco.container():
|
| 765 |
+
# Draw the results, 2 images per line
|
| 766 |
+
reco_lines = math.ceil(len(in_reader_type_list) / 2)
|
| 767 |
+
column_width = 400
|
| 768 |
+
for ind_lig in range(0, reco_lines+1, 2):
|
| 769 |
+
cols = st.columns(2)
|
| 770 |
+
for ind_col in range(2):
|
| 771 |
+
ind = ind_lig + ind_col
|
| 772 |
+
if ind < len(in_reader_type_list):
|
| 773 |
+
if in_reader_type_list[ind] == 'Tesseract':
|
| 774 |
+
column_title = '<p style="font-size: 20px;color:rgb(228,26,28); \
|
| 775 |
+
">Recognition with ' + in_reader_type_list[ind] + \
|
| 776 |
+
'<sp style="font-size: 17px"> (with its own detector) \
|
| 777 |
+
</sp></p>'
|
| 778 |
+
else:
|
| 779 |
+
column_title = '<p style="font-size: 20px;color:rgb(228,26,28); \
|
| 780 |
+
">Recognition with ' + \
|
| 781 |
+
in_reader_type_list[ind]+ '</p>'
|
| 782 |
+
cols[ind_col].markdown(column_title, unsafe_allow_html=True)
|
| 783 |
+
if st.session_state.list_reco_status[ind] == 'OK':
|
| 784 |
+
cols[ind_col].image(list_reco_images[ind], \
|
| 785 |
+
width=column_width, use_container_width=True)
|
| 786 |
+
else:
|
| 787 |
+
cols[ind_col].write(list_reco_status[ind], \
|
| 788 |
+
use_container_width=True)
|
| 789 |
+
st.markdown(' 💡 Bad font size? you can adjust it below and refresh:')
|
| 790 |
+
###
|
| 791 |
+
def highlight():
|
| 792 |
+
""" Highlight choosen detector results
|
| 793 |
+
"""
|
| 794 |
+
with show_detect.container():
|
| 795 |
+
columns_size = [1 for x in reader_type_list]
|
| 796 |
+
column_width = [300 for x in reader_type_list]
|
| 797 |
+
columns_color = ["rgb(12, 5, 105)" for x in reader_type_list]
|
| 798 |
+
columns_size[reader_type_dict[st.session_state.detect_reader]] = 2
|
| 799 |
+
column_width[reader_type_dict[st.session_state.detect_reader]] = 400
|
| 800 |
+
columns_color[reader_type_dict[st.session_state.detect_reader]] = "rgb(228,26,28)"
|
| 801 |
+
columns = st.columns(columns_size, ) #gap='medium')
|
| 802 |
+
for ind_col, col in enumerate(columns):
|
| 803 |
+
column_title = '<p style="font-size: 20px;color:'+columns_color[ind_col] + \
|
| 804 |
+
';">Detection with ' + reader_type_list[ind_col]+ '</p>'
|
| 805 |
+
col.markdown(column_title, unsafe_allow_html=True)
|
| 806 |
+
if isinstance(list_images[ind_col+2], PIL.Image.Image):
|
| 807 |
+
col.image(list_images[ind_col+2], width=column_width[ind_col], \
|
| 808 |
+
use_container_width=True)
|
| 809 |
+
else:
|
| 810 |
+
col.write(list_images[ind_col+2], use_container_width=True)
|
| 811 |
+
st.session_state.columns_size = columns_size
|
| 812 |
+
st.session_state.column_width = column_width
|
| 813 |
+
st.session_state.columns_color = columns_color
|
| 814 |
+
###
|
| 815 |
+
@st.cache(show_spinner=False)
|
| 816 |
+
def get_demo():
|
| 817 |
+
"""Get the demo files
|
| 818 |
+
Returns:
|
| 819 |
+
PIL.Image : input file opened with Pillow
|
| 820 |
+
PIL.Image : input file opened with Pillow
|
| 821 |
+
"""
|
| 822 |
+
out_img_demo_1 = Image.open("img_demo_1.jpg")
|
| 823 |
+
out_img_demo_2 = Image.open("img_demo_2.jpg")
|
| 824 |
+
return out_img_demo_1, out_img_demo_2
|
| 825 |
+
###
|
| 826 |
+
def raz():
|
| 827 |
+
st.session_state.list_coordinates = []
|
| 828 |
+
st.session_state.list_images = []
|
| 829 |
+
st.session_state.detect_reader = reader_type_list[0]
|
| 830 |
+
st.session_state.columns_size = [2] + [1 for x in reader_type_list[1:]]
|
| 831 |
+
st.session_state.column_width = [400] + [300 for x in reader_type_list[1:]]
|
| 832 |
+
st.session_state.columns_color = ["rgb(228,26,28)"] + \
|
| 833 |
+
["rgb(79, 43, 255)" for x in reader_type_list[1:]]
|
| 834 |
+
# Clear caches
|
| 835 |
+
easyocr_detect.clear()
|
| 836 |
+
ppocr_detect.clear()
|
| 837 |
+
#mmocr_detect.clear()
|
| 838 |
+
tesserocr_detect.clear()
|
| 839 |
+
process_detect.clear()
|
| 840 |
+
get_cropped.clear()
|
| 841 |
+
easyocr_recog.clear()
|
| 842 |
+
ppocr_recog.clear()
|
| 843 |
+
#mmocr_recog.clear()
|
| 844 |
+
tesserocr_recog.clear()
|
| 845 |
+
###
|
| 846 |
+
###################################################################################################
|
| 847 |
+
## STREAMLIT APP
|
| 848 |
+
###################################################################################################
|
| 849 |
+
# ##----------- Initializations ---------------------------------------------------------------------
|
| 850 |
+
#print("PID : ", os.getpid())
|
| 851 |
+
print("ocr comparator")
|
| 852 |
+
st.set_option("client.showErrorDetails", False)
|
| 853 |
+
st.markdown("""
|
| 854 |
+
<style>
|
| 855 |
+
.block-container {
|
| 856 |
+
padding-top: 1rem;
|
| 857 |
+
padding-bottom: 1rem;
|
| 858 |
+
padding-left: 1rem;
|
| 859 |
+
padding-right: 2rem;
|
| 860 |
+
}
|
| 861 |
+
</style>
|
| 862 |
+
""", unsafe_allow_html=True)
|
| 863 |
+
st.title("OCR solutions comparator")
|
| 864 |
+
#st.markdown("##### *EasyOCR, PPOCR, Tesseract*")
|
| 865 |
+
st.markdown("##### *EasyOCR, PPOCR, MMOCR, Tesseract*")
|
| 866 |
+
#st.markdown("#### PID : " + str(os.getpid()))
|
| 867 |
+
# Initializations
|
| 868 |
+
with st.spinner("Initializations in progress ..."):
|
| 869 |
+
reader_type_list, reader_type_dict, list_dict_lang, \
|
| 870 |
+
cols_size, dict_back_colors, fig_colorscale = initializations()
|
| 871 |
+
img_demo_1, img_demo_2 = get_demo()
|
| 872 |
+
##----------- Choose language & image -------------------------------------------------------------
|
| 873 |
+
st.markdown("#### Choose languages for the text recognition:")
|
| 874 |
+
lang_col = st.columns(4)
|
| 875 |
+
easyocr_key_lang = lang_col[0].selectbox(reader_type_list[0]+" :", list_dict_lang[0].keys(), 26)
|
| 876 |
+
easyocr_lang = list_dict_lang[0][easyocr_key_lang]
|
| 877 |
+
ppocr_key_lang = lang_col[1].selectbox(reader_type_list[1]+" :", list_dict_lang[1].keys(), 22)
|
| 878 |
+
ppocr_lang = list_dict_lang[1][ppocr_key_lang]
|
| 879 |
+
#mmocr_key_lang = lang_col[2].selectbox(reader_type_list[2]+" :", list_dict_lang[2].keys(), 0)
|
| 880 |
+
#mmocr_lang = list_dict_lang[2][mmocr_key_lang]
|
| 881 |
+
#tesserocr_key_lang = lang_col[3].selectbox(reader_type_list[3]+" :", list_dict_lang[3].keys(), 35)
|
| 882 |
+
#tesserocr_lang = list_dict_lang[3][tesserocr_key_lang]
|
| 883 |
+
tesserocr_key_lang = lang_col[2].selectbox(reader_type_list[2]+" :", list_dict_lang[2].keys(), 35)
|
| 884 |
+
tesserocr_lang = list_dict_lang[2][tesserocr_key_lang]
|
| 885 |
+
st.markdown("#### Choose picture:")
|
| 886 |
+
cols_pict = st.columns([1, 2])
|
| 887 |
+
img_typ = cols_pict[0].radio("", ['Upload file', 'Take a picture', 'Use a demo file'], \
|
| 888 |
+
index=0, on_change=raz)
|
| 889 |
+
if img_typ == 'Upload file':
|
| 890 |
+
image_file = cols_pict[1].file_uploader("Upload a file:", type=["jpg","jpeg","png"], on_change=raz)
|
| 891 |
+
if img_typ == 'Take a picture':
|
| 892 |
+
image_file = cols_pict[1].camera_input("Take a picture:", on_change=raz)
|
| 893 |
+
if img_typ == 'Use a demo file':
|
| 894 |
+
with st.expander('Choose a demo file:', expanded=True):
|
| 895 |
+
demo_used = st.radio('', ['File 1', 'File 2'], index=0, \
|
| 896 |
+
horizontal=True, on_change=raz)
|
| 897 |
+
cols_demo = st.columns([1, 2])
|
| 898 |
+
cols_demo[0].markdown('###### File 1')
|
| 899 |
+
cols_demo[0].image(img_demo_1, width=150)
|
| 900 |
+
cols_demo[1].markdown('###### File 2')
|
| 901 |
+
cols_demo[1].image(img_demo_2, width=300)
|
| 902 |
+
if demo_used == 'File 1':
|
| 903 |
+
image_file = 'img_demo_1.jpg'
|
| 904 |
+
else:
|
| 905 |
+
image_file = 'img_demo_2.jpg'
|
| 906 |
+
##----------- Process input image -----------------------------------------------------------------
|
| 907 |
+
if image_file is not None:
|
| 908 |
+
try:
|
| 909 |
+
image_path, image_orig, image_cv2 = load_image(image_file)
|
| 910 |
+
list_images = [image_orig, image_cv2]
|
| 911 |
+
except Exception as e:
|
| 912 |
+
image_file = None
|
| 913 |
+
st.exception(e)
|
| 914 |
+
##----------- Form with original image & hyperparameters for detectors ----------------------------
|
| 915 |
+
with st.form("form1"):
|
| 916 |
+
col1, col2 = st.columns(2, ) #gap="medium")
|
| 917 |
+
col1.markdown("##### Original image")
|
| 918 |
+
col1.image(list_images[0], width=400)
|
| 919 |
+
col2.markdown("##### Hyperparameters values for detection")
|
| 920 |
+
with col2.expander("Choose detection hyperparameters for " + reader_type_list[0], \
|
| 921 |
+
expanded=False):
|
| 922 |
+
t0_min_size = st.slider("min_size", 1, 20, 10, step=1, \
|
| 923 |
+
help="min_size (int, default = 10) - Filter text box smaller than \
|
| 924 |
+
minimum value in pixel")
|
| 925 |
+
t0_text_threshold = st.slider("text_threshold", 0.1, 1., 0.7, step=0.1, \
|
| 926 |
+
help="text_threshold (float, default = 0.7) - Text confidence threshold")
|
| 927 |
+
t0_low_text = st.slider("low_text", 0.1, 1., 0.4, step=0.1, \
|
| 928 |
+
help="low_text (float, default = 0.4) - Text low-bound score")
|
| 929 |
+
t0_link_threshold = st.slider("link_threshold", 0.1, 1., 0.4, step=0.1, \
|
| 930 |
+
help="link_threshold (float, default = 0.4) - Link confidence threshold")
|
| 931 |
+
t0_canvas_size = st.slider("canvas_size", 2000, 5000, 2560, step=10, \
|
| 932 |
+
help='''canvas_size (int, default = 2560) \n
|
| 933 |
+
Maximum e size. Image bigger than this value will be resized down''')
|
| 934 |
+
t0_mag_ratio = st.slider("mag_ratio", 0.1, 5., 1., step=0.1, \
|
| 935 |
+
help="mag_ratio (float, default = 1) - Image magnification ratio")
|
| 936 |
+
t0_slope_ths = st.slider("slope_ths", 0.01, 1., 0.1, step=0.01, \
|
| 937 |
+
help='''slope_ths (float, default = 0.1) - Maximum slope \
|
| 938 |
+
(delta y/delta x) to considered merging. \n
|
| 939 |
+
Low valuans tiled boxes will not be merged.''')
|
| 940 |
+
t0_ycenter_ths = st.slider("ycenter_ths", 0.1, 1., 0.5, step=0.1, \
|
| 941 |
+
help='''ycenter_ths (float, default = 0.5) - Maximum shift in y direction. \n
|
| 942 |
+
Boxes wiifferent level should not be merged.''')
|
| 943 |
+
t0_height_ths = st.slider("height_ths", 0.1, 1., 0.5, step=0.1, \
|
| 944 |
+
help='''height_ths (float, default = 0.5) - Maximum different in box height. \n
|
| 945 |
+
Boxes wiery different text size should not be merged.''')
|
| 946 |
+
t0_width_ths = st.slider("width_ths", 0.1, 1., 0.5, step=0.1, \
|
| 947 |
+
help="width_ths (float, default = 0.5) - Maximum horizontal \
|
| 948 |
+
distance to merge boxes.")
|
| 949 |
+
t0_add_margin = st.slider("add_margin", 0.1, 1., 0.1, step=0.1, \
|
| 950 |
+
help='''add_margin (float, default = 0.1) - \
|
| 951 |
+
Extend bounding boxes in all direction by certain value. \n
|
| 952 |
+
This is rtant for language with complex script (E.g. Thai).''')
|
| 953 |
+
t0_optimal_num_chars = st.slider("optimal_num_chars", None, 100, None, step=10, \
|
| 954 |
+
help="optimal_num_chars (int, default = None) - If specified, bounding boxes \
|
| 955 |
+
with estimated number of characters near this value are returned first.")
|
| 956 |
+
with col2.expander("Choose detection hyperparameters for " + reader_type_list[1], \
|
| 957 |
+
expanded=False):
|
| 958 |
+
t1_det_algorithm = st.selectbox('det_algorithm', ['DB'], \
|
| 959 |
+
help='Type of detection algorithm selected. (default = DB)')
|
| 960 |
+
t1_det_max_side_len = st.slider('det_max_side_len', 500, 2000, 960, step=10, \
|
| 961 |
+
help='''The maximum size of the long side of the image. (default = 960)\n
|
| 962 |
+
Limit thximum image height and width.\n
|
| 963 |
+
When theg side exceeds this value, the long side will be resized to this size, and the short side \
|
| 964 |
+
will be ed proportionally.''')
|
| 965 |
+
t1_det_db_thresh = st.slider('det_db_thresh', 0.1, 1., 0.3, step=0.1, \
|
| 966 |
+
help='''Binarization threshold value of DB output map. (default = 0.3) \n
|
| 967 |
+
Used to er the binarized image of DB prediction, setting 0.-0.3 has no obvious effect on the result.''')
|
| 968 |
+
t1_det_db_box_thresh = st.slider('det_db_box_thresh', 0.1, 1., 0.6, step=0.1, \
|
| 969 |
+
help='''The threshold value of the DB output box. (default = 0.6) \n
|
| 970 |
+
DB post-essing filter box threshold, if there is a missing box detected, it can be reduced as appropriate. \n
|
| 971 |
+
Boxes sclower than this value will be discard.''')
|
| 972 |
+
t1_det_db_unclip_ratio = st.slider('det_db_unclip_ratio', 1., 3.0, 1.6, step=0.1, \
|
| 973 |
+
help='''The expanded ratio of DB output box. (default = 1.6) \n
|
| 974 |
+
Indicatee compactness of the text box, the smaller the value, the closer the text box to the text.''')
|
| 975 |
+
t1_det_east_score_thresh = st.slider('det_east_cover_thresh', 0.1, 1., 0.8, step=0.1, \
|
| 976 |
+
help="Binarization threshold value of EAST output map. (default = 0.8)")
|
| 977 |
+
t1_det_east_cover_thresh = st.slider('det_east_cover_thresh', 0.1, 1., 0.1, step=0.1, \
|
| 978 |
+
help='''The threshold value of the EAST output box. (default = 0.1) \n
|
| 979 |
+
Boxes sclower than this value will be discarded.''')
|
| 980 |
+
t1_det_east_nms_thresh = st.slider('det_east_nms_thresh', 0.1, 1., 0.2, step=0.1, \
|
| 981 |
+
help="The NMS threshold value of EAST model output box. (default = 0.2)")
|
| 982 |
+
t1_det_db_score_mode = st.selectbox('det_db_score_mode', ['fast', 'slow'], \
|
| 983 |
+
help='''slow: use polygon box to calculate bbox score, fast: use rectangle box \
|
| 984 |
+
to calculate. (default = fast) \n
|
| 985 |
+
Use rectlar box to calculate faster, and polygonal box more accurate for curved text area.''')
|
| 986 |
+
|
| 987 |
+
#with col2.expander("Choose detection hyperparameters for " + reader_type_list[2], \
|
| 988 |
+
# expanded=False):
|
| 989 |
+
# t2_det = st.selectbox('det', ['DB_r18','DB_r50','DBPP_r50','DRRG','FCE_IC15', \
|
| 990 |
+
# 'FCE_CTW_DCNv2','MaskRCNN_CTW','MaskRCNN_IC15', \
|
| 991 |
+
# 'MaskRCNN_IC17', 'PANet_CTW','PANet_IC15','PS_CTW',\
|
| 992 |
+
# 'PS_IC15','Tesseract','TextSnake'], 10, \
|
| 993 |
+
# help='Text detection algorithm. (default = PANet_IC15)')
|
| 994 |
+
# st.write("###### *More about text detection models* 👉 \
|
| 995 |
+
# [here](https://mmocr.readthedocs.io/en/latest/textdet_models.html)")
|
| 996 |
+
# t2_merge_xdist = st.slider('merge_xdist', 1, 50, 20, step=1, \
|
| 997 |
+
# help='The maximum x-axis distance to merge boxes. (defaut=20)')
|
| 998 |
+
|
| 999 |
+
#with col2.expander("Choose detection hyperparameters for " + reader_type_list[3], \
|
| 1000 |
+
with col2.expander("Choose detection hyperparameters for " + reader_type_list[2], \
|
| 1001 |
+
expanded=False):
|
| 1002 |
+
t3_psm = st.selectbox('Page segmentation mode (psm)', \
|
| 1003 |
+
[' - Default', \
|
| 1004 |
+
' 4 Assume a single column of text of variable sizes', \
|
| 1005 |
+
' 5 Assume a single uniform block of vertically aligned text', \
|
| 1006 |
+
' 6 Assume a single uniform block of text', \
|
| 1007 |
+
' 7 Treat the image as a single text line', \
|
| 1008 |
+
' 8 Treat the image as a single word', \
|
| 1009 |
+
' 9 Treat the image as a single word in a circle', \
|
| 1010 |
+
'10 Treat the image as a single character', \
|
| 1011 |
+
'11 Sparse text. Find as much text as possible in no \
|
| 1012 |
+
particular order', \
|
| 1013 |
+
'13 Raw line. Treat the image as a single text line, \
|
| 1014 |
+
bypassing hacks that are Tesseract-specific'])
|
| 1015 |
+
t3_oem = st.selectbox('OCR engine mode', ['0 Legacy engine only', \
|
| 1016 |
+
'1 Neural nets LSTM engine only', \
|
| 1017 |
+
'2 Legacy + LSTM engines', \
|
| 1018 |
+
'3 Default, based on what is available'], 3)
|
| 1019 |
+
t3_whitelist = st.text_input('Limit tesseract to recognize only this characters :', \
|
| 1020 |
+
placeholder='Limit tesseract to recognize only this characters', \
|
| 1021 |
+
help='Example for numbers only : 0123456789')
|
| 1022 |
+
color_hex = col2.color_picker('Set a color for box outlines:', '#004C99')
|
| 1023 |
+
color_part = color_hex.lstrip('#')
|
| 1024 |
+
color = tuple(int(color_part[i:i+2], 16) for i in (0, 2, 4))
|
| 1025 |
+
submit_detect = st.form_submit_button("Launch detection")
|
| 1026 |
+
##----------- Process text detection --------------------------------------------------------------
|
| 1027 |
+
if submit_detect:
|
| 1028 |
+
# Process text detection
|
| 1029 |
+
if t0_optimal_num_chars == 0:
|
| 1030 |
+
t0_optimal_num_chars = None
|
| 1031 |
+
# Construct the config Tesseract parameter
|
| 1032 |
+
t3_config = ''
|
| 1033 |
+
psm = t3_psm[:2]
|
| 1034 |
+
if psm != ' -':
|
| 1035 |
+
t3_config += '--psm ' + psm.strip()
|
| 1036 |
+
oem = t3_oem[:1]
|
| 1037 |
+
if oem != '3':
|
| 1038 |
+
t3_config += ' --oem ' + oem
|
| 1039 |
+
if t3_whitelist != '':
|
| 1040 |
+
t3_config += ' -c tessedit_char_whitelist=' + t3_whitelist
|
| 1041 |
+
list_params_det = \
|
| 1042 |
+
[[easyocr_lang, \
|
| 1043 |
+
{'min_size': t0_min_size, 'text_threshold': t0_text_threshold, \
|
| 1044 |
+
'low_text': t0_low_text, 'link_threshold': t0_link_threshold, \
|
| 1045 |
+
'canvas_size': t0_canvas_size, 'mag_ratio': t0_mag_ratio, \
|
| 1046 |
+
'slope_ths': t0_slope_ths, 'ycenter_ths': t0_ycenter_ths, \
|
| 1047 |
+
'height_ths': t0_height_ths, 'width_ths': t0_width_ths, \
|
| 1048 |
+
'add_margin': t0_add_margin, 'optimal_num_chars': t0_optimal_num_chars \
|
| 1049 |
+
}], \
|
| 1050 |
+
[ppocr_lang, \
|
| 1051 |
+
{'det_algorithm': t1_det_algorithm, 'det_max_side_len': t1_det_max_side_len, \
|
| 1052 |
+
'det_db_thresh': t1_det_db_thresh, 'det_db_box_thresh': t1_det_db_box_thresh, \
|
| 1053 |
+
'det_db_unclip_ratio': t1_det_db_unclip_ratio, \
|
| 1054 |
+
'det_east_score_thresh': t1_det_east_score_thresh, \
|
| 1055 |
+
'det_east_cover_thresh': t1_det_east_cover_thresh, \
|
| 1056 |
+
'det_east_nms_thresh': t1_det_east_nms_thresh, \
|
| 1057 |
+
'det_db_score_mode': t1_det_db_score_mode}],
|
| 1058 |
+
#[mmocr_lang, {'det': t2_det, 'merge_xdist': t2_merge_xdist}],
|
| 1059 |
+
[tesserocr_lang, {'lang': tesserocr_lang, 'config': t3_config}]
|
| 1060 |
+
]
|
| 1061 |
+
show_info1 = st.empty()
|
| 1062 |
+
show_info1.info("Readers initializations in progress (it may take a while) ...")
|
| 1063 |
+
list_readers = init_readers(list_params_det)
|
| 1064 |
+
show_info1.info("Text detection in progress ...")
|
| 1065 |
+
list_images, list_coordinates = process_detect(image_path, list_images, list_readers, \
|
| 1066 |
+
list_params_det, color)
|
| 1067 |
+
show_info1.empty()
|
| 1068 |
+
# Clear previous recognition results
|
| 1069 |
+
st.session_state.df_results = pd.DataFrame([])
|
| 1070 |
+
st.session_state.list_readers = list_readers
|
| 1071 |
+
st.session_state.list_coordinates = list_coordinates
|
| 1072 |
+
st.session_state.list_images = list_images
|
| 1073 |
+
st.session_state.list_params_det = list_params_det
|
| 1074 |
+
if 'columns_size' not in st.session_state:
|
| 1075 |
+
st.session_state.columns_size = [2] + [1 for x in reader_type_list[1:]]
|
| 1076 |
+
if 'column_width' not in st.session_state:
|
| 1077 |
+
st.session_state.column_width = [400] + [300 for x in reader_type_list[1:]]
|
| 1078 |
+
if 'columns_color' not in st.session_state:
|
| 1079 |
+
st.session_state.columns_color = ["rgb(228,26,28)"] + \
|
| 1080 |
+
["rgb(79, 43, 255)" for x in reader_type_list[1:]]
|
| 1081 |
+
if st.session_state.list_coordinates:
|
| 1082 |
+
list_coordinates = st.session_state.list_coordinates
|
| 1083 |
+
list_images = st.session_state.list_images
|
| 1084 |
+
list_readers = st.session_state.list_readers
|
| 1085 |
+
list_params_det = st.session_state.list_params_det
|
| 1086 |
+
##----------- Text detection results --------------------------------------------------------------
|
| 1087 |
+
st.subheader("Text detection")
|
| 1088 |
+
show_detect = st.empty()
|
| 1089 |
+
list_ok_detect = []
|
| 1090 |
+
with show_detect.container():
|
| 1091 |
+
columns = st.columns(st.session_state.columns_size, ) #gap='medium')
|
| 1092 |
+
for no_col, col in enumerate(columns):
|
| 1093 |
+
column_title = '<p style="font-size: 20px;color:' + \
|
| 1094 |
+
st.session_state.columns_color[no_col] + \
|
| 1095 |
+
';">Detection with ' + reader_type_list[no_col]+ '</p>'
|
| 1096 |
+
col.markdown(column_title, unsafe_allow_html=True)
|
| 1097 |
+
if isinstance(list_images[no_col+2], PIL.Image.Image):
|
| 1098 |
+
col.image(list_images[no_col+2], width=st.session_state.column_width[no_col], \
|
| 1099 |
+
use_container_width=True)
|
| 1100 |
+
list_ok_detect.append(reader_type_list[no_col])
|
| 1101 |
+
else:
|
| 1102 |
+
col.write(list_images[no_col+2], use_container_width=True)
|
| 1103 |
+
st.subheader("Text recognition")
|
| 1104 |
+
st.markdown("##### Using detection performed above by:")
|
| 1105 |
+
st.radio('Choose the detecter:', list_ok_detect, key='detect_reader', \
|
| 1106 |
+
horizontal=True, on_change=highlight)
|
| 1107 |
+
##----------- Form with hyperparameters for recognition -----------------------
|
| 1108 |
+
st.markdown("##### Hyperparameters values for recognition:")
|
| 1109 |
+
with st.form("form2"):
|
| 1110 |
+
with st.expander("Choose recognition hyperparameters for " + reader_type_list[0], \
|
| 1111 |
+
expanded=False):
|
| 1112 |
+
t0_decoder = st.selectbox('decoder', ['greedy', 'beamsearch', 'wordbeamsearch'], \
|
| 1113 |
+
help="decoder (string, default = 'greedy') - options are 'greedy', \
|
| 1114 |
+
'beamsearch' and 'wordbeamsearch.")
|
| 1115 |
+
t0_beamWidth = st.slider('beamWidth', 2, 20, 5, step=1, \
|
| 1116 |
+
help="beamWidth (int, default = 5) - How many beam to keep when decoder = \
|
| 1117 |
+
'beamsearch' or 'wordbeamsearch'.")
|
| 1118 |
+
t0_batch_size = st.slider('batch_size', 1, 10, 1, step=1, \
|
| 1119 |
+
help="batch_size (int, default = 1) - batch_size>1 will make EasyOCR faster \
|
| 1120 |
+
but use more memory.")
|
| 1121 |
+
t0_workers = st.slider('workers', 0, 10, 0, step=1, \
|
| 1122 |
+
help="workers (int, default = 0) - Number thread used in of dataloader.")
|
| 1123 |
+
t0_allowlist = st.text_input('allowlist', value="", max_chars=None, \
|
| 1124 |
+
placeholder='Force EasyOCR to recognize only this subset of characters', \
|
| 1125 |
+
help='''allowlist (string) - Force EasyOCR to recognize only subset of characters.\n
|
| 1126 |
+
Usefor specific problem (E.g. license plate, etc.)''')
|
| 1127 |
+
t0_blocklist = st.text_input('blocklist', value="", max_chars=None, \
|
| 1128 |
+
placeholder='Block subset of character (will be ignored if allowlist is given)', \
|
| 1129 |
+
help='''blocklist (string) - Block subset of character. This argument will be \
|
| 1130 |
+
ignored if allowlist is given.''')
|
| 1131 |
+
t0_detail = st.radio('detail', [0, 1], 1, horizontal=True, \
|
| 1132 |
+
help="detail (int, default = 1) - Set this to 0 for simple output")
|
| 1133 |
+
t0_paragraph = st.radio('paragraph', [True, False], 1, horizontal=True, \
|
| 1134 |
+
help='paragraph (bool, default = False) - Combine result into paragraph')
|
| 1135 |
+
t0_contrast_ths = st.slider('contrast_ths', 0.05, 1., 0.1, step=0.01, \
|
| 1136 |
+
help='''contrast_ths (float, default = 0.1) - Text box with contrast lower than \
|
| 1137 |
+
this value will be passed into model 2 times.\n
|
| 1138 |
+
Firs with original image and second with contrast adjusted to 'adjust_contrast' value.\n
|
| 1139 |
+
The with more confident level will be returned as a result.''')
|
| 1140 |
+
t0_adjust_contrast = st.slider('adjust_contrast', 0.1, 1., 0.5, step=0.1, \
|
| 1141 |
+
help = 'adjust_contrast (float, default = 0.5) - target contrast level for low \
|
| 1142 |
+
contrast text box')
|
| 1143 |
+
with st.expander("Choose recognition hyperparameters for " + reader_type_list[1], \
|
| 1144 |
+
expanded=False):
|
| 1145 |
+
t1_rec_algorithm = st.selectbox('rec_algorithm', ['CRNN', 'SVTR_LCNet'], 0, \
|
| 1146 |
+
help="Type of recognition algorithm selected. (default=CRNN)")
|
| 1147 |
+
t1_rec_batch_num = st.slider('rec_batch_num', 1, 50, step=1, \
|
| 1148 |
+
help="When performing recognition, the batchsize of forward images. \
|
| 1149 |
+
(default=30)")
|
| 1150 |
+
t1_max_text_length = st.slider('max_text_length', 3, 250, 25, step=1, \
|
| 1151 |
+
help="The maximum text length that the recognition algorithm can recognize. \
|
| 1152 |
+
(default=25)")
|
| 1153 |
+
t1_use_space_char = st.radio('use_space_char', [True, False], 0, horizontal=True, \
|
| 1154 |
+
help="Whether to recognize spaces. (default=TRUE)")
|
| 1155 |
+
t1_drop_score = st.slider('drop_score', 0., 1., 0.25, step=.05, \
|
| 1156 |
+
help="Filter the output by score (from the recognition model), and those \
|
| 1157 |
+
below this score will not be returned. (default=0.5)")
|
| 1158 |
+
|
| 1159 |
+
#with st.expander("Choose recognition hyperparameters for " + reader_type_list[2], \
|
| 1160 |
+
# expanded=False):
|
| 1161 |
+
# t2_recog = st.selectbox('recog', ['ABINet','CRNN','CRNN_TPS','MASTER', \
|
| 1162 |
+
# 'NRTR_1/16-1/8','NRTR_1/8-1/4','RobustScanner','SAR','SAR_CN', \
|
| 1163 |
+
# 'SATRN','SATRN_sm','SEG','Tesseract'], 7, \
|
| 1164 |
+
# help='Text recognition algorithm. (default = SAR)')
|
| 1165 |
+
# st.write("###### *More about text recognition models* 👉 \
|
| 1166 |
+
# [here](https://mmocr.readthedocs.io/en/latest/textrecog_models.html)")
|
| 1167 |
+
|
| 1168 |
+
#with st.expander("Choose recognition hyperparameters for " + reader_type_list[3], \
|
| 1169 |
+
with st.expander("Choose recognition hyperparameters for " + reader_type_list[2], \
|
| 1170 |
+
expanded=False):
|
| 1171 |
+
t3r_psm = st.selectbox('Page segmentation mode (psm)', \
|
| 1172 |
+
[' - Default', \
|
| 1173 |
+
' 4 Assume a single column of text of variable sizes', \
|
| 1174 |
+
' 5 Assume a single uniform block of vertically aligned \
|
| 1175 |
+
text', \
|
| 1176 |
+
' 6 Assume a single uniform block of text', \
|
| 1177 |
+
' 7 Treat the image as a single text line', \
|
| 1178 |
+
' 8 Treat the image as a single word', \
|
| 1179 |
+
' 9 Treat the image as a single word in a circle', \
|
| 1180 |
+
'10 Treat the image as a single character', \
|
| 1181 |
+
'11 Sparse text. Find as much text as possible in no \
|
| 1182 |
+
particular order', \
|
| 1183 |
+
'13 Raw line. Treat the image as a single text line, \
|
| 1184 |
+
bypassing hacks that are Tesseract-specific'])
|
| 1185 |
+
t3r_oem = st.selectbox('OCR engine mode', ['0 Legacy engine only', \
|
| 1186 |
+
'1 Neural nets LSTM engine only', \
|
| 1187 |
+
'2 Legacy + LSTM engines', \
|
| 1188 |
+
'3 Default, based on what is available'], 3)
|
| 1189 |
+
t3r_whitelist = st.text_input('Limit tesseract to recognize only this \
|
| 1190 |
+
characters :', \
|
| 1191 |
+
placeholder='Limit tesseract to recognize only this characters', \
|
| 1192 |
+
help='Example for numbers only : 0123456789')
|
| 1193 |
+
submit_reco = st.form_submit_button("Launch recognition")
|
| 1194 |
+
if submit_reco:
|
| 1195 |
+
process_detect.clear()
|
| 1196 |
+
##----------- Process recognition ------------------------------------------
|
| 1197 |
+
reader_ind = reader_type_dict[st.session_state.detect_reader]
|
| 1198 |
+
list_boxes = list_coordinates[reader_ind]
|
| 1199 |
+
# Construct the config Tesseract parameter
|
| 1200 |
+
t3r_config = ''
|
| 1201 |
+
psm = t3r_psm[:2]
|
| 1202 |
+
if psm != ' -':
|
| 1203 |
+
t3r_config += '--psm ' + psm.strip()
|
| 1204 |
+
oem = t3r_oem[:1]
|
| 1205 |
+
if oem != '3':
|
| 1206 |
+
t3r_config += ' --oem ' + oem
|
| 1207 |
+
if t3r_whitelist != '':
|
| 1208 |
+
t3r_config += ' -c tessedit_char_whitelist=' + t3r_whitelist
|
| 1209 |
+
list_params_rec = \
|
| 1210 |
+
[{'decoder': t0_decoder, 'beamWidth': t0_beamWidth, \
|
| 1211 |
+
'batch_size': t0_batch_size, 'workers': t0_workers, \
|
| 1212 |
+
'allowlist': t0_allowlist, 'blocklist': t0_blocklist, \
|
| 1213 |
+
'detail': t0_detail, 'paragraph': t0_paragraph, \
|
| 1214 |
+
'contrast_ths': t0_contrast_ths, 'adjust_contrast': t0_adjust_contrast
|
| 1215 |
+
},
|
| 1216 |
+
{ **list_params_det[1][1], **{'rec_algorithm': t1_rec_algorithm, \
|
| 1217 |
+
'rec_batch_num': t1_rec_batch_num, 'max_text_length': t1_max_text_length, \
|
| 1218 |
+
'use_space_char': t1_use_space_char, 'drop_score': t1_drop_score}, \
|
| 1219 |
+
**{'lang': list_params_det[1][0]}
|
| 1220 |
+
},
|
| 1221 |
+
#{'recog': t2_recog},
|
| 1222 |
+
{'lang': tesserocr_lang, 'config': t3r_config}
|
| 1223 |
+
]
|
| 1224 |
+
show_info2 = st.empty()
|
| 1225 |
+
with show_info2.container():
|
| 1226 |
+
st.info("Text recognition in progress ...")
|
| 1227 |
+
df_results, df_results_tesseract, list_reco_status = \
|
| 1228 |
+
process_recog(list_readers, list_images[1], list_boxes, list_params_rec)
|
| 1229 |
+
show_info2.empty()
|
| 1230 |
+
st.session_state.df_results = df_results
|
| 1231 |
+
st.session_state.list_boxes = list_boxes
|
| 1232 |
+
st.session_state.df_results_tesseract = df_results_tesseract
|
| 1233 |
+
st.session_state.list_reco_status = list_reco_status
|
| 1234 |
+
if 'df_results' in st.session_state:
|
| 1235 |
+
if not st.session_state.df_results.empty:
|
| 1236 |
+
##----------- Show recognition results ------------------------------------------------------------
|
| 1237 |
+
results_cols = st.session_state.df_results.columns
|
| 1238 |
+
list_col_text = np.arange(1, len(cols_size), 2)
|
| 1239 |
+
list_col_confid = np.arange(2, len(cols_size), 2)
|
| 1240 |
+
dict_draw_reco = {'in_image': st.session_state.list_images[1], \
|
| 1241 |
+
'in_boxes_coordinates': st.session_state.list_boxes, \
|
| 1242 |
+
'in_list_texts': [st.session_state.df_results[x].to_list() \
|
| 1243 |
+
for x in results_cols[list_col_text]], \
|
| 1244 |
+
'in_list_confid': [st.session_state.df_results[x].to_list() \
|
| 1245 |
+
for x in results_cols[list_col_confid]], \
|
| 1246 |
+
'in_dict_back_colors': dict_back_colors, \
|
| 1247 |
+
'in_df_results_tesseract' : st.session_state.df_results_tesseract, \
|
| 1248 |
+
'in_reader_type_list': reader_type_list
|
| 1249 |
+
}
|
| 1250 |
+
show_reco = st.empty()
|
| 1251 |
+
with st.form("form3"):
|
| 1252 |
+
st.plotly_chart(fig_colorscale, use_container_width=True)
|
| 1253 |
+
col_font, col_threshold = st.columns(2)
|
| 1254 |
+
col_font.slider('Font scale', 0.1, 7., 1., step=0.1, key="font_scale_sld")
|
| 1255 |
+
col_threshold.slider('% confidence threshold for text color change', 40, 100, 64, \
|
| 1256 |
+
step=1, key="conf_threshold_sld")
|
| 1257 |
+
col_threshold.write("(text color is black below this % confidence threshold, \
|
| 1258 |
+
and white above)")
|
| 1259 |
+
draw_reco_images(**dict_draw_reco)
|
| 1260 |
+
submit_resize = st.form_submit_button("Refresh")
|
| 1261 |
+
if submit_resize:
|
| 1262 |
+
draw_reco_images(**dict_draw_reco, \
|
| 1263 |
+
in_font_scale=st.session_state.font_scale_sld, \
|
| 1264 |
+
in_conf_threshold=st.session_state.conf_threshold_sld)
|
| 1265 |
+
st.subheader("Recognition details")
|
| 1266 |
+
#with st.expander("Detailed areas for EasyOCR, PPOCR, MMOCR", expanded=True):
|
| 1267 |
+
with st.expander("Detailed areas for EasyOCR, PPOCR", expanded=True):
|
| 1268 |
+
cols = st.columns(cols_size)
|
| 1269 |
+
cols[0].markdown('#### Detected area')
|
| 1270 |
+
for i in range(1, (len(reader_type_list)-1)*2, 2):
|
| 1271 |
+
cols[i].markdown('#### with ' + reader_type_list[i//2])
|
| 1272 |
+
for row in st.session_state.df_results.itertuples():
|
| 1273 |
+
#cols = st.columns(1 + len(reader_type_list)*2)
|
| 1274 |
+
cols = st.columns(cols_size)
|
| 1275 |
+
cols[0].image(row.cropped_image, width=150)
|
| 1276 |
+
for ind_col in range(1, len(cols), 2):
|
| 1277 |
+
cols[ind_col].write(getattr(row, results_cols[ind_col]))
|
| 1278 |
+
cols[ind_col+1].write("("+str( \
|
| 1279 |
+
getattr(row, results_cols[ind_col+1]))+"%)")
|
| 1280 |
+
st.download_button(
|
| 1281 |
+
label="Download results as CSV file",
|
| 1282 |
+
data=convert_df(st.session_state.df_results),
|
| 1283 |
+
file_name='OCR_comparator_results.csv',
|
| 1284 |
+
mime='text/csv',
|
| 1285 |
+
)
|
| 1286 |
+
if not st.session_state.df_results_tesseract.empty:
|
| 1287 |
+
with st.expander("Detailed areas for Tesseract", expanded=False):
|
| 1288 |
+
cols = st.columns([2,2,1])
|
| 1289 |
+
cols[0].markdown('#### Detected area')
|
| 1290 |
+
cols[1].markdown('#### with Tesseract')
|
| 1291 |
+
for row in st.session_state.df_results_tesseract.itertuples():
|
| 1292 |
+
cols = st.columns([2,2,1])
|
| 1293 |
+
cols[0].image(row.cropped, width=150)
|
| 1294 |
+
cols[1].write(getattr(row, 'text'))
|
| 1295 |
+
cols[2].write("("+str(getattr(row, 'conf'))+"%)")
|
| 1296 |
+
st.download_button(
|
| 1297 |
+
label="Download Tesseract results as CSV file",
|
| 1298 |
+
data=convert_df(st.session_state.df_results),
|
| 1299 |
+
file_name='OCR_comparator_Tesseract_results.csv',
|
| 1300 |
+
mime='text/csv',
|
| 1301 |
+
)
|
requirements.txt
CHANGED
|
@@ -1,22 +1,21 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
openmim
|
|
|
|
| 1 |
+
easyocr==1.7.1
|
| 2 |
+
streamlit==1.43.0
|
| 3 |
+
opencv-python-headless==4.9.0.80
|
| 4 |
+
torch==2.4.0
|
| 5 |
+
torchvision==0.19.0
|
| 6 |
+
Pillow
|
| 7 |
+
#mmcv-full --no-binary mmcv-full
|
| 8 |
+
#mmcv
|
| 9 |
+
#mmdet #==2.28.2
|
| 10 |
+
#mmengine
|
| 11 |
+
#mmocr #==0.6.3
|
| 12 |
+
paddleocr==2.8.0
|
| 13 |
+
paddlepaddle==2.6.0
|
| 14 |
+
numpy #==1.23.4
|
| 15 |
+
mycolorpy==1.5.1
|
| 16 |
+
plotly-express==0.4.1
|
| 17 |
+
altair==4.0
|
| 18 |
+
pytesseract==0.3.10
|
| 19 |
+
streamlit_option_menu
|
| 20 |
+
#openmim
|
| 21 |
+
imutils
|
|
|