Official implementation of Character Region Awareness for Text Detection (CRAFT)

Overview

CRAFT: Character-Region Awareness For Text detection

Official Pytorch implementation of CRAFT text detector | Paper | Pretrained Model | Supplementary

Youngmin Baek, Bado Lee, Dongyoon Han, Sangdoo Yun, Hwalsuk Lee.

Clova AI Research, NAVER Corp.

Sample Results

Overview

PyTorch implementation for CRAFT text detector that effectively detect text area by exploring each character region and affinity between characters. The bounding box of texts are obtained by simply finding minimum bounding rectangles on binary map after thresholding character region and affinity scores.

teaser

Updates

13 Jun, 2019: Initial update 20 Jul, 2019: Added post-processing for polygon result 28 Sep, 2019: Added the trained model on IC15 and the link refiner

Getting started

Install dependencies

Requirements

  • PyTorch>=0.4.1
  • torchvision>=0.2.1
  • opencv-python>=3.4.2
  • check requiremtns.txt
pip install -r requirements.txt

Training

The code for training is not included in this repository, and we cannot release the full training code for IP reason.

Test instruction using pretrained model

  • Download the trained models
Model name Used datasets Languages Purpose Model Link
General SynthText, IC13, IC17 Eng + MLT For general purpose Click
IC15 SynthText, IC15 Eng For IC15 only Click
LinkRefiner CTW1500 - Used with the General Model Click
  • Run with pretrained model
python test.py --trained_model=[weightfile] --test_folder=[folder path to test images]

The result image and socre maps will be saved to ./result by default.

Arguments

  • --trained_model: pretrained model
  • --text_threshold: text confidence threshold
  • --low_text: text low-bound score
  • --link_threshold: link confidence threshold
  • --cuda: use cuda for inference (default:True)
  • --canvas_size: max image size for inference
  • --mag_ratio: image magnification ratio
  • --poly: enable polygon type result
  • --show_time: show processing time
  • --test_folder: folder path to input images
  • --refine: use link refiner for sentense-level dataset
  • --refiner_model: pretrained refiner model

Links

Citation

@inproceedings{baek2019character,
  title={Character Region Awareness for Text Detection},
  author={Baek, Youngmin and Lee, Bado and Han, Dongyoon and Yun, Sangdoo and Lee, Hwalsuk},
  booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
  pages={9365--9374},
  year={2019}
}

License

