### Install cnocr using a domestic mirror Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Installs the cnocr library using a specified domestic installation source, such as Aliyun. This can help speed up installation if the default PyPI source is slow. ```bash pip install cnocr -i https://mirrors.aliyun.com/pypi/simple ``` -------------------------------- ### Install cnocr for development Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Installs the cnocr library with development dependencies. This includes tools and libraries necessary for training new models or contributing to the project. ```bash $ pip install cnocr[dev] ``` -------------------------------- ### Install cnocr with CPU support Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Installs the cnocr library with support for CPU-based ONNX runtime. This is the standard installation for environments without a GPU. ```bash $ pip install cnocr[ort-cpu] ``` -------------------------------- ### Install cnocr with GPU support Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Installs the cnocr library with support for GPU-accelerated ONNX runtime. This option is recommended for users with a compatible GPU environment. ```bash $ pip install cnocr[ort-gpu] ``` -------------------------------- ### Deploy and Consume HTTP Server API Source: https://context7.com/breezedeus/cnocr/llms.txt Shows how to start the CnOCR HTTP server programmatically and interact with it using Python requests to perform OCR on uploaded images. ```python import subprocess import requests subprocess.run(['cnocr', 'serve', '-p', '8501']) image_path = './document.jpg' response = requests.post('http://localhost:8501/ocr', files={'image': (image_path, open(image_path, 'rb'), 'image/jpeg')}) result = response.json() ``` -------------------------------- ### Vertical Text Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This example demonstrates how to perform vertical text recognition using CnOCR. It specifies the Chinese recognition model `ch_PP-OCRv3` from PaddleOCR, which is suitable for recognizing text arranged vertically in an image. ```python from cnocr import CnOcr img_fp = './docs/examples/shupai.png' ocr = CnOcr(rec_model_name='ch_PP-OCRv3') out = ocr.ocr(img_fp) print(out) ``` -------------------------------- ### Pull cnocr Docker image Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Pulls the latest Docker image for cnocr from Docker Hub. This allows for running cnocr in a containerized environment without local installation. ```bash $ docker pull breezedeus/cnocr:latest ``` -------------------------------- ### CnOcr with Different Model Configurations (Python) Source: https://context7.com/breezedeus/cnocr/llms.txt Illustrates how to initialize the CnOcr class with various pre-trained models for different use cases, including document screenshots, scene images, English text, Traditional Chinese, vertical text, and pure numbers. It also shows how to configure the backend (PyTorch/ONNX), use GPU acceleration, and restrict recognized characters. ```python from cnocr import CnOcr # For document screenshots (faster, simpler detection) ocr_doc = CnOcr( rec_model_name='doc-densenet_lite_136-gru', det_model_name='naive_det' # Rule-based line splitting, no neural detection ) result = ocr_doc.ocr('./screenshot.png') # For scene images (photographs with complex backgrounds) ocr_scene = CnOcr( rec_model_name='scene-densenet_lite_136-gru', det_model_name='ch_PP-OCRv5_det' ) result = ocr_scene.ocr('./photo.jpg') # For pure English text ocr_en = CnOcr( rec_model_name='en_PP-OCRv3', det_model_name='en_PP-OCRv3_det' ) result = ocr_en.ocr('./english_document.jpg') # For Traditional Chinese o cr_cht = CnOcr(rec_model_name='chinese_cht_PP-OCRv3') result = ocr_cht.ocr('./traditional_chinese.jpg') # For vertical text (using PaddleOCR models) o cr_vertical = CnOcr(rec_model_name='ch_PP-OCRv3') result = ocr_vertical.ocr('./vertical_text.png') # For pure numbers (bank cards, ID numbers) o cr_num = CnOcr( rec_model_name='number-densenet_lite_136-fc', det_model_name='naive_det' ) result = ocr_num.ocr('./bank_card.jpg') # Using GPU with PyTorch backend o cr_gpu = CnOcr( rec_model_name='densenet_lite_136-gru', rec_model_backend='pytorch', # 'pytorch' or 'onnx' (default) context='cuda' # 'cpu', 'gpu', or 'cuda:0' ) result = ocr_gpu.ocr('./image.jpg') # Restrict recognition to specific characters o cr_digits = CnOcr(cand_alphabet='0123456789') result = ocr_digits.ocr('./captcha.png') ``` -------------------------------- ### Initialize and Use Recognizer Class Source: https://context7.com/breezedeus/cnocr/llms.txt Provides direct access to the recognition model. Useful for pre-cropped images and supports custom model files, vocabularies, and candidate character restrictions. ```python from cnocr.recognizer import Recognizer rec = Recognizer(model_name='densenet_lite_136-gru', model_backend='onnx', context='cpu') text, score = rec.ocr_for_single_line('./text_line.jpg') rec.set_cand_alphabet('0123456789ABCDEF') rec_custom = Recognizer(model_name='densenet_lite_136-gru', model_fp='./my_trained_model.ckpt', vocab_fp='./my_vocab.txt') ``` -------------------------------- ### Train, Fine-tune, or Resume cnocr Model Training via CLI Source: https://context7.com/breezedeus/cnocr/llms.txt Command-line interface commands for training a new cnocr model, fine-tuning from a pretrained model, or resuming an interrupted training session. These commands utilize a specified configuration file and model architecture. ```bash # Train a new model cnocr train \ -m densenet_lite_136-gru \ -i ./data_index_dir/ \ --train-config-fp ./train_config.json # Fine-tune from pretrained model cnocr train \ -m densenet_lite_136-gru \ -i ./data_index_dir/ \ --train-config-fp ./train_config.json \ -p ./pretrained_model.ckpt \ --finetuning # Resume interrupted training cnocr train \ -m densenet_lite_136-gru \ -i ./data_index_dir/ \ --train-config-fp ./train_config.json \ -r ./checkpoints/last.ckpt ``` -------------------------------- ### Initialize and Use ImageClassifier for Image Classification Source: https://context7.com/breezedeus/cnocr/llms.txt Python code demonstrating how to initialize and use the ImageClassifier from cnocr for image classification tasks. It covers initializing the classifier with custom categories, loading trained weights, performing single image predictions, and batch predictions. ```python from cnocr.classification import ImageClassifier import torch # Initialize classifier with custom categories clf = ImageClassifier( base_model_name='mobilenet_v2', # or 'densenet121', 'efficientnet_v2_s' categories=('blurry', 'clear', 'rotated'), transform_configs={ 'crop_size': [224, 224], 'resize_size': 232 } ) # Load trained weights clf.load('./classifier_model.ckpt', device='cuda') clf.eval() # Predict single image img = torch.tensor(read_img('./image.jpg', gray=False).transpose((2, 0, 1))) with torch.no_grad(): output = clf(clf.eval_transform(img).unsqueeze(0)) category = clf.categories[output['preds'][0].item()] confidence = output['probs'][0].item() print(f"Category: {category}, Confidence: {confidence:.2f}") # Batch prediction image_paths = ['./img1.jpg', './img2.jpg', './img3.jpg'] results = clf.predict_images(image_paths, batch_size=16) # Returns: [('clear', 0.95), ('blurry', 0.87), ('rotated', 0.92)] for path, (category, prob) in zip(image_paths, results): print(f"{path}: {category} ({prob:.2%})") ``` -------------------------------- ### Perform Single and Batch Text Recognition Source: https://context7.com/breezedeus/cnocr/llms.txt Demonstrates how to recognize text from single image files or NumPy arrays, and how to process multiple images in batches for efficiency. ```python result = ocr.ocr_for_single_line('./single_line.jpg') print(f"Text: {result['text']}") img = np.array(Image.open('./captcha.png').convert('L')) result = ocr.ocr_for_single_line(img) images = ['./line1.jpg', './line2.jpg', np.array(Image.open('./line3.png'))] results = ocr.ocr_for_single_lines(images, batch_size=4) ``` -------------------------------- ### Execute Command Line Interface Operations Source: https://context7.com/breezedeus/cnocr/llms.txt Covers common CLI tasks including prediction, evaluation, model export to ONNX, and server management. ```bash cnocr predict -i ./image.jpg cnocr predict -m scene-densenet_lite_136-gru -b onnx -i ./images_folder/ --draw-results-dir ./output/ cnocr evaluate -m densenet_lite_136-gru -i ./test_index.txt --image-folder ./test_images/ cnocr export-onnx -m densenet_lite_136-gru -i ./trained_model.ckpt -o ./model.onnx cnocr serve -p 8501 --reload ``` -------------------------------- ### Basic Image Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This Python code snippet demonstrates how to perform basic optical character recognition on an image using the CnOCR library. It initializes the CnOcr object with default parameters and processes a specified image file, printing the recognition results. This is suitable for general image recognition tasks. ```python from cnocr import CnOcr img_fp = './docs/examples/huochepiao.jpeg' ocr = CnOcr() # Use default values for all parameters out = ocr.ocr(img_fp) print(out) ``` -------------------------------- ### Configure cnocr Model Training Source: https://context7.com/breezedeus/cnocr/llms.txt This JSON configuration file defines parameters for training or fine-tuning a cnocr OCR model. It specifies paths to vocabulary and image data, training hyperparameters, and metrics to monitor during training. ```json { "vocab_fp": "./vocab.txt", "img_folder": "./images/", "batch_size": 32, "num_workers": 4, "pin_memory": true, "train_bucket_size": 10000, "optimizer": "adamw", "learning_rate": 0.001, "weight_decay": 0.0001, "epochs": 50, "metrics": { "complete_match": {}, "cer": {} }, "pl_checkpoint_monitor": "val-complete_match-epoch", "pl_checkpoint_mode": "max", "accelerator": "auto", "devices": 1, "precision": 32 } ``` -------------------------------- ### Single Line Recognition with ocr_for_single_line (Python) Source: https://context7.com/breezedeus/cnocr/llms.txt Introduces the `ocr_for_single_line()` function for scenarios where the input image is known to contain only a single line of text. This method bypasses the detection step, offering a significant speed improvement for tasks like processing cropped text regions or captchas. ```python from cnocr import CnOcr import numpy as np from PIL import Image ocr = CnOcr() ``` -------------------------------- ### CnOcr Class - Main OCR Interface (Python) Source: https://context7.com/breezedeus/cnocr/llms.txt Demonstrates the primary interface for performing OCR using the CnOcr class. It supports various input formats like file paths, PIL Images, and NumPy arrays, and allows customization of detection and recognition parameters. The output includes recognized text, confidence scores, and bounding box positions. ```python from cnocr import CnOcr import numpy as np from PIL import Image # Initialize with default models (densenet_lite_136-gru + ch_PP-OCRv5_det) ocr = CnOcr() # OCR from file path result = ocr.ocr('./image.jpg') # Returns: [{'text': '识别的文字', 'score': 0.95, 'position': np.ndarray([[x1,y1],[x2,y2],[x3,y3],[x4,y4]])}] # OCR from PIL Image img = Image.open('./image.jpg') result = ocr.ocr(img) # OCR from NumPy array (RGB format, shape: [height, width, 3]) img_array = np.array(Image.open('./image.jpg').convert('RGB')) result = ocr.ocr(img_array) # With custom detection parameters result = ocr.ocr( './image.jpg', rec_batch_size=4, # Batch size for recognition return_cropped_image=True, # Include cropped text region images resized_shape=(768, 768), # Detection input size (affects accuracy) preserve_aspect_ratio=True, # Keep aspect ratio when resizing min_box_size=8, # Filter small boxes (height or width < 8) box_score_thresh=0.3 # Filter low-confidence detections ) # Process results for item in result: print(f"Text: {item['text']}") print(f"Confidence: {item['score']:.2f}") print(f"Position: {item['position']}") # 4 corner coordinates if 'cropped_img' in item: print(f"Cropped image shape: {item['cropped_img'].shape}") ``` -------------------------------- ### POST /ocr Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md Performs OCR on an image file using specified detection and recognition models. ```APIDOC ## POST /ocr ### Description Performs text recognition on an image. Users can specify custom detection and recognition models based on the target language or image type. ### Method POST ### Endpoint /ocr ### Parameters #### Request Body - **img_fp** (string) - Required - Path to the image file. - **det_model_name** (string) - Optional - Name of the detection model (e.g., 'en_PP-OCRv3_det', 'naive_det'). - **rec_model_name** (string) - Optional - Name of the recognition model (e.g., 'en_PP-OCRv3', 'ch_PP-OCRv3', 'chinese_cht_PP-OCRv3'). ### Request Example { "img_fp": "./docs/examples/en_book1.jpeg", "det_model_name": "en_PP-OCRv3_det", "rec_model_name": "en_PP-OCRv3" } ### Response #### Success Response (200) - **result** (list) - A list of recognized text segments and their coordinates. #### Response Example [ {"text": "Hello World", "position": [[10, 10], [100, 10], [100, 30], [10, 30]]} ] ``` -------------------------------- ### POST /ocr Source: https://context7.com/breezedeus/cnocr/llms.txt Performs full-image OCR by combining text detection and recognition. ```APIDOC ## POST /ocr ### Description Performs end-to-end OCR on an image, detecting text regions and recognizing the content within them. ### Method POST ### Endpoint /ocr ### Parameters #### Request Body - **image** (file/binary) - Required - The image file to process (supports path, PIL, NumPy, or Tensor). - **rec_batch_size** (int) - Optional - Batch size for recognition. - **return_cropped_image** (bool) - Optional - Whether to return cropped images of detected regions. - **box_score_thresh** (float) - Optional - Confidence threshold for detection boxes. ### Request Example { "image": "./image.jpg", "rec_batch_size": 4 } ### Response #### Success Response (200) - **text** (string) - The recognized text. - **score** (float) - Confidence score of the recognition. - **position** (array) - Coordinates of the detected text box. #### Response Example [ { "text": "识别的文字", "score": 0.95, "position": [[10, 10], [100, 10], [100, 30], [10, 30]] } ] ``` -------------------------------- ### English Text Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This snippet demonstrates how to use CnOCR with English-specific detection and recognition models for improved accuracy in English-only applications. It utilizes PaddleOCR's `en_PP-OCRv3_det` and `en_PP-OCRv3` models. ```python from cnocr import CnOcr img_fp = './docs/examples/en_book1.jpeg' ocr = CnOcr(det_model_name='en_PP-OCRv3_det', rec_model_name='en_PP-OCRv3') out = ocr.ocr(img_fp) print(out) ``` -------------------------------- ### Traditional Chinese Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This snippet illustrates how to use CnOCR for recognizing traditional Chinese characters. It employs the `chinese_cht_PP-OCRv3` model from PaddleOCR. Note that this model has limitations regarding punctuation, English, numbers, and vertical text recognition. ```python from cnocr import CnOcr img_fp = './docs/examples/fanti.jpg' ocr = CnOcr(rec_model_name='chinese_cht_PP-OCRv3') # use the traditional Chinese recognition model out = ocr.ocr(img_fp) print(out) ``` -------------------------------- ### POST /ocr Source: https://context7.com/breezedeus/cnocr/llms.txt Endpoint for submitting an image file to the CnOCR server for text recognition. ```APIDOC ## POST /ocr ### Description Performs OCR on the provided image file and returns the recognized text lines with their respective confidence scores and coordinates. ### Method POST ### Endpoint /ocr ### Parameters #### Request Body - **image** (file) - Required - The image file to be processed (e.g., image/jpeg, image/png). ### Request Example curl -F image=@./document.jpg http://localhost:8501/ocr ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code. - **results** (array) - List of recognized text objects. - **text** (string) - The recognized string. - **score** (float) - Confidence score of the recognition. - **position** (array) - Bounding box coordinates [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]. #### Response Example { "status_code": 200, "results": [ { "text": "第一行文字", "score": 0.95, "position": [[0,0], [100,0], [100,20], [0,20]] } ] } ``` -------------------------------- ### POST /ocr_for_single_line Source: https://context7.com/breezedeus/cnocr/llms.txt Performs fast recognition on images known to contain only a single line of text. ```APIDOC ## POST /ocr_for_single_line ### Description Skips detection and performs direct recognition on a single-line image, offering significantly higher performance. ### Method POST ### Endpoint /ocr_for_single_line ### Parameters #### Request Body - **image** (file/binary) - Required - The single-line image to process. ### Request Example { "image": "./line.jpg" } ### Response #### Success Response (200) - **text** (string) - The recognized text. - **score** (float) - Confidence score. #### Response Example { "text": "单行文字", "score": 0.99 } ``` -------------------------------- ### Typographic Screenshot Image Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This code snippet shows how to configure CnOCR for recognizing simple typographic text images, such as screenshots or scanned documents, by using the 'naive_det' model. This mode bypasses a dedicated text detection model for faster processing, suitable for images where text is clearly laid out. ```python from cnocr import CnOcr img_fp = './docs/examples/multi-line_cn1.png' ocr = CnOcr(det_model_name='naive_det') out = ocr.ocr(img_fp) print(out) ``` -------------------------------- ### Single Line Text Image Recognition with CnOCR Source: https://github.com/breezedeus/cnocr/blob/master/README_en.md This code snippet shows an optimized method for recognizing single-line text images using CnOCR's `ocr_for_single_line()` function. This approach bypasses the text detection step, significantly speeding up the recognition process for images containing only one line of text. ```python from cnocr import CnOcr img_fp = './docs/examples/helloworld.jpg' ocr = CnOcr() out = ocr.ocr_for_single_line(img_fp) print(out) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.