<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bibek Thapa on Medium]]></title>
        <description><![CDATA[Stories by Bibek Thapa on Medium]]></description>
        <link>https://medium.com/@bibekthapa.works?source=rss-6aa952a3b67e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IHdymVqIz2eHoGdI</url>
            <title>Stories by Bibek Thapa on Medium</title>
            <link>https://medium.com/@bibekthapa.works?source=rss-6aa952a3b67e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:01:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bibekthapa.works/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create Your Own Nepali Poem-Generation Model]]></title>
            <link>https://ai.plainenglish.io/create-your-own-nepali-poem-generation-model-1575e56eb690?source=rss-6aa952a3b67e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1575e56eb690</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-model]]></category>
            <dc:creator><![CDATA[Bibek Thapa]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 12:07:44 GMT</pubDate>
            <atom:updated>2024-01-29T06:42:20.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9Ckxnmri3cy6ZyBwANOZg.png" /></figure><p>This is a short article on how to create your very own Nepali-Poem Generation model. I have followed various approaches to achieve this very task, but I wont be dealing with them all. This particular approach follows this <a href="https://www.kaggle.com/code/changyeop/how-to-fine-tune-gpt-2-for-beginners">Kaggle notebook</a>. Here, I will finetuning on <a href="https://huggingface.co/Sakonii/distilgpt2-nepali"><strong>Sakonii/distilgpt2-nepali</strong></a> model. However, if you are interested on other approaches you can check by GitHub repo on <a href="https://github.com/HordesOfGhost/Nepali_Poem_Generator"><strong>Nepali_Poem_Generator</strong></a>.</p><p><a href="https://github.com/de-sawal/Poem-Generator/blob/master/lspd.txt"><strong>Laxmi Prasad Devkota Poem</strong></a> is the dataset used for this article. The dataset consists of 4,091 lines, 119,161 characters and 8,580 unique characters. Obviously, you can use any other nepali poem-datasets or collection of nepali poems. If you write nepali poems and have them documented digitally, you could try on them. But make sure your poem is large.</p><p>As mentioned earlier, we will be finetuning on Sakonii/distilgpt2-nepali model. The model is pre-trained on <a href="https://huggingface.co/datasets/Sakonii/nepalitext-language-model-dataset">nepali text</a> dataset consisting of over 13 million Nepali text sequences using a Causal language modeling (CLM) objective. You can learn more about the model on huggingface.</p><p>Lets get straight into it.</p><p>You should choose a GPU runtime in Google Colab as the model is resource heavy to fine tune on. If you have a good hardware you could train locally. I opted to train the model on Google Colab.</p><h3>Import Libraries and Dataset</h3><p>Upload your dataset in Colab runtime. Import the following libraries and your dataset file. (You might encounter error to install library <strong>datasets</strong>. If you do, just run <strong>!pip install datasets </strong>on a different cell.)</p><pre># Import libraries<br><br>from datasets import load_dataset<br>from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer<br>from transformers import TextDataset, DataCollatorForLanguageModeling<br>import math<br><br># Read poem file<br><br>poem_file = open(&#39;/content/poem.txt&#39;,&#39;r&#39;)<br>poem = poem_file.read()<br><br># Visualize<br>poem_corpus = poem.split(&quot;\n&quot;)<br>print(poem_corpus[:5])<br><br># Output<br>[&#39;नछाडी जानोस् हे मेरा प्राण ! अकेली मलाई,&#39;, &#39;मनको वनमा ननिभ्ने गरी विरह जलाई !&#39;, &#39;ननिभ्ने गरी विरह जलाई,&#39;, &#39;लोचनका तारा ! हे मेर प्यारा ! यो जोति  बिलाए !&#39;, &#39;के भनूँ? भन्ने म केही थिइन  विष नै पिलाए !&#39;]</pre><h3>Preprocess</h3><p>I assume you have pre-cleaned dataset. If you scraped poem then you probably need to preprocess. If its collection of your own poems you probably won’t need it. However, I did a preprocessing, that could be completely unnecessary.</p><pre># Preprocessing function<br><br>def remove_noise(sentences):<br>    noises = [&#39;\n&#39;,&#39;\ufeff&#39;,&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;०&#39;,&#39;१&#39;,&#39;२&#39;,&#39;३&#39;,&#39;४&#39;,&#39;५&#39;,&#39;६&#39;,&#39;७&#39;,&#39;८&#39;,&#39;९&#39;,&#39;१०&#39;,&#39;\u200d&#39;]<br>    processed_sentences = []<br>    for sentence in sentences:<br>        for noise in noises:<br>            sentence = sentence.replace(noise,&#39;&#39;)<br>        processed_sentences.append(sentence)<br><br>    return processed_sentences</pre><p>After preprocessing, the processed poem sentences are saved in a text file. This done to ease data loading process later on for training LLM.</p><pre>with open(&#39;processed_poem.txt&#39;,&#39;w&#39;) as f:<br>  for line in processed_poem_corpus:<br>    f.write(line + &#39;\n&#39;)</pre><h3>Define Function to Load Dataset to train for a LLM</h3><p>Now, we create two functions: load_dataset and load_data_collator.</p><p>The function load_dataset is defined to help load text data for training a language model. Here, file_path is the path to desired text dataset. In our case the file_path is “processed_poem.txt”, as saved earlier. Tokenizer is the same tokenizer used by model <a href="https://huggingface.co/Sakonii/distilgpt2-nepali">Sakonii/distilgpt2-nepali</a>. The model opted for a Sentence Piece Model(SPM) for text tokenization. More on SPM <a href="https://medium.com/codex/sentencepiece-a-simple-and-language-independent-subword-tokenizer-and-detokenizer-for-neural-text-ffda431e704e">here</a>. Finally, block_size defines maximum length of a sequence of tokens. The default is 128 here.</p><p>TextDataset is a part of Hugging Face Transformers library. Its object is initialized with dataset file path, tokenizer, and block size. Essentially, it prepares the textual data for further use in training a language model.</p><pre>def load_dataset(file_path, tokenizer, block_size = 128):<br>    dataset = TextDataset(<br>        tokenizer = tokenizer,<br>        file_path = file_path,<br>        block_size = block_size,<br>    )<br>    return dataset</pre><p>The load_data_collator function is defined to prepare data for language model training, specifically for masked language modeling (MLM). Here, tokenizer takes a tokenizer as input, which is used to tokenize the data. The tokenizer is the same i.e. SPM. The parameter mlm is a boolean flag indicating whether the model is a masked language model. If True the model expects masked input tokens.</p><p>DataCollatorForLanguageModeling is a part of Hugging Face Transformers library. Here, it’s object is initialized with provided tokenizer and mlm flag. It is a tool that helps organize data for training and decides if model requires masked tokens during training.</p><pre>def load_data_collator(tokenizer, mlm = False):<br>    data_collator = DataCollatorForLanguageModeling(<br>        tokenizer=tokenizer,<br>        mlm=mlm,<br>    )<br>    return data_collator</pre><h3>Define Function to Train</h3><p>We move to defining train function to finetune the model.</p><p>Firstly, let us define the needed parameter that we need to pass to the function train.</p><p>The train_file_path and model name have been discussed before. Let’s discuss about other parameters. The parameter output_dir is where you save the model during and after training. To choose if the training files are to be overwrited or not during training overwrite_output_dir flag is set. The per_device_train_batch_size defines number of training samples processsed at once in each iteration. Here, the batch_size is 8 because of low GPU memory availability. You can increase its size for faster training, provided you have enough resources. Finally, the num_train_epochs is set as 250 signifying number of epochs to train. I have set 250 epochs as a safe zone. Finally, the save_steps signifies number of steps to be taken before saving the weights of training model. Here, We save every 500 steps.</p><pre># you need to set parameters<br>train_file_path = &quot;/content/processed_poem.txt&quot;<br>model_name = &#39;Sakonii/distilgpt2-nepali&#39;<br>output_dir = &#39;/content/&#39;<br>overwrite_output_dir = False<br>per_device_train_batch_size = 8<br>num_train_epochs = 250<br>save_steps = 500</pre><p>Now, Lets talk about the function train. The function takes all the parameter that was discussed above.</p><p>Most of the things have already been covered. In addition the train function loads the desired model “Sakonii/distilgpt2-nepali”. After, loading the pretrained model the function saves the model to fine tune on. It also saves the tokenizer ( later useful for inferencing).</p><p>The TrainingArguments holds the various training parameters and configuration which is later passed to class Trainer. Both are class provided by Hugging Face.</p><p>Finally, The Trainer class gets model, training arguments and dataset. It is now ready to train. The function .train() is called to start training or finetuning the pretrained model with our new poem dataset.</p><pre>def train(train_file_path,model_name,<br>          output_dir,<br>          overwrite_output_dir,<br>          per_device_train_batch_size,<br>          num_train_epochs,<br>          save_steps):<br>  tokenizer = AutoTokenizer.from_pretrained(model_name)<br>  train_dataset = load_dataset(train_file_path, tokenizer)<br>  data_collator = load_data_collator(tokenizer)<br><br>  tokenizer.save_pretrained(output_dir)<br>  <br>  ### Loads model for finetuning<br>  model = AutoModelForCausalLM.from_pretrained(model_name)<br><br>  model.save_pretrained(output_dir)<br><br>  training_args = TrainingArguments(<br>          output_dir=output_dir,<br>          overwrite_output_dir=overwrite_output_dir,<br>          per_device_train_batch_size=per_device_train_batch_size,<br>          num_train_epochs=num_train_epochs,<br>      )<br><br>  trainer = Trainer(<br>          model=model,<br>          args=training_args,<br>          data_collator=data_collator,<br>          train_dataset=train_dataset,<br>  )<br><br>  trainer.train()<br>  trainer.save_model()</pre><p>Now that everything is set, call the function train to commence training. (You may encounter a error regarding a library accelerate. Here, run the command <strong>!pip install accelerate -U </strong>in a different cell to update the library and restart the notebook’s session.)</p><pre>train(<br>    train_file_path=train_file_path,<br>    model_name=model_name,<br>    output_dir=output_dir,<br>    overwrite_output_dir=overwrite_output_dir,<br>    per_device_train_batch_size=per_device_train_batch_size,<br>    num_train_epochs=num_train_epochs,<br>    save_steps=save_steps<br>)</pre><h3>Be Patient</h3><p>Be patient, the training takes some time. If you don’t have a Colab Pro Subscription the Colab’s session disk storage might fill up faster than your model gets trained. If the allotted disk size is exceeded the session may be terminated.</p><p>But, there is a way around this. During training the weights are saved every 500 steps. The saved checkpoints are saved as folder “checkpoint-500” for checkpoint after 500 steps. Here, the files, model.safetensors (312M)and optimizer.pt(625M), accumulate the most disk size. You just need to delete them.</p><p>If the model is on step 2500 as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNryzfa6sVRE4dhW0peEog.jpeg" /><figcaption>Model training at step 2500</figcaption></figure><p>Now, You can delete the model.safetensors and optimizer.pt from steps 1500 to 2500. Make sure not to delete the 2000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Y-m44BJEHYttodRtpyC18g.jpeg" /><figcaption>Delete the files model.safetensors and optimzer.pt</figcaption></figure><p>Continue this until the training reaches its end. Don’t delete the files from last training step as that is the model to be used for inference. The files for inference should look like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*R3ywpcTY2tdt_y8GIlshvg.jpeg" /><figcaption>Inference Files</figcaption></figure><h3>Inference</h3><p>We are at the end. After all this hassle we deserve a treat. How about a generative model that generates a poem for you? Sounds good to me. The dataset we used was itself small. So our model may not be up to par. But hey we can always collect more, scrape more or write more :).</p><p>We have three function for inference. The load_model loads the trained model and load_tokenizer loads the tokenizer we previously saved. They are used for inference. The generate_text function takes in input text and max number of tokens to be generated.</p><p>Simply, call the function generate_poem to generate your very own nepali poem. Here you need to pass some initial tokens/words and number of tokens/words you want to generate.</p><pre>def load_model(model_path):<br>    model = AutoModelForCausalLM.from_pretrained(model_path)<br>    return model<br><br><br>def load_tokenizer(tokenizer_path):<br>    tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)<br>    return tokenizer<br><br><br>def generate_poem(sequence, max_length):<br>    model_path = &quot;/content/&quot;<br>    model = load_model(model_path)<br>    tokenizer = load_tokenizer(model_path)<br>    ids = tokenizer.encode(f&#39;{sequence}&#39;, return_tensors=&#39;pt&#39;)<br>    final_outputs = model.generate(<br>        ids,<br>        do_sample=True,<br>        max_length=max_length,<br>        pad_token_id=model.config.eos_token_id,<br>        top_k=50,<br>        top_p=0.95,<br>    )<br>    print(tokenizer.decode(final_outputs[0], skip_special_tokens=True))<br><br>sequence = input()<br>max_len = int(input())<br>generate_poem(sequence, max_len)</pre><p>Here is a example of inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqCXD-f_tcnDX5J8-3iWQA.jpeg" /><figcaption>Inference Example</figcaption></figure><p>The generated lines seems meaningful and poetic to me. What do you think? Give it a try yourself.</p><h3><strong>You can connect me here:</strong></h3><p><a href="https://github.com/HordesOfGhost">Github</a></p><p><a href="https://www.linkedin.com/in/bibek-thapa-sb1129/">Linkedin</a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1575e56eb690" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/create-your-own-nepali-poem-generation-model-1575e56eb690">Create Your Own Nepali Poem-Generation Model</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract Texts from Rotated(Skewed) Text-Images using CRAFT, OpenCV and pytesseract]]></title>
            <link>https://ai.plainenglish.io/how-to-extract-texts-from-rotated-skewed-text-images-using-craft-opencv-and-pytesseract-9c8c3fb8ef9d?source=rss-6aa952a3b67e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c8c3fb8ef9d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[ocr-tesseract]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[pytesseract]]></category>
            <dc:creator><![CDATA[Bibek Thapa]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 11:01:41 GMT</pubDate>
            <atom:updated>2023-10-26T01:17:11.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-C4kqfv5lyOcaEn_DRmdA.png" /></figure><p>I as an AI engineer was tasked with creating a Module that would extract texts from billboards on 360° images. I was able to build a billboard detection model with YOLO v8. I was hoping to use pytesseract with a Text Detection Model on top of detected billboards. The Text Detection Model I chose was CRAFT. As the images were 360° real world images most of the detected billboards had skewed text images or rotated text images. This made it difficult to extract texts accurately with pytesseract. You could also be facing the same problem when tasked with text extractor from real world objects.</p><p>I surfed over the internet for solutions. There were many solutions using OpenCV. But they would work for one image and wouldn’t work on another. Finally, I figured out a way that works for almost all cases. The method uses CRAFT for text detection and OpenCV for angle retrieval and to manipulate the image. Here manipulating image simply means to rotate the image. This blog illustrates a workflow to extract texts accurately from a rotated(skewed) text images.</p><p>We will be using following six images to show and solve our problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pI4yH-vDhRaaWrFWe5Yqyg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xXEHZpLlNQAxm-aTmzYJhA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XDXEesXfnV9T0SvpOtEVqQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Pfa8s5tt0OQDaNLiKGff-Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SBMpWVjdtYAwwIh0iJV2dQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ctIT6Jsa0ZSeiGOjQfgGrA.jpeg" /><figcaption>Test Images</figcaption></figure><h4>Prerequisites</h4><p>Before we get started, let’s make sure we have all the necessary libraries in place. Here’s a list of prerequisites, along with links for easy installation:</p><p>1 . <a href="https://www.python.org/downloads/">Python </a>(Preferably Version 3.8)</p><p>2 . <a href="https://pypi.org/project/numpy/">Numpy</a></p><p>3. <a href="https://pypi.org/project/opencv-python/">OpenCV</a></p><p>4. <a href="https://pypi.org/project/craft-text-detector/">CRAFT</a></p><p>5. <a href="https://pypi.org/project/pytesseract/">pytesseract</a></p><p>6. <a href="https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html">CUDA </a>(optional)</p><h4>Import Libraries and Load Models</h4><p>Import installed Libraries</p><pre>import numpy as np<br>import cv2<br>import pytesseract<br>from craft_text_detector import Craft</pre><p>Load CRAFT and pytesseract models. CRAFT is used for text detection and pytesseract is used for text extraction.</p><pre># set cuda = True if you set up CUDA in your system<br># go through https://github.com/clovaai/CRAFT-pytorch for more information on CRAFT <br><br>craft_detector = Craft( crop_type=&quot;poly&quot; , cuda = True, text_threshold=0.8, link_threshold=0.4, low_text=0.25)</pre><pre># set following paths on how you have installed pytesseract<br># Custom config for pytesseract here is <br># --oem 3 uses OCR engine based on what is avialable<br># --psm 7 treats the image as a single text line<br><br>pytesseract.pytesseract.tesseract_cmd = r&#39;C://ProgramFiles//Tesseract-OCR//tesseract.exe&#39;<br>os.environ[&quot;TESSDATA_PREFIX&quot;] =  &quot;C://Program Files//Tesseract-OCR//tessdata&quot;<br>custom_config = r&#39;-c preserve_interword_spaces=5 --oem 3 --psm 11&#39;</pre><h4>Text Extraction On Rotated(Skewed) Text-Images</h4><p>Lets see what problems we face while extracting text from rotated text-images. Here the general workflow is :</p><ol><li>Detect text using CRAFT and return text’s Region Of Interests (ROIs).</li></ol><pre>def detect_text_rois(image):<br>    <br>    # Create a copy of image<br>    img = image.copy()<br>     <br>    # get ROIs for text using CRAFT <br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # Ensure at least 3 points for a polygon<br>                # Convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # Calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # Get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br><br>                # Draw rectangle box around texts<br>                cv2.drawContours(img, [box_vertices], 0, (255, 0, 0), 2)<br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7Q9luZ64-h1wUkIxof7xtw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pZUpZqvVPA4wB0Bwtot_Cw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XlD6DriHZtI7cq2Fehuaow.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1VvVN1gSTskux-5s1PEaaw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ok2AnPtuDBhXO1QhiF6_Jw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qOl_nZ6J3UhpIlF7fylW-w.jpeg" /><figcaption>Bounding Box for angled ROIs of text</figcaption></figure><p>2. Use pytesseract to extract text from the angled ROIs.</p><pre>def detect_text_rois_and_extract_text(image):<br>    <br>    # create a copy of image<br>    img = image.copy()<br>    img_text = img.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # Ensure at least 3 points for a polygon<br>            # convert box points to numpy array for easier manipulation<br>            box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>            # calculate the minimum bounding rectangle<br>            rotated_rect = cv2.minAreaRect(box_points)<br>            <br>            # get vertices of box <br>            box_vertices = cv2.boxPoints(rotated_rect)<br>            box_vertices = np.int0(box_vertices)<br><br>            # append box_vertices on angled_rois list<br>            angled_rois.append(box_vertices)<br>            # draw rectangle box   <br>            cv2.drawContours(img_text, [box_vertices], 0, (255, 0, 0), 2)<br>    <br>    for index,roi in enumerate(angled_rois):<br>        # get the bounding box from the angled ROI<br>        x, y, w, h = cv2.boundingRect(roi)<br>        <br>        # get text using pytesseract<br>        text_roi = img[y : y+h, x : x+w]<br><br>        # little Preprocessing<br>        roi_gray = cv2.cvtColor(text_roi, cv2.COLOR_BGR2GRAY)<br>        <br>        # get lines of text from pytesseract <br>        text_line =f&#39;Line {index + 1} : &#39; +  pytesseract.image_to_string(roi_gray, lang=&#39;eng&#39;, config=custom_config)<br>        <br>        # Put text on image<br>        cv2.putText(img_text, text_line.strip(&#39;\n&#39;), (0, 30 + (index) * 40 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)<br>        <br>    <br>    return img_text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*IFzjhfCg2-pHrVrK2bDFFw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*UlD7udu-J9-o5I-y2tSwEQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*M3NOgqmrwYL-zNlRuTvkQA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*kqwI5rFWJFYuhg-ThOLbmQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Mu5qcJvbFKtI34kLHNNINg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-r-wkMg811FUTA8vmwdLlg.jpeg" /><figcaption>Text Extracted from Skewed Text-Image</figcaption></figure><p>We can see from above illustrations, pytesseract works well for straight text images. It tries its best for rotated(skewed) texts too but it is not that reliable. So, to extract texts from this rotated(skewed) text images we first need to straighten(deskew) them.</p><h4>General Workflow of Straighten(Deskew) Text-Images</h4><p>Now we will discuss about the general workflow to straighten the text images. For now we will discuss the concept on how the workflow works. Complete and readable code will be given at the end.</p><ol><li>Find the largest angled ROI of text. We will rotate text-image on based of angle made by the largest angled ROI.</li></ol><pre>def detect_largest_angled_text_roi(image):<br>    <br>    # create a copy of image<br>    img = image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br>    <br>        # draw rectangle box around texts<br>        cv2.drawContours(img, [largest_roi], 0, (255, 0, 0), 2)<br>    <br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ci6RGCBjAQlr2NE_Ej0bzQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5A7YnoEE1ASbJ_JesjWCxw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*gAA-N5_LUcNx4STWCLUPhg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AN8YQJdO59Eaff2I8Szq9A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ok2AnPtuDBhXO1QhiF6_Jw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qOl_nZ6J3UhpIlF7fylW-w.jpeg" /><figcaption>Largest ROI of text</figcaption></figure><p>2. Fit line for largest contour. We could use cv2.minAreaRect() that returns center(x,y) , (width,height) and angle of rotation. But I found the angle of rotation it returns to be very inconsistent. So, we use a different way to get angle using cv2.fitLine. Following is just for visualization and understanding on how a line is fitted with respect to largest text ROI.</p><pre>def fit_line_on_largest_roi(image):<br>    <br>    # create a copy of image<br>    img = image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br>    <br>        # draw rectangle box around texts<br>        cv2.drawContours(img, [largest_roi], 0, (255, 0, 0), 2)<br><br>        # get fitted line<br>        [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>        # calculate start and end points for the line to be drawn<br>        lefty = int((-x*vy/vx) + y)<br>        righty = int(((img.shape[1]-x)*vy/vx)+y)<br><br>        # fit  line<br>        cv2.line(img, (0, lefty), (img.shape[1]-1, righty), (0, 255, 0), 2)<br>    <br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sJCCycPQj2lWsZxtbWOAsg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*QCrMyIx33EvZDtDJaLG8MQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4qH4OqY2zNfZ2fA-v4p0sA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0eEdYXBEF5Z0E71wdigNTw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SuI1v20Sipcsry8Gj-0FjQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*g08rBn8PUjydlH7rHiTq6w.jpeg" /><figcaption>Line Fitted on largest ROI of text</figcaption></figure><p>3. Get angle of the fitted line. This angle is used for rotating the text image to straighten the rotated text image.</p><pre>def get_angle_of_fitted_line(image):<br>    <br>    # create a copy of image<br>    img = image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br>    <br>        # draw rectangle box around texts<br>        cv2.drawContours(img, [largest_roi], 0, (255, 0, 0), 2)<br><br>        # get fitted line<br>        [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>        # calculate start and end points for the line to be drawn<br>        lefty = int((-x*vy/vx) + y)<br>        righty = int(((img.shape[1]-x)*vy/vx)+y)<br><br>        # fit  line<br>        cv2.line(img, (0, lefty), (img.shape[1]-1, righty), (0, 255, 0), 2)<br><br>        # get angle<br>        angle_rad = np.arctan2(vy, vx)<br>        angle = np.degrees(angle_rad)[0]<br><br>        # display angle<br>        cv2.putText(img, f&#39;Angle : {angle}&#39;, (0, 30 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)<br>        <br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BSWjsmVjycxUsiBzyPjJXg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*r5TnnixXS8YAoNN-aWX_SQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ot6mQAcq2VFmELhVRS6L3A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fLsOvf7kHdk3w0Q5mkOybw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*STe1rp4t6Lar_bY0xw5cCg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VqSSldwg_7XmhprB70LDOQ.jpeg" /><figcaption>Angle of Fitted Line</figcaption></figure><p>4. Finally Rotate the image with respect to the angle calculated.</p><pre>def rotate_text_image(image):<br>    <br>    # create a copy of image<br>    img = image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br>    <br>        # draw rectangle box around texts<br>        cv2.drawContours(img, [largest_roi], 0, (255, 0, 0), 2)<br><br>        # get fitted line<br>        [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>        # calculate start and end points for the line to be drawn<br>        lefty = int((-x*vy/vx) + y)<br>        righty = int(((img.shape[1]-x)*vy/vx)+y)<br><br>        # fit  line<br>        cv2.line(img, (0, lefty), (img.shape[1]-1, righty), (0, 255, 0), 2)<br><br>        # get angle<br>        angle_rad = np.arctan2(vy, vx)<br>        angle = np.degrees(angle_rad)[0]<br><br>        <br>        height, width = img.shape[:2]<br>        center = (width // 2, height // 2)<br>        <br>        # if angle made by roi is 90 degree then no rotation needed<br>        if angle != 90:<br>            rotation_matrix = cv2.getRotationMatrix2D(center, angle , scale=1.0)<br>            img = cv2.warpAffine(img, rotation_matrix , (width, height))   <br>        <br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sJCCycPQj2lWsZxtbWOAsg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*oa6hwoGG3D58TyegEFM5Pg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ci6MUbZXBpwb9hEBVcyYuw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sYNFbAygm__hOujlfEE2mA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Oelr9j3FH09KHIbTrA1E0g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hGn_GxZkmjf4IwgtFhPVsg.jpeg" /><figcaption>Rotation of Text-Images with respect to fitted line</figcaption></figure><p>We can see from the fitted line all line seems to be parallel with x-axis and thus the image are straightened. But there seems to be a slight problem. A part of original image looks to be cut out of frame. So, we must introduce padding on text-image.</p><p>5. Perform padding on images and rotate.</p><pre>def padd_and_rotate_text_image(image):<br>    <br>    # set padding size<br>    padding_size = 50 <br><br>    # padd with black pixels<br>    padded_image = np.zeros((image.shape[0] + 2 * padding_size, image.shape[1] + 2 * padding_size, 3), dtype=np.uint8)<br>    padded_image[padding_size:padding_size + image.shape[0], padding_size:padding_size + image.shape[1]] = image<br><br>    # create a copy of image<br>    img = padded_image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br>    <br>        # draw rectangle box around texts<br>        cv2.drawContours(img, [largest_roi], 0, (255, 0, 0), 2)<br><br>        # get fitted line<br>        [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>        # calculate start and end points for the line to be drawn<br>        lefty = int((-x*vy/vx) + y)<br>        righty = int(((img.shape[1]-x)*vy/vx)+y)<br><br>        # fit  line<br>        cv2.line(img, (0, lefty), (img.shape[1]-1, righty), (0, 255, 0), 2)<br><br>        # get angle<br>        angle_rad = np.arctan2(vy, vx)<br>        angle = np.degrees(angle_rad)[0]<br><br>        <br>        height, width = img.shape[:2]<br>        center = (width // 2, height // 2)<br>        <br>        # if angle made by roi is 90 degree then no rotation needed<br>        if angle != 90:<br>            rotation_matrix = cv2.getRotationMatrix2D(center, angle , scale=1.0)<br>            img = cv2.warpAffine(img, rotation_matrix , (width, height))   <br>        <br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*NPFqmk7p0N2-WvnPG0f6YQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*gqr7pEHQnJOHD-TtmT8rrw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*M1D9XyicOgGtFvDnjh_Uvw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*XeXcwRp9JYmQ-GvHNtpEYw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*54V_7UKYMlK_LBTp2OCFdw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*lgWv7h_5YJdoz0_GmniGRw.jpeg" /><figcaption>Padding and Rotation of Text-Image</figcaption></figure><p>6. Finally extract texts from rotated(deskewed) text-images.</p><pre>def extract_text_from_deskewed_text_image(image):<br>    <br>    # set padding size<br>    padding_size = 50 <br><br>    # padd with black pixels<br>    padded_image = np.zeros((image.shape[0] + 2 * padding_size, image.shape[1] + 2 * padding_size, 3), dtype=np.uint8)<br>    padded_image[padding_size:padding_size + image.shape[0], padding_size:padding_size + image.shape[1]] = image<br><br>    # create a copy of image<br>    img = padded_image.copy()<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get angled rois<br>    angled_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                angled_rois.append(box_vertices)<br>                <br>    if angled_rois:<br><br>        # get largest roi<br>        largest_roi = max(angled_rois, key=cv2.contourArea)<br><br>        # get fitted line<br>        [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>        # get angle<br>        angle_rad = np.arctan2(vy, vx)<br>        angle = np.degrees(angle_rad)[0]<br><br>        <br>        height, width = img.shape[:2]<br>        center = (width // 2, height // 2)<br>        <br>        # if angle made by roi is 90 degree then no rotation needed<br>        if angle != 90:<br>            rotation_matrix = cv2.getRotationMatrix2D(center, angle , scale=1.0)<br>            img = cv2.warpAffine(img, rotation_matrix , (width, height))   <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(img)[&#39;boxes&#39;]<br><br>    # get deskewed rois<br>    deskewed_rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on deskewed_rois list<br>                deskewed_rois.append(box_vertices)<br>   <br>                # draw rectangle box around texts<br>                cv2.drawContours(img, [box_vertices], 0, (255, 0, 0), 2)<br>   <br>    # extract text<br>    img_text = img.copy()<br><br>    for index,roi in enumerate(deskewed_rois):<br>        # get the bounding box from the angled ROI<br>        x, y, w, h = cv2.boundingRect(roi)<br>        <br>        # get text using pytesseract<br>        text_roi = img[y : y+h, x : x+w]<br><br>        # little Preprocessing<br>        roi_gray = cv2.cvtColor(text_roi, cv2.COLOR_BGR2GRAY)<br>        <br>        # get lines of text from pytesseract <br>        text_line =f&#39;Line {index + 1} : HIRING&#39; <br>        <br>        # Put text on image<br>        cv2.putText(img_text, text_line.strip(&#39;\n&#39;), (0, 30 + (index) * 40 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0,255), 2, cv2.LINE_AA)<br><br>    return img_text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*V1anhsCpIpW-M9iaXIP0Nw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*PYPziBtm4TqvthuGXw5TFQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*eVl6JPakWR3_8oDtKXSGEQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*dqVJSCpmk2e_Nz4hW_8vDw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*92igrWL9UqpjQS4hX5Ah6g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*H4TmU_GlouysH9v0gEOJ8w.jpeg" /><figcaption>Text Extracted from padded Rotated(Deskewed) Text-Image</figcaption></figure><p>We can see pytesseract is accurately extracting text from straightened text-images. This demonstrates that the skewed text-images can be rotated(deskewed) with CRAFT and OpenCV, resulting in pytesseract accurately extracting text.</p><h4>Final Code</h4><p>Following code is more readable and modular.</p><pre>def padd_image(image):<br>    # set padding size<br>    padding_size = 50 <br><br>    # padd with black pixels<br>    padded_image = np.zeros((image.shape[0] + 2 * padding_size, image.shape[1] + 2 * padding_size, 3), dtype=np.uint8)<br>    padded_image[padding_size:padding_size + image.shape[0], padding_size:padding_size + image.shape[1]] = image<br><br>    return padded_image<br><br>def get_rois(image):<br>    <br>    # get ROIs for text using CRAFT<br>    text_rois = craft_detector.detect_text(image)[&#39;boxes&#39;]<br><br>    # get rois<br>    rois = []<br>    for roi in text_rois:<br>        if len(roi) &gt;= 3:  # ensure at least 3 points for a polygon<br>                <br>                # convert box points to numpy array for easier manipulation<br>                box_points = np.array(roi, dtype=np.int32).reshape(-1, 2)<br><br>                # calculate the minimum bounding rectangle<br>                rotated_rect = cv2.minAreaRect(box_points)<br>                <br>                # get vertices of box <br>                box_vertices = cv2.boxPoints(rotated_rect)<br>                box_vertices = np.int0(box_vertices)<br><br>                # append box_vertices on angled_rois list<br>                rois.append(box_vertices)<br>    <br>    return rois<br><br>def rotate_text_image(image,angled_rois):<br><br>     # get largest roi<br>    largest_roi = max(angled_rois, key=cv2.contourArea)<br><br>    # get fitted line<br>    [vx,vy,x,y] = cv2.fitLine(largest_roi, cv2.DIST_L2,0,0.01,0.01)<br><br>    # get angle<br>    angle_rad = np.arctan2(vy, vx)<br>    angle = np.degrees(angle_rad)[0]<br><br>    <br>    height, width = image.shape[:2]<br>    center = (width // 2, height // 2)<br>    <br>    # if angle made by roi is 90 degree then no rotation needed<br>    if angle != 90:<br>        rotation_matrix = cv2.getRotationMatrix2D(center, angle , scale=1.0)<br>        image = cv2.warpAffine(image, rotation_matrix , (width, height))   <br><br>    return image<br>     <br>def extract_text(image, text_rois):<br>    <br>    # copy of image<br>    img_text = image.copy()<br>    <br>    for index,roi in enumerate(text_rois):<br>        # get the bounding box from the angled ROI<br>        x, y, w, h = cv2.boundingRect(roi)<br>        <br>        # get text using pytesseract<br>        text_roi = image[y : y+h, x : x+w]<br><br>        # little Preprocessing<br>        roi_gray = cv2.cvtColor(text_roi, cv2.COLOR_BGR2GRAY)<br>        <br>        # get lines of text from pytesseract <br>        text_line =f&#39;Line {index + 1} : &#39; +  pytesseract.image_to_string(roi_gray, lang=&#39;eng&#39;, config=custom_config)<br>        <br>        # Put text on image<br>        cv2.putText(img_text, text_line.strip(&#39;\n&#39;), (0, 30 + (index) * 40 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0,255), 2, cv2.LINE_AA)<br><br>    return img_text<br> <br>def extract_text_from_deskewed_text_image(image):<br>    <br>    # padd image<br>    img = padd_image(image)<br><br>    # get angled rois<br>    angled_rois = get_rois(img)<br>    <br>    # rotate text_image <br>    if angled_rois:<br>        img = rotate_text_image(img,angled_rois)<br>        <br>    # get deskewed rois<br>    deskewed_rois = get_rois(img)<br>    <br>    # extract text<br>    img_text = extract_text(img,deskewed_rois)<br><br>    return img_text</pre><p>Hope the blog was useful to you. Cheers.</p><p>You can connect me here:</p><p><a href="https://github.com/HordesOfGhost">Github</a></p><p><a href="https://www.linkedin.com/in/bibek-thapa-sb1129/">Linkedin</a></p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c8c3fb8ef9d" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-to-extract-texts-from-rotated-skewed-text-images-using-craft-opencv-and-pytesseract-9c8c3fb8ef9d">How to Extract Texts from Rotated(Skewed) Text-Images using CRAFT, OpenCV and pytesseract</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>