Copyright (c) 2019-present NAVER Corp.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Comments
  • Export to ONNX

    Export to ONNX

    I'm trying to export from pth to ONNX format:

    import torch
    from torch.autograd import Variable
    import cv2
    import imgproc
    from craft import CRAFT
    
    # load net
    net = CRAFT()     # initialize
    net = net.cuda()
    net = torch.nn.DataParallel(net)
    
    net.load_state_dict(torch.load('./craft_mlt_25k.pth'))
    net.eval()
    
    
    # load data
    image = imgproc.loadImage('./misc/test.jpg')
    
    # resize
    img_resized, target_ratio, size_heatmap = imgproc.resize_aspect_ratio(image, 1280, interpolation=cv2.INTER_LINEAR, mag_ratio=1.5)
    ratio_h = ratio_w = 1 / target_ratio
    
    # preprocessing
    x = imgproc.normalizeMeanVariance(img_resized)
    x = torch.from_numpy(x).permute(2, 0, 1)    # [h, w, c] to [c, h, w]
    x = Variable(x.unsqueeze(0))                # [c, h, w] to [b, c, h, w]
    x = x.cuda()
    
    # trace export
    torch.onnx.export(net,
                      x,
                      'onnx/craft.onnx',
                      export_params=True,
                      verbose=True)
    

    But then encountered this error:

    RuntimeError: tuple appears in op that does not forward tuples (VisitNode at /opt/conda/conda-bld/pytorch_1556653114079/work/torch/csrc/jit/passes/lower_tuples.cpp:117)
    

    Followed these issue https://github.com/pytorch/pytorch/issues/5315 and https://github.com/pytorch/pytorch/issues/13397, it turnned out that nn.DataParallel wrapper doesn't support trace export for ONNX.

    Is there a workaround for this?

    opened by hiepph 19
  • Why the result is different from local run of the repo and the web demo version?

    Why the result is different from local run of the repo and the web demo version?

    I tested my images first on the web demo, but when I test using the repo locally on my machine I get different results. Is there a difference in the parameters or you are using another weight. I need to know the difference to apply it to my local version.

    Website demo result that recognizes line by line[what I need] Screenshot from 2019-10-02 14-40-36

    Local repo result that recognizes word by word

    res_4558

    opened by ShroukMansour 14
  • TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

    TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

    Loading weights from checkpoint (craft_mlt_25k.pth) Loading weights of refiner from checkpoint (craft_refiner_CTW1500.pth) Traceback (most recent call last):08014857_IMG_0236.jpeg File "test.py", line 169, in file_utils.saveResult(image_path, image[:,:,::-1], polys, dirname=result_folder) File "/home/aiteammor/Downloads/CRAFT-pytorch/file_utils.py", line 62, in saveResult cv2.polylines(np.array(img), [poly.reshape((-1, 1, 2))], True, color=(0, 0, 255), thickness=2) TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

    opened by xxxpsyduck 9
  • The reimplementation results are not good

    The reimplementation results are not good

    image This is my reimplementation results. I found that it is not good enough and recall is much lower than your results. Could you give me some advice or matters needing attention. Thanks a lot

    opened by backtime92 9
  • Bounding box is shuffled. How to sort it?

    Bounding box is shuffled. How to sort it?

    First of all thanks very much for your model. I have used your pretrained model for text detection. I have got the bounding box coordinates as txt files. The resulted bounding boxes are shuffled and i could not sort it . When there is a presence of curved text in a same line like in the image below, the order gets shuffled and i need to sort it before passing it to text extraction model.

    image

    I have not used POLY mode. For the above image, the model outputs a txt file in which the bb coordinates are as follows. I have added the detected text for better explanation of my problem. In this case the detection order is

    146,36,354,34,354,82,146,84 "Australian"

    273,78,434,151,411,201,250,129 "Collection"

    146,97,250,97,250,150,146,150 "vine"

    77,166,131,126,154,158,99,197 "Old"

    242,215,361,241,354,273,235,248 "Valley"

    140,247,224,219,234,250,150,277 "Eden"

    194,298,306,296,307,324,194,325 "Shiraz"

    232,406,363,402,364,421,233,426 "Vintage"

    152,402,216,405,215,425,151,422 "2008"

    124,470,209,480,207,500,122,490 "South"

    227,481,387,472,389,494,228,503 "Australia"

    222,562,312,564,311,585,222,583 "Gibson"

    198,564,217,564,217,584,198,584 "by"

    386,570,421,570,421,600,386,600 "750 ml"

    But the expected output is Australian->old->vine->collection->Eden->Valley->shiraz->2008->vintage->south->Australia->by->GIBSON->750ml.

    opened by kalai2033 8
  • Execution in docker image issue vgg16_bn.py

    Execution in docker image issue vgg16_bn.py

    Hey, so I got this working on my mac pretty easily. However I just can't seem to get it to work on a docker image.

    It seems to crash when executing this line https://github.com/clovaai/CRAFT-pytorch/blob/master/basenet/vgg16_bn.py#L61

    Tried to debug through, but don't really have any experience with pdb so got nowhere there. I suspect my Dockerfile isn't setup right. Did anyone manage to get this working or have similar issues? My dockerfile is below.

    FROM ubuntu:18.04
    
    ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
     
    # Install tools
    RUN apt-get update \
            && apt-get --yes install \
            wget \
            curl \
            ca-certificates \
            sudo \
            git \
            bzip2 \
            libx11-6 libglib2.0-0 \
            libsm6 libxext6 libxrender-dev \
            && rm -rf /var/lib/apt/lists/*
     
    
     # Create a working directory
    RUN mkdir /app
    WORKDIR /app
    
    
    # Create a non-root user and switch to it
    RUN adduser --disabled-password --gecos '' --shell /bin/bash user \
     && chown -R user:user /app
    RUN echo "user ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/90-user
    USER user
    
    # All users can use /home/user as their home directory
    ENV HOME=/home/user
    RUN chmod 777 /home/user
    
    # Install Miniconda
    RUN curl -so ~/miniconda.sh https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \
     && chmod +x ~/miniconda.sh \
     && ~/miniconda.sh -b -p ~/miniconda \
     && rm ~/miniconda.sh
     
    # Set environment PATH
    ENV PATH=/home/user/miniconda/bin:$PATH
    ENV CONDA_AUTO_UPDATE_CONDA=false
    
    RUN conda install --yes python=3.6
    
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    COPY . .
    
    CMD ["python", "test.py"]
    
    opened by loopedice 7
  • How to evaluate text detection results without word level annotation

    How to evaluate text detection results without word level annotation

    Dataset like ICDAR2015 has word level annotation, so that craft can be evaluated easily by IoU.

    How can we evaluate the performance of craft with annotation like text region? Such as labeling the entire text area "Hello World!" with a single rectangle.

    It is my pleasure to get the answers.

    opened by KosukeHao 7
  • Extracting the detected boxes

    Extracting the detected boxes

    @YoungminBaek Now that Craft have detected the boxes and saved them into a .txt file, can you add a script to extract/crop the detected boxes into images.

    opened by ghost 6
  • Training details about generating pseudo groundtruth

    Training details about generating pseudo groundtruth

    Hi, thanks for your work. I have some questions about the detail of generating pseudo ground-truth.

    1. In Figure 6, I am confused that why can't we just input the whole image to generate the pseudo ground truth (non-text region area are padded with 0).

    2. How to crop the image? As I understand for the paper Figure 4, we should first crop the text region and then feed them to the network. Is that right? However, in the ICDAR2015, the word ground truths aren't the normal rectangle. 1) How do we crop it? (rotate it and then crop?).

    opened by lianqing11 6
  • How to get rectified polygons from polygon points?

    How to get rectified polygons from polygon points?

    In the paper you state "Moreover, with our polygon representation, the curved images can be rectified into straight text images, which are also shown in Fig. 11. We believe this ability for rectification can further be of use for recognition tasks." My question is from a set of polygon points, how can I reconstruct the rectified image? Can you kindly point me towards the correct direction? many thanks in advance

    opened by ziudeso 6
  • LinkRefiner clarification ?

    LinkRefiner clarification ?

    Hi @YoungminBaek. Thanks for the excellent works.

    I'm trying to replicate LinkRefiner but not achieve a good result as you did.

    May I ask:

    1. You said that the width of each line in LinkRefiner ground truth is proportional to the distance between paired control points. How much is it exactly? 40% of the distance between paired control points, 60%, ..etc ? image

    2. What loss function do you used to train the LinkRefiner? Currently I'm using Focal Loss ;_;

    Hope you can answer these question :P

    opened by lamhoangtung 5
  • What is `score_text` in line 162 of `test.py` ?

    What is `score_text` in line 162 of `test.py` ?

    I am extracting the texts box from the image, but one thing that I am confused about is what is the significance of score_text in the following code. bboxes, polys, score_text = test_net(net, image, args.text_threshold, args.link_threshold, args.low_text, args.cuda, args.poly, refine_net)

    Is there any confidence threshold for the extracted texts?

    opened by np-n 0
  • OSError: image file is truncated (0 bytes not processed)

    OSError: image file is truncated (0 bytes not processed)

    While reading the images using the scikit-image skimage.io module i.e img = io.imread(img_file) in imgproc.py python file it throws an error : OSError: image file is truncated (0 bytes not processed) error. How to fix it?

    opened by np-n 1
  • Cropped image with merge bounding boxes

    Cropped image with merge bounding boxes

    Hi everyone, I am sorry for bothering, maybe that's a trivial question, but I need to "merge" the bounding boxes detected and save them to an image. I have read this issue (https://github.com/clovaai/CRAFT-pytorch/issues/39#issuecomment-526930324) but I believe this code allows to save an image for every bounding box I need an image with more bounding boxes merged. In other terms, with text "Hello World" on the image, I don't want two different cropped images "Hello" and "World", but only one cropped image with "Hello World"

    Any suggestions?

    Thank you again!

    opened by riccardoregnicoli 0
  • CRAFT uses lots of video ram

    CRAFT uses lots of video ram

    Hi everyone!

    craft_mlt_25k.pth uses 3 GB of video ram. I think this is overkill for my work. Do you have any lightweight CRAFT network ?

    Thank you!

    Batu.

    opened by dilerbatu 0
  • Polylines bad argument: expected Ptr<cv::UMat> for argument 'img'

    Polylines bad argument: expected Ptr for argument 'img'

    Only for some images the text detection fails with the error: cv2.polylines(img, [poly.reshape((-1, 1, 2))], True, color=(0, 0, 255), thickness=2) cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'polylines'

    Overload resolution failed:

    • Layout of the output array img is incompatible with cv::Mat
    • Expected Ptrcv::UMat for argument 'img'

    I have looked for a difference between the working and to failed images but cannot seem to find a difference?

    opened by LiamSimons 1
Owner
Clova AI Research
Open source repository of Clova AI Research, NAVER & LINE
Clova AI Research
Motion detector, Full body detection, Upper body detection, Cat face detection, Smile detection, Face detection (haar cascade), Silverware detection, Face detection (lbp), and Sending email notifications

Security camera running OpenCV for object and motion detection. The camera will send email with image of any objects it detects. It also runs a server that provides web interface with live stream video.

Peace 10 Jun 30, 2021
Packaged, Pytorch-based, easy to use, cross-platform version of the CRAFT text detector

CRAFT: Character-Region Awareness For Text detection Packaged, Pytorch-based, easy to use, cross-platform version of the CRAFT text detector | Paper |

null 188 Dec 28, 2022
A novel region proposal network for more general object detection ( including scene text detection ).

DeRPN: Taking a further step toward more general object detection DeRPN is a novel region proposal network which concentrates on improving the adaptiv

Deep Learning and Vision Computing Lab, SCUT 151 Dec 12, 2022
This is a implementation of CRAFT OCR method

This is a implementation of CRAFT OCR method

Esaka 0 Nov 1, 2021
caffe re-implementation of R2CNN: Rotational Region CNN for Orientation Robust Scene Text Detection

R2CNN: Rotational Region CNN for Orientation Robust Scene Text Detection Abstract This is a caffe re-implementation of R2CNN: Rotational Region CNN fo

candler 80 Dec 28, 2021
Scene text detection and recognition based on Extremal Region(ER)

Scene text recognition A real-time scene text recognition algorithm. Our system is able to recognize text in unconstrain background. This algorithm is

HSIEH, YI CHIA 155 Dec 6, 2022
Multi-Oriented Scene Text Detection via Corner Localization and Region Segmentation

This is the official implementation of "Multi-Oriented Scene Text Detection via Corner Localization and Region Segmentation". For more details, please

Pengyuan Lyu 309 Dec 6, 2022
A curated list of resources for text detection/recognition (optical character recognition ) with deep learning methods.

awesome-deep-text-detection-recognition A curated list of awesome deep learning based papers on text detection and recognition. Text Detection Papers

null 2.4k Jan 8, 2023
Rotational region detection based on Faster-RCNN.

R2CNN_Faster_RCNN_Tensorflow Abstract This is a tensorflow re-implementation of R2CNN: Rotational Region CNN for Orientation Robust Scene Text Detecti

UCAS-Det 581 Nov 22, 2022
Text recognition (optical character recognition) with deep learning methods.

What Is Wrong With Scene Text Recognition Model Comparisons? Dataset and Model Analysis | paper | training and evaluation data | failure cases and cle

Clova AI Research 3.2k Jan 4, 2023
Optical character recognition for Japanese text, with the main focus being Japanese manga

Manga OCR Optical character recognition for Japanese text, with the main focus being Japanese manga. It uses a custom end-to-end model built with Tran

Maciej Budyś 327 Jan 1, 2023
An Implementation of the alogrithm in paper IncepText: A New Inception-Text Module with Deformable PSROI Pooling for Multi-Oriented Scene Text Detection

InceptText-Tensorflow An Implementation of the alogrithm in paper IncepText: A New Inception-Text Module with Deformable PSROI Pooling for Multi-Orien

GeorgeJoe 115 Dec 12, 2022
A semi-automatic open-source tool for Layout Analysis and Region EXtraction on early printed books.

LAREX LAREX is a semi-automatic open-source tool for layout analysis on early printed books. It uses a rule based connected components approach which

null 162 Jan 5, 2023
Corner-based Region Proposal Network

Corner-based Region Proposal Network CRPN is a two-stage detection framework for multi-oriented scene text. It employs corners to estimate the possibl

xhzdeng 140 Nov 4, 2022
Character Segmentation using TensorFlow

Character Segmentation Segment characters and spaces in one text line,from this paper Chinese English mixed Character Segmentation as Semantic Segment

null 26 Aug 25, 2022
Handwritten Number Recognition using CNN and Character Segmentation

Handwritten-Number-Recognition-With-Image-Segmentation Info About this repository This Repository is aimed at reading handwritten images of numbers an

Sparsha Saha 17 Aug 25, 2022
Extract tables from scanned image PDFs using Optical Character Recognition.

ocr-table This project aims to extract tables from scanned image PDFs using Optical Character Recognition. Install Requirements Tesseract OCR sudo apt

Abhijeet Singh 209 Dec 6, 2022
ISI's Optical Character Recognition (OCR) software for machine-print and handwriting data

VistaOCR ISI's Optical Character Recognition (OCR) software for machine-print and handwriting data Publications "How to Efficiently Increase Resolutio

ISI Center for Vision, Image, Speech, and Text Analytics 21 Dec 8, 2021
make a better chinese character recognition OCR than tesseract

deep ocr See README_en.md for English installation documentation. 只在ubuntu下面测试通过,需要virtualenv安装,安装路径可自行调整: git clone https://github.com/JinpengLI/deep

Jinpeng 1.5k Dec 28, 2022