Spaces:
Runtime error
Runtime error
File size: 19,049 Bytes
db5855f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "0293f65e",
"metadata": {},
"source": [
"# Handwritten Chinese and Japanese OCR with OpenVINO™\n",
"\n",
"In this tutorial, we perform optical character recognition (OCR) for handwritten Chinese (simplified) and Japanese. An OCR tutorial using the Latin alphabet is available in [notebook 208](../optical-character-recognition/optical-character-recognition.ipynb). This model is capable of processing only one line of symbols at a time.\n",
"\n",
"The models used in this notebook are [`handwritten-japanese-recognition-0001`](https://docs.openvino.ai/2024/omz_models_model_handwritten_japanese_recognition_0001.html) and [`handwritten-simplified-chinese-0001`](https://docs.openvino.ai/2024/omz_models_model_handwritten_simplified_chinese_recognition_0001.html). To decode model outputs as readable text [`kondate_nakayosi`](https://github.com/openvinotoolkit/open_model_zoo/blob/master/data/dataset_classes/kondate_nakayosi.txt) and [`scut_ept`](https://github.com/openvinotoolkit/open_model_zoo/blob/master/data/dataset_classes/scut_ept.txt) charlists are used. Both models are available on [Open Model Zoo](https://github.com/openvinotoolkit/open_model_zoo/).\n",
"\n",
"\n",
"#### Table of contents:\n",
"\n",
"- [Imports](#Imports)\n",
"- [Settings](#Settings)\n",
"- [Select a Language](#Select-a-Language)\n",
"- [Download the Model](#Download-the-Model)\n",
"- [Load the Model and Execute](#Load-the-Model-and-Execute)\n",
"- [Select inference device](#Select-inference-device)\n",
"- [Fetch Information About Input and Output Layers](#Fetch-Information-About-Input-and-Output-Layers)\n",
"- [Load an Image](#Load-an-Image)\n",
"- [Visualize Input Image](#Visualize-Input-Image)\n",
"- [Prepare Charlist](#Prepare-Charlist)\n",
"- [Run Inference](#Run-Inference)\n",
"- [Process the Output Data](#Process-the-Output-Data)\n",
"- [Print the Output](#Print-the-Output)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "b2642605",
"metadata": {},
"outputs": [],
"source": [
"import platform\n",
"\n",
"# Install openvino-dev package\n",
"%pip install -q \"openvino>=2023.1.0\" opencv-python tqdm\n",
"\n",
"if platform.system() != \"Windows\":\n",
" %pip install -q \"matplotlib>=3.4\"\n",
"else:\n",
" %pip install -q \"matplotlib>=3.4,<3.7\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "fda2e1e0",
"metadata": {},
"source": [
"## Imports\n",
"[back to top ⬆️](#Table-of-contents:)\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e0a6a0d5",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"from collections import namedtuple\n",
"from itertools import groupby\n",
"\n",
"import cv2\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import openvino as ov\n",
"\n",
"# Fetch `notebook_utils` module\n",
"import requests\n",
"\n",
"r = requests.get(\n",
" url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
")\n",
"\n",
"open(\"notebook_utils.py\", \"w\").write(r.text)\n",
"from notebook_utils import download_file"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "7a46517a",
"metadata": {},
"source": [
"## Settings\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Set up all constants and folders used in this notebook"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b50b2bad",
"metadata": {},
"outputs": [],
"source": [
"# Directories where data will be placed.\n",
"base_models_dir = \"models\"\n",
"data_folder = \"data\"\n",
"charlist_folder = f\"{data_folder}/text\"\n",
"\n",
"# Precision used by the model.\n",
"precision = \"FP16\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "f3c93fed",
"metadata": {},
"source": [
"To group files, you have to define the collection. In this case, use `namedtuple`."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "17402fcc",
"metadata": {},
"outputs": [],
"source": [
"Language = namedtuple(typename=\"Language\", field_names=[\"model_name\", \"charlist_name\", \"demo_image_name\"])\n",
"chinese_files = Language(\n",
" model_name=\"handwritten-simplified-chinese-recognition-0001\",\n",
" charlist_name=\"chinese_charlist.txt\",\n",
" demo_image_name=\"handwritten_chinese_test.jpg\",\n",
")\n",
"japanese_files = Language(\n",
" model_name=\"handwritten-japanese-recognition-0001\",\n",
" charlist_name=\"japanese_charlist.txt\",\n",
" demo_image_name=\"handwritten_japanese_test.png\",\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "8c61827c",
"metadata": {},
"source": [
"## Select a Language\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Depending on your choice you will need to change a line of code in the cell below.\n",
"\n",
"If you want to perform OCR on a text in Japanese, set `language = \"japanese\"`. For Chinese, set `language = \"chinese\"`."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "1d3b1190",
"metadata": {},
"outputs": [],
"source": [
"# Select the language by using either language=\"chinese\" or language=\"japanese\".\n",
"language = \"chinese\"\n",
"\n",
"languages = {\"chinese\": chinese_files, \"japanese\": japanese_files}\n",
"\n",
"selected_language = languages.get(language)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "750355d4",
"metadata": {},
"source": [
"## Download the Model\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"In addition to images and charlists, you need to download the model file. In the sections below, there are cells for downloading either the Chinese or Japanese model.\n",
" \n",
"If it is your first time running the notebook, the model will be downloaded. It may take a few minutes. \n",
"\n",
"Use `download_file` function from the utils package, which automatically creates a directory structure and downloads the selected model file. "
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "e8f266fa",
"metadata": {},
"outputs": [],
"source": [
"path_to_model = download_file(\n",
" url=f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2023.0/models_bin/1/{selected_language.model_name}/{precision}/{selected_language.model_name}.xml\",\n",
" directory=base_models_dir,\n",
")\n",
"_ = download_file(\n",
" url=f\"https://storage.openvinotoolkit.org/repositories/open_model_zoo/2023.0/models_bin/1/{selected_language.model_name}/{precision}/{selected_language.model_name}.bin\",\n",
" directory=base_models_dir,\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "6d026308",
"metadata": {},
"source": [
"## Load the Model and Execute\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"When all files are downloaded and language is selected, read and compile the network to run inference. The path to the model is defined based on the selected language."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7114e467",
"metadata": {
"collapsed": false,
"jupyter": {
"outputs_hidden": false
},
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [],
"source": [
"core = ov.Core()\n",
"model = core.read_model(model=path_to_model)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "9ecb4551",
"metadata": {},
"source": [
"## Select inference device\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"select device from dropdown list for running inference using OpenVINO"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "aaef9cca-de02-49b3-9544-d1c9cfce7792",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d80e65b78ae44972b9f64e84f91c7fae",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Dropdown(description='Device:', index=2, options=('CPU', 'GPU', 'AUTO'), value='AUTO')"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import ipywidgets as widgets\n",
"\n",
"device = widgets.Dropdown(\n",
" options=core.available_devices + [\"AUTO\"],\n",
" value=\"AUTO\",\n",
" description=\"Device:\",\n",
" disabled=False,\n",
")\n",
"\n",
"device"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "024ad3a4",
"metadata": {},
"outputs": [],
"source": [
"compiled_model = core.compile_model(model=model, device_name=device.value)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "3df5b652",
"metadata": {},
"source": [
"## Fetch Information About Input and Output Layers\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Now that the model is loaded, fetch information about the input and output layers (shape)."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "7d31411a",
"metadata": {},
"outputs": [],
"source": [
"recognition_output_layer = compiled_model.output(0)\n",
"recognition_input_layer = compiled_model.input(0)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "41307bc7",
"metadata": {},
"source": [
"## Load an Image\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Next, load an image. The model expects a single-channel image as input, so the image is read in grayscale.\n",
"\n",
"After loading the input image, get information to use for calculating the scale ratio between required input layer height and the current image height. In the cell below, the image will be resized and padded to keep letters proportional and meet input shape."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "afa1d51a",
"metadata": {},
"outputs": [],
"source": [
"# Download the image from the openvino_notebooks storage based on the selected model.\n",
"file_name = download_file(\n",
" \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/image/\" + selected_language.demo_image_name,\n",
" directory=data_folder,\n",
")\n",
"\n",
"# Text detection models expect an image in grayscale format.\n",
"# IMPORTANT! This model enables reading only one line at time.\n",
"\n",
"# Read the image.\n",
"image = cv2.imread(filename=str(file_name), flags=cv2.IMREAD_GRAYSCALE)\n",
"\n",
"# Fetch the shape.\n",
"image_height, _ = image.shape\n",
"\n",
"# B,C,H,W = batch size, number of channels, height, width.\n",
"_, _, H, W = recognition_input_layer.shape\n",
"\n",
"# Calculate scale ratio between the input shape height and image height to resize the image.\n",
"scale_ratio = H / image_height\n",
"\n",
"# Resize the image to expected input sizes.\n",
"resized_image = cv2.resize(image, None, fx=scale_ratio, fy=scale_ratio, interpolation=cv2.INTER_AREA)\n",
"\n",
"# Pad the image to match input size, without changing aspect ratio.\n",
"resized_image = np.pad(resized_image, ((0, 0), (0, W - resized_image.shape[1])), mode=\"edge\")\n",
"\n",
"# Reshape to network input shape.\n",
"input_image = resized_image[None, None, :, :]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "ba364bee",
"metadata": {},
"source": [
"## Visualize Input Image\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"After preprocessing, you can display the image."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "f7a8e437",
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(20, 1))\n",
"plt.axis(\"off\")\n",
"plt.imshow(resized_image, cmap=\"gray\", vmin=0, vmax=255);"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "c6d4c642",
"metadata": {},
"source": [
"## Prepare Charlist\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"The model is loaded and the image is ready. The only element left is the charlist, which is downloaded. You must add a blank symbol at the beginning of the charlist before using it. This is expected for both the Chinese and Japanese models."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8e35eae1",
"metadata": {},
"outputs": [],
"source": [
"# Download the image from the openvino_notebooks storage based on the selected model.\n",
"used_charlist_file = download_file(\n",
" \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/text/\" + selected_language.charlist_name,\n",
" directory=charlist_folder,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "2cb18186",
"metadata": {},
"outputs": [],
"source": [
"# Get a dictionary to encode the output, based on model documentation.\n",
"used_charlist = selected_language.charlist_name\n",
"\n",
"# With both models, there should be blank symbol added at index 0 of each charlist.\n",
"blank_char = \"~\"\n",
"\n",
"with used_charlist_file.open(mode=\"r\", encoding=\"utf-8\") as charlist:\n",
" letters = blank_char + \"\".join(line.strip() for line in charlist)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "b6a4da65",
"metadata": {},
"source": [
"## Run Inference\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Now, run inference. The `compiled_model()` function takes a list with input(s) in the same order as model input(s). Then, fetch the output from output tensors.\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "e44a9de4",
"metadata": {},
"outputs": [],
"source": [
"# Run inference on the model\n",
"predictions = compiled_model([input_image])[recognition_output_layer]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "03a40d22",
"metadata": {},
"source": [
"## Process the Output Data\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"The output of a model is in the `W x B x L` format, where:\n",
"\n",
"* W - output sequence length\n",
"* B - batch size\n",
"* L - confidence distribution across the supported symbols in Kondate and Nakayosi.\n",
"\n",
"To get a more human-readable format, select a symbol with the highest probability. When you hold a list of indexes that are predicted to have the highest probability, due to limitations in [CTC Decoding](https://towardsdatascience.com/beam-search-decoding-in-ctc-trained-neural-networks-5a889a3d85a7), you will remove concurrent symbols and then remove the blanks.\n",
"\n",
"Finally, get the symbols from corresponding indexes in the charlist."
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "da1b8bc5",
"metadata": {},
"outputs": [],
"source": [
"# Remove a batch dimension.\n",
"predictions = np.squeeze(predictions)\n",
"\n",
"# Run the `argmax` function to pick the symbols with the highest probability.\n",
"predictions_indexes = np.argmax(predictions, axis=1)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "f6730159",
"metadata": {},
"outputs": [],
"source": [
"# Use the `groupby` function to remove concurrent letters, as required by CTC greedy decoding.\n",
"output_text_indexes = list(groupby(predictions_indexes))\n",
"\n",
"# Remove grouper objects.\n",
"output_text_indexes, _ = np.transpose(output_text_indexes, (1, 0))\n",
"\n",
"# Remove blank symbols.\n",
"output_text_indexes = output_text_indexes[output_text_indexes != 0]\n",
"\n",
"# Assign letters to indexes from the output array.\n",
"output_text = [letters[letter_index] for letter_index in output_text_indexes]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "ac88f622",
"metadata": {},
"source": [
"## Print the Output\n",
"[back to top ⬆️](#Table-of-contents:)\n",
"\n",
"Now, having a list of letters predicted by the model, you can display the image with predicted text printed below."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "6f8a90f3",
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(20, 1))\n",
"plt.axis(\"off\")\n",
"plt.imshow(resized_image, cmap=\"gray\", vmin=0, vmax=255)\n",
"\n",
"print(\"\".join(output_text))"
]
}
],
"metadata": {
"interpreter": {
"hash": "ae617ccb002f72b3ab6d0069d721eac67ac2a969e83c083c4321cfcab0437cd1"
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
},
"openvino_notebooks": {
"imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/notebooks/handwritten-ocr/handwritten-ocr.png?raw=true",
"tags": {
"categories": [
"Model Demos"
],
"libraries": [],
"other": [],
"tasks": [
"Image-to-Text"
]
}
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|