Giter VIP home page Giter VIP logo

nomeroff-net's Introduction

Nomeroff Net

Nomeroff Net. Automatic numberplate recognition system

Nomeroff Net. Automatic numberplate recognition system. Version 3.5.0

Now there is a war going on in our country, russian soldiers are shooting at civilians in Ukraine. Enemy aviation launches rockets and drops bombs on residential quarters.
We are deeply thankful for the unprecedented wave of support for Ukraine from around the world. Below is a list of funds that help the Ukrainian army in the fight against Russian invaders: Russian troops shelling of civilians in Ukraine. Donbass. Kostyantynivka. 09.07.2022 Photo: Konstantin Liberov https://www.instagram.com/libkos/

Introduction

Nomeroff Net is an opensource python license plate recognition framework based on YOLOv5 and CRAFT networks and customized OCR-module powered by RNN architecture.

Write to us if you are interested in helping us in the formation of a dataset for your country.

Change History.

Installation

Installation from Source (Linux)

Nomeroff Net requires Python >= 3.7

Clone Project

git clone https://github.com/ria-com/nomeroff-net.git
cd nomeroff-net

For Centos, Fedora and other RedHat-like OS:

# for Opencv
yum install libSM

# for pycocotools install 
yum install python3-devel 

# ensure that you have installed gcc compiler
yum install gcc

yum install git

# Before "yum install ..." download https://libjpeg-turbo.org/pmwiki/uploads/Downloads/libjpeg-turbo.repo to /etc/yum.repos.d/
yum install libjpeg-turbo-official

install requirements:

pip3 install -r requirements.txt 

For Ubuntu and other Debian-like OS:

# ensure that you have installed gcc compiler
apt-get install gcc

# for opencv install
apt-get install -y libglib2.0
apt-get install -y libgl1-mesa-glx

# for pycocotools install (Check the name of the dev-package for your python3)
apt-get install python3.7-dev

# other packages
apt-get install -y git
apt-get install -y libturbojpeg

install requirements:

pip3 install -r requirements.txt 

Hello Nomeroff Net

from nomeroff_net import pipeline
from nomeroff_net.tools import unzip

number_plate_detection_and_reading = pipeline("number_plate_detection_and_reading", 
                                              image_loader="opencv")

(images, images_bboxs, 
 images_points, images_zones, region_ids, 
 region_names, count_lines, 
 confidences, texts) = unzip(number_plate_detection_and_reading(['./data/examples/oneline_images/example1.jpeg', 
                                                                 './data/examples/oneline_images/example2.jpeg']))
 
print(texts)

Hello Nomeroff Net for systems with a small GPU size.

Note: This example disables some important Nomeroff Net features. It will recognize numbers that are photographed in a horizontal position.

from nomeroff_net import pipeline
from nomeroff_net.tools import unzip

number_plate_detection_and_reading = pipeline("number_plate_short_detection_and_reading", 
                                              image_loader="opencv")

(images, images_bboxs,
 zones, texts) = unzip(number_plate_detection_and_reading(['./data/examples/oneline_images/example1.jpeg', 
                                                           './data/examples/oneline_images/example2.jpeg']))
 
print(texts)
# (['AC4921CB'], ['RP70012', 'JJF509'])


More Examples

Nomeroff Net Professional

If you don't want to install and configure the Nomeroff Net programmed code for your own tasks or if your client hardware does not have enough resources to run a service that requires ML computing, you can use our commercial API Nomeroff Net Professional, which allows you to perform recognition remotely on the RIA.com Сompany servers.

The Nomeroff Net Professional API is based on the open source Nomeroff Net engine, with commercial modifications aimed mainly at using improved models that can produce better results in photos with poor image quality.

Right now you can try ALPR/ANPR Nomeroff Net Professional Demo for free.

Online Demo

In order to evaluate the quality of work of Nomeroff Net without spending time on setting up and installing, we made an online form in which you can upload your photo and get the recognition result online

AUTO.RIA Numberplate Dataset

All data on the basis of which the training was conducted is provided by RIA.com. In the following, we will call this data the AUTO.RIA Numberplate Dataset.

We will be grateful for your help in the formation and layout of the dataset with the image of the license plates of your country. For markup, we recommend using VGG Image Annotator (VIA)

Dataset Example: Nomeroff-Net Segment Example

AUTO.RIA Numberplate Options Dataset

The system uses several neural networks. One of them is the classifier of numbers at the post-processing stage. It uses dataset AUTO.RIA Numberplate Options Dataset.

The categorizer accurately (99%) determines the country and the type of license plate. Please note that now the classifier is configured mainly for the definition of Ukrainian numbers, for other countries it will be necessary to train the classifier with new data.

Nomeroff-Net OCR Example

AUTO.RIA Numberplate OCR Datasets

As OCR, we use a specialized implementation of a neural network with RNN layers, for which we have created several datasets:

If we did not manage to update the link on dataset you can find the latest version here

This gives you the opportunity to get 99% accuracyon photos that are uploaded to AUTO.RIA project

Nomeroff-Net OCR Example

Contributing

Contributions to this repository are welcome. Examples of things you can contribute:

  • Training on other datasets.
  • Accuracy Improvements.

Credits

Links

nomeroff-net's People

Contributors

andrmist avatar apelsyn avatar azimovs avatar dependabot[bot] avatar dimabendera avatar rm-yakovenko avatar serhii-hladiholov avatar workoverflow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nomeroff-net's Issues

Не получается обернуть код через Flask, прошу помощи.

Друзья, день добрый!

Пытаюсь обернуть ваш код через Flask. Что бы выбор файла картинки был через веб.
В питоне не особо силен, помогите если не сложно разобраться со следующей проблемой:

Собственно сам код:

import os
import numpy as np
import sys
import matplotlib.image as mpimg

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
NOMEROFF_NET_DIR = os.path.abspath('../../')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

MASK_RCNN_DIR = os.path.join(NOMEROFF_NET_DIR, 'Mask_RCNN')
MASK_RCNN_LOG_DIR = os.path.join(NOMEROFF_NET_DIR, 'logs')

sys.path.append(NOMEROFF_NET_DIR)

from flask import Flask, render_template, request, url_for
from werkzeug.utils import secure_filename
from NomeroffNet import  filters, RectDetector, TextDetector, OptionsDetector, Detector, textPostprocessing, textPostprocessingAsync

nnet = Detector(MASK_RCNN_DIR, MASK_RCNN_LOG_DIR)
nnet.loadModel("latest")

rectDetector = RectDetector()
optionsDetector = OptionsDetector()
optionsDetector.load("latest")
textDetector = TextDetector.get_static_module("eu")()
textDetector.load("latest")


app = Flask(__name__)


@app.route("/", methods=["POST", "GET"])
def index():
    if request.method == "POST":
        file = request.files["file"]
        if file and (file.content_type.rsplit('/', 1)[1] in ALLOWED_EXTENSIONS).__bool__():
            filename = secure_filename(file.filename)
            file.save(NOMEROFF_NET_DIR + '/examples/images/' + filename)
            imgPath = (NOMEROFF_NET_DIR + '/examples/images/' +  filename)
            img = mpimg.imread(imgPath)
            NP = nnet.detect([img])
            cv_img_masks = filters.cv_img_mask(NP)
            arrPoints = rectDetector.detect(cv_img_masks)
            zones = rectDetector.get_cv_zonesBGR(img, arrPoints)
            regionIds, stateIds, countLines = optionsDetector.predict(zones)
            regionNames = optionsDetector.getRegionLabels(regionIds)
            textArr = textDetector.predict(zones)
            textArr = textPostprocessing(textArr, regionNames)
            print(textArr)
    return render_template("index.html")


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)


После выбора файла и загрузки через веб, вылетает следующее:

 * Serving Flask app "site" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
10.10.77.200 - - [04/Mar/2020 10:07:28] "GET / HTTP/1.1" 200 -
[2020-03-04 10:07:32,699] ERROR in app: Exception on / [POST]
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/src/nomeroff-net/examples/py/site.py", line 43, in index
    NP = nnet.detect([img])
  File "/usr/src/nomeroff-net/NomeroffNet/Detector.py", line 98, in detect
    return self.MODEL.detect(self.normalize(images), verbose=verbose)
  File "/usr/src/nomeroff-net/Mask_RCNN/mrcnn/model.py", line 2524, in detect
    self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)
  File "/usr/local/lib/python3.6/dist-packages/keras/engine/training.py", line 1395, in predict
    self._make_predict_function()
  File "/usr/local/lib/python3.6/dist-packages/keras/engine/training.py", line 557, in _make_predict_function
    **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py", line 3010, in function
    return Function(inputs, outputs, updates=updates, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py", line 2808, in __init__
    with tf.control_dependencies(self.outputs):
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 5426, in control_dependencies
    return get_default_graph().control_dependencies(control_inputs)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 4867, in control_dependencies
    c = self.as_graph_element(c)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3796, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3875, in _as_graph_element_locked
    raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("mrcnn_detection/Reshape_1:0", shape=(1, 100, 6), dtype=float32) is not an element of this graph.
10.10.77.200 - - [04/Mar/2020 10:07:32] "POST / HTTP/1.1" 500 -

В чем может быть проблема, ткните пожалуйста носом куда копать?

Error demo3.py

Hello

I am have error, when I want running script demo3.py
Path: ~/examples/py/demo3.py

$ python demo3.py
File "demo3.py", line 78
cv_img_masks = await filters.cv_img_mask_async(NP)

I am using python v3.6
Can you help me with solve this problem?

bad accuracy

this model need to be retrained even with ukrainian plates

Error: Run on GPU

Hi Team

I have problem with run model on GPU. When I running script:
`import os
import cv2
import numpy as np
import sys
import json
import matplotlib.image as mpimg
import warnings
warnings.filterwarnings('ignore')

change this property

NOMEROFF_NET_DIR = os.path.abspath('../../')

specify the path to Mask_RCNN if you placed it outside Nomeroff-net project

MASK_RCNN_DIR = os.path.join(NOMEROFF_NET_DIR, 'Mask_RCNN')

MASK_RCNN_LOG_DIR = os.path.join(NOMEROFF_NET_DIR, 'logs')
MASK_RCNN_MODEL_PATH = os.path.join(NOMEROFF_NET_DIR, "models/mask_rcnn_numberplate_0700.h5")
OPTIONS_MODEL_PATH = os.path.join(NOMEROFF_NET_DIR, "models/numberplate_options_2019_06_27.h5")

If you use gpu version tensorflow please change model to gpu version named like *-gpu.pb

#mode = "cpu" if "NN_MODE" not in os.environ else os.environ["NN_MODE"] if os.environ["NN_MODE"]=="gpu" else "cpu"
mode = "gpu"
OCR_NP_UKR_TEXT = os.path.join(NOMEROFF_NET_DIR, "models/anpr_ocr_ua_12-{}.h5".format(mode))
OCR_NP_EU_TEXT = os.path.join(NOMEROFF_NET_DIR, "models/anpr_ocr_eu_2-{}.h5".format(mode))
OCR_NP_RU_TEXT = os.path.join(NOMEROFF_NET_DIR, "models/anpr_ocr_ru_3-{}.h5".format(mode))

sys.path.append(NOMEROFF_NET_DIR)

Import license plate recognition tools.

from NomeroffNet import filters, RectDetector, TextDetector, OptionsDetector, Detector, textPostprocessing, textPostprocessing

Initialize npdetector with default configuration file.

nnet = Detector(MASK_RCNN_DIR, MASK_RCNN_LOG_DIR)
nnet.loadModel(MASK_RCNN_MODEL_PATH)

rectDetector = RectDetector()

optionsDetector = OptionsDetector()
optionsDetector.load(OPTIONS_MODEL_PATH)

Initialize text detector.

textDetector = TextDetector({
"eu_ua_2004_2015": {
"for_regions": ["eu_ua_2015", "eu_ua_2004"],
"model_path": OCR_NP_UKR_TEXT
},
"eu": {
"for_regions": ["eu", "eu_ua_1995"],
"model_path": OCR_NP_EU_TEXT
},
"ru": {
"for_regions": ["ru"],
"model_path": OCR_NP_RU_TEXT
}
})

Walking through the ./examples/images/ directory and checking each of the images for license plates.

rootDir = '../../images/'

max_img_w = 1600
for dirName, subdirList, fileList in os.walk(rootDir):
for fname in fileList:
img_path = os.path.join(dirName, fname)
print(img_path)
img = mpimg.imread(img_path)

    # corect size for better speed
    img_w = img.shape[1]
    img_h = img.shape[0]
    img_w_r = 1
    img_h_r = 1
    if img_w > max_img_w:
        resized_img = cv2.resize(img, (max_img_w, int(max_img_w/img_w*img_h)))
        img_w_r = img_w/max_img_w
        img_h_r = img_h/(max_img_w/img_w*img_h)
    else:
        resized_img = img

    NP = nnet.detect([resized_img])

    # Generate image mask.
    cv_img_masks = filters.cv_img_mask(NP)

    # Detect points.
    arrPoints = rectDetector.detect(cv_img_masks, outboundHeightOffset=3-img_w_r)

print(arrPoints)

    arrPoints[..., 1:2] = arrPoints[..., 1:2]*img_h_r
    arrPoints[..., 0:1] = arrPoints[..., 0:1]*img_w_r

    # cut zones
    zones = rectDetector.get_cv_zonesBGR(img, arrPoints)

    # find standart
    regionIds, stateIds, countLines = optionsDetector.predict(zones)
    regionNames = optionsDetector.getRegionLabels(regionIds)
    print(regionNames)

    # find text with postprocessing by standart
    textArr = textDetector.predict(zones, regionNames)
    textArr = textPostprocessing(textArr, regionNames)
    print(textArr)`

with mode = "gpu", I am get error:

`Traceback (most recent call last):
File "test.py", line 54, in
"model_path": OCR_NP_RU_TEXT
File "/home/ubuntu/nomeroff-net/NomeroffNet/TextDetector.py", line 37, in init
detector.load(priset['model_path'])
File "/home/ubuntu/nomeroff-net/NomeroffNet/Base/OCR.py", line 190, in load
self.MODEL = load_model(path_to_model, compile=False)
File "/home/ubuntu/.local/lib/python3.6/site-packages/keras/engine/saving.py", line 419, in load_model
model = _deserialize_model(f, custom_objects, compile)
File "/home/ubuntu/.local/lib/python3.6/site-packages/keras/engine/saving.py", line 287, in _deserialize_model
K.batch_set_value(weight_value_tuples)
File "/home/ubuntu/.local/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2470, in batch_set_value
get_session().run(assign_ops, feed_dict=feed_dict)
File "/home/ubuntu/.local/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 199, in get_session
[tf.is_variable_initialized(v) for v in candidate_vars])
File "/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 950, in run
run_metadata_ptr)
File "/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1173, in _run
feed_dict_tensor, options, run_metadata)
File "/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1350, in _do_run
run_metadata)
File "/home/ubuntu/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1370, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: No OpKernel was registered to support Op 'CudnnRNN' used by node gru1/CudnnRNN (defined at /home/ubuntu/.local/lib/python3.6/site-packages/keras/layers/cudnn_recurrent.py:297) with these attrs: [T=DT_FLOAT, input_mode="linear_input", direction="unidirectional", rnn_mode="gru", is_training=true, seed2=0, dropout=0, seed=87654321]
Registered devices: [CPU, XLA_CPU]
Registered kernels:

 [[gru1/CudnnRNN]]

Errors may have originated from an input operation.
Input Source operations connected to node gru1/CudnnRNN:
gru1/ExpandDims_1 (defined at /home/ubuntu/.local/lib/python3.6/site-packages/keras/layers/cudnn_recurrent.py:273)
gru1/concat (defined at /home/ubuntu/.local/lib/python3.6/site-packages/keras/layers/cudnn_recurrent.py:60)
gru1/transpose (defined at /home/ubuntu/.local/lib/python3.6/site-packages/keras/layers/cudnn_recurrent.py:271)`

Help me please, for solve this problem...

Ошибка list index out of range при вызове model = numberClassificator.train(LOG_DIR, cnn="simple")

Добрый день,
пытаюсь выполнить скрипт options.ipynb, но получаю ошибку IndexError: list index out of range. Подскажите, пожалуйста, в чем проблема. Заранее благодарен.

Прилагаю скрипт с ошибкой.

Python 3.6.9
tensorflow (14)
keras 2.2.4
GPU нет, запускаю на ноутбуке.
options.zip

Недопустимая инструкция

В чем может быть проблема, устанавливал по инструкции

root@Server:nomeroff-net/examples/py# python3 demo0.py
Недопустимая инструкция
root@Server:nomeroff-net/examples/py# uname -a
Linux Server 5.3.0-kali2-amd64 #1 SMP Debian 5.3.9-3kali1 (2019-11-20) x86_64 GNU/Linux

Проблема с mrcnn_train.py

Доброго времени суток!
Файл модели не создался:
ошибка:

    f = h5py.File(filepath, mode='r')
  File "/usr/local/lib/python3.6/site-packages/h5py/_hl/files.py", line 408, in __init__
    swmr=swmr)
  File "/usr/local/lib/python3.6/site-packages/h5py/_hl/files.py", line 173, in make_fid
    fid = h5f.open(name, flags, fapl=fapl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5f.pyx", line 88, in h5py.h5f.open
OSError: Unable to open file (unable to open file: name = '//nomeroff-net/models/numberplate_mrcnn_2019_11_25.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0)

Код по которому тренировал.

import os
import cv2
import numpy as np
import sys
import json
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore')

NOMEROFF_NET_DIR = os.path.abspath('../../')
sys.path.append(NOMEROFF_NET_DIR)

# specify the path to Mask_RCNN if you placed it outside Nomeroff-net project
MASK_RCNN_DIR = os.path.join(NOMEROFF_NET_DIR, 'Mask_RCNN')
MASK_RCNN_LOG_DIR = os.path.join(NOMEROFF_NET_DIR, "logs")

DATASET_NAME = "mrcnn"
VERSION = "2019_11_25"
MASK_RCNN_FROZEN_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.pb'.format(DATASET_NAME, VERSION))

# Import license plate recognition tools.
from NomeroffNet import  Detector
from NomeroffNet.Base import convert_keras_to_freeze_pb

CONFIG = {
    "GPU_COUNT": 1,
    "IMAGES_PER_GPU": 1,
    "WEIGHTS": "coco",
    "EPOCHS": 100,
    "CLASS_NAMES": ["BG", "numberplate"],
    "NAME": "numberplate",
    "DATASET_DIR": "/nomeroff-net/datasets/mrcnn",
    "LAYERS": "all",
    "NUM_CLASSES": 2
}

# Initialize npdetector with default configuration file.
nnet = Detector(MASK_RCNN_DIR, MASK_RCNN_LOG_DIR, CONFIG)

nnet.train()
#nnet.loadModel(MASK_RCNN_MODEL_PATH)

import keras
keras.backend.clear_session()
nnet.loadModel("/nomeroff-net/models/numberplate_mrcnn_2019_11_25.h5")
model = nnet.getKerasModel()
convert_keras_to_freeze_pb(model,MASK_RCNN_FROZEN_PATH)

в /nomeroff-net/logs/numberplate20191201T0858 есть некие файлы:

events.out.tfevents.1575180012.asrv247  mask_rcnn_numberplate_0021.h5  mask_rcnn_numberplate_0042.h5  mask_rcnn_numberplate_0063.h5  mask_rcnn_numberplate_0084.h5
mask_rcnn_numberplate_0001.h5           mask_rcnn_numberplate_0022.h5  mask_rcnn_numberplate_0043.h5  mask_rcnn_numberplate_0064.h5  mask_rcnn_numberplate_0085.h5
mask_rcnn_numberplate_0002.h5           mask_rcnn_numberplate_0023.h5  mask_rcnn_numberplate_0044.h5  mask_rcnn_numberplate_0065.h5  mask_rcnn_numberplate_0086.h5
mask_rcnn_numberplate_0003.h5           mask_rcnn_numberplate_0024.h5  mask_rcnn_numberplate_0045.h5  mask_rcnn_numberplate_0066.h5  mask_rcnn_numberplate_0087.h5
mask_rcnn_numberplate_0004.h5           mask_rcnn_numberplate_0025.h5  mask_rcnn_numberplate_0046.h5  mask_rcnn_numberplate_0067.h5  mask_rcnn_numberplate_0088.h5
mask_rcnn_numberplate_0005.h5           mask_rcnn_numberplate_0026.h5  mask_rcnn_numberplate_0047.h5  mask_rcnn_numberplate_0068.h5  mask_rcnn_numberplate_0089.h5
mask_rcnn_numberplate_0006.h5           mask_rcnn_numberplate_0027.h5  mask_rcnn_numberplate_0048.h5  mask_rcnn_numberplate_0069.h5  mask_rcnn_numberplate_0090.h5
mask_rcnn_numberplate_0007.h5           mask_rcnn_numberplate_0028.h5  mask_rcnn_numberplate_0049.h5  mask_rcnn_numberplate_0070.h5  mask_rcnn_numberplate_0091.h5
mask_rcnn_numberplate_0008.h5           mask_rcnn_numberplate_0029.h5  mask_rcnn_numberplate_0050.h5  mask_rcnn_numberplate_0071.h5  mask_rcnn_numberplate_0092.h5
mask_rcnn_numberplate_0009.h5           mask_rcnn_numberplate_0030.h5  mask_rcnn_numberplate_0051.h5  mask_rcnn_numberplate_0072.h5  mask_rcnn_numberplate_0093.h5
mask_rcnn_numberplate_0010.h5           mask_rcnn_numberplate_0031.h5  mask_rcnn_numberplate_0052.h5  mask_rcnn_numberplate_0073.h5  mask_rcnn_numberplate_0094.h5
mask_rcnn_numberplate_0011.h5           mask_rcnn_numberplate_0032.h5  mask_rcnn_numberplate_0053.h5  mask_rcnn_numberplate_0074.h5  mask_rcnn_numberplate_0095.h5
mask_rcnn_numberplate_0012.h5           mask_rcnn_numberplate_0033.h5  mask_rcnn_numberplate_0054.h5  mask_rcnn_numberplate_0075.h5  mask_rcnn_numberplate_0096.h5
mask_rcnn_numberplate_0013.h5           mask_rcnn_numberplate_0034.h5  mask_rcnn_numberplate_0055.h5  mask_rcnn_numberplate_0076.h5  mask_rcnn_numberplate_0097.h5
mask_rcnn_numberplate_0014.h5           mask_rcnn_numberplate_0035.h5  mask_rcnn_numberplate_0056.h5  mask_rcnn_numberplate_0077.h5  mask_rcnn_numberplate_0098.h5
mask_rcnn_numberplate_0015.h5           mask_rcnn_numberplate_0036.h5  mask_rcnn_numberplate_0057.h5  mask_rcnn_numberplate_0078.h5  mask_rcnn_numberplate_0099.h5
mask_rcnn_numberplate_0016.h5           mask_rcnn_numberplate_0037.h5  mask_rcnn_numberplate_0058.h5  mask_rcnn_numberplate_0079.h5  mask_rcnn_numberplate_0100.h5
mask_rcnn_numberplate_0017.h5           mask_rcnn_numberplate_0038.h5  mask_rcnn_numberplate_0059.h5  mask_rcnn_numberplate_0080.h5
mask_rcnn_numberplate_0018.h5           mask_rcnn_numberplate_0039.h5  mask_rcnn_numberplate_0060.h5  mask_rcnn_numberplate_0081.h5
mask_rcnn_numberplate_0019.h5           mask_rcnn_numberplate_0040.h5  mask_rcnn_numberplate_0061.h5  mask_rcnn_numberplate_0082.h5
mask_rcnn_numberplate_0020.h5           mask_rcnn_numberplate_0041.h5  mask_rcnn_numberplate_0062.h5  mask_rcnn_numberplate_0083.h5

Можно ли из этого собрать единый файл без повторной тренировки?

Проблема с точностью OCR для eu-ua-2015

Проблема с точностью OCR для украинских номеров eu-ua-2015

Проблема была замечена в демке https://nomeroff.net.ua/onlinedemo.html

С 2013 года появились новые номера с буквой К. Так например для киевского региона появились номера типа КА1234АА. При попытке распознать номера, точность падает до ~5% и почти всегда выдает “АА” вместо “КА”.
Попробовал уже много фотографий но результат тот же.

Вот для примера фото с интернета, чтобы попробовать:
numberK2

И результат демки:
result

В случаях где нету "К" в номере - работает очень хорошо (около 98% точности)

TextDetector from the image of LP

Если у меня есть фотка только номеров автомобиля, можно ли его как-то проверить на ваших алгоритмах? Просто ваш алгоритм не находит номера (из-за плохого качества картинки). Хотелось бы проверить как он определит текст, если будет только фотка номеров.

Здесь можно увидеть какие именно картинки были использованы
https://github.com/AzimovS/LPDetection/blob/master/demo3.ipynb

Ошибки при тесте

Когда хочу натренировать свою модель встречается такая проблема
image

Дальше я просто попытался протестить на вашей готовой модели Для удобства я загрузил только две фотки. Вот здесь можно увидеть
https://github.com/AzimovS/LPDetection/blob/master/ocr-kz.ipynb что в 5 блоке выходит та же ошибка.Можете подсказать из-за чего возникает данная ошибка?

TensorRT

Добрый день, Вы не пробовали оптимизировать ваши модели с помощью библиотеки TensorRT?

module 'numpy.random' has no attribute 'bit_generator'

При импорте модулей возникает ошибка

Traceback (most recent call last):
File "demo0.py", line 17, in
from NomeroffNet import filters, RectDetector, TextDetector, OptionsDetector, Detector, textPostprocessing, textPostprocessingAsync
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/examples/py/../../NomeroffNet/init.py", line 5, in
from .TextDetector import *
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/examples/py/../../NomeroffNet/TextDetector.py", line 4, in
import TextDetectors
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/TextDetectors/init.py", line 6, in
importlib.import_module(modname)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/importlib/init.py", line 127, in import_module
return bootstrap.gcd_import(name[level:], package, level)
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/TextDetectors/eu.py", line 1, in
from Base import OCR
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/Base/init.py", line 1, in
from .OCR import *
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/Base/OCR.py", line 26, in
from .TextImageGenerator import TextImageGenerator
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/Base/TextImageGenerator.py", line 9, in
from .aug import aug
File "/Users/caesarisme/Desktop/clr3/nomeroff-net/NomeroffNet/Base/aug.py", line 5, in
ia.seed(1)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/imgaug.py", line 502, in seed
imgaug.random.seed(entropy)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/random.py", line 762, in seed
seed_np117(entropy)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/random.py", line 770, in seed_np117
GLOBAL_RNG = RNG(entropy)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/random.py", line 142, in init
self.generator = normalize_generator
(generator)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/random.py", line 841, in normalize_generator

return normalize_generator_np117(generator)
File "/Users/caesarisme/Desktop/clr3/venv/lib/python3.7/site-packages/imgaug/random.py", line 851, in normalize_generator_np117
elif isinstance(generator, np.random.bit_generator.BitGenerator):
AttributeError: module 'numpy.random' has no attribute 'bit_generator'

об OCR

Добрый день. Это личный вопрос из интереса. Хотел узнать как OCR распознавание распознает символы? как он определяет в каком месте картинки какой символ? Как во время обучения обучается OCR разпознавалка? Как она определяет символы на картинке? Был бы очень рад, если вы расскажете по подробнее. Я хотел бы попробовать обучить вашу OCR модель на датасете рукописных текстов. Первый результат дал 75% точности на тестовых данных, но это пока не удовлетворительно. Благодарю за ответ.

How to train OCR?

How to train OCR?
Describe, please, each steps and all needed(images, json, how to run script and so on)
Thanks you.

Ошибка во время обучения своей ocr

Здравствуйте!
пытаюсь обучить свою ocr для русских номеров, используя файл ocr.py
разметила дополнительно номера через админку вдобавок к основному датасету, размечала на английском языке.
Во время запуска обучения появляется ошибка
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 79: invalid start byte
Пыталась изменить в файле OCR.py кодирование букв во время открытия json файлов. Тогда появляется ошибка в файле decode.

также в файле ocr.py класс настроен для украинских номеров, поменяла под российские.
Спасибо!

OSError: Unable to open file (file signature not found)

Доброго времени суток, возникла ошибка при попытке запустить demo:

Traceback (most recent call last): File "recognition.py", line 33, in <module> textDetector.load("/srv/nomeroff-net/models/anpr_ocr_eu_2-cpu.pb") File "/usr/local/lib/python3.6/dist-packages/NomeroffNet/Base/OCR.py", line 190, in load self.MODEL = load_model(path_to_model, compile=False) File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 458, in load_wrapper return load_function(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/keras/engine/saving.py", line 549, in load_model with H5Dict(filepath, mode='r') as h5dict: File "/usr/local/lib/python3.6/dist-packages/keras/utils/io_utils.py", line 191, in __init__ self.data = h5py.File(path, mode=mode) File "/usr/local/lib/python3.6/dist-packages/h5py/_hl/files.py", line 408, in __init__ swmr=swmr) File "/usr/local/lib/python3.6/dist-packages/h5py/_hl/files.py", line 173, in make_fid fid = h5f.open(name, flags, fapl=fapl) File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper File "h5py/h5f.pyx", line 88, in h5py.h5f.open OSError: Unable to open file (file signature not found)

пробовал различные файлы по указанной в документации ссылке https://nomeroff.net.ua/models/ocr/ и каждый выдаёт такую ошибку, подскажите пожалуйста, в чем может быть проблема?

Mask RCNN epochs

Добрый день! Сколько эпох использовали для тренировки?

Распознавание Казахских kz автомобильных номеров

Это продолжение ветки коментов Habra https://habr.com/ru/post/439330/#comment_20067900 о распознавании казахских номеров.
Так как мне пишут в личку стандартные вопросы и я отвечаю одни и те же ответы я решил сделать переписку в коментариях более структурированой.
Давайте на каждую новую тему создавать соответствующий issue и там вести диалог по теме пока мы ее не закроем.

Ошибка оучения mrcnn

Использовал этот dataset: https://nomeroff.net.ua/datasets/autoriaNumberplateDataset-2019-03-06.zip

Упала ошибка:

Traceback (most recent call last):
  File "m.py", line 41, in <module>
    nnet.train()
  File "/nomeroff-net/NomeroffNet/Detector.py", line 243, in train
    layers=self.CONFIG.LAYERS )
  File "/usr/local/lib/python3.6/site-packages/mrcnn/model.py", line 2374, in train
    use_multiprocessing=True,
  File "/usr/local/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/keras/engine/training.py", line 1658, in fit_generator
    initial_epoch=initial_epoch)
  File "/usr/local/lib/python3.6/site-packages/keras/engine/training_generator.py", line 181, in fit_generator
    generator_output = next(output_generator)
  File "/usr/local/lib/python3.6/site-packages/keras/utils/data_utils.py", line 733, in get
    six.reraise(*sys.exc_info())
  File "/.local/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/keras/utils/data_utils.py", line 702, in get
    inputs = future.get(timeout=30)
  File "/usr/local/lib/python3.6/multiprocessing/pool.py", line 608, in get
    raise self._value
IndexError: index 1159 is out of bounds for axis 1 with size 1080

Проблема с запуском demo3.py

При попытке запуска демо user@ubuntu:~/nomeroff-net/examples/py$ python3 demo3.py
возникает вот такая проблема:

2019-10-24 13:20:12.700437: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2019-10-24 13:20:12.764445: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 1992000000 Hz
2019-10-24 13:20:12.764839: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x1cb2810 executing computations on platform Host. Devices:
2019-10-24 13:20:12.764973: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): <undefined>, <undefined>
Using TensorFlow backend.
Traceback (most recent call last):
  File "demo3.py", line 20, in <module>
    from NomeroffNet import  filters, RectDetector, TextDetector, OptionsDetector, Detector, textPostprocessing, textPostprocessingAsync
  File "/home/user/nomeroff-net/examples/py/../../NomeroffNet/__init__.py", line 2, in <module>
    from .Detector import *
  File "/home/user/nomeroff-net/examples/py/../../NomeroffNet/Detector.py", line 11, in <module>
    import keras
  File "/home/user/.local/lib/python3.6/site-packages/keras/__init__.py", line 3, in <module>
    from . import utils
  File "/home/user/.local/lib/python3.6/site-packages/keras/utils/__init__.py", line 24, in <module>
    from .vis_utils import model_to_dot
  File "/home/user/.local/lib/python3.6/site-packages/keras/utils/vis_utils.py", line 7, in <module>
    from ..models import Model
  File "/home/user/.local/lib/python3.6/site-packages/keras/models.py", line 10, in <module>
    from .engine.input_layer import Input
  File "/home/user/.local/lib/python3.6/site-packages/keras/engine/__init__.py", line 8, in <module>
    from .training import Model
  File "/home/user/.local/lib/python3.6/site-packages/keras/engine/training.py", line 24, in <module>
    from . import training_arrays
  File "/home/user/.local/lib/python3.6/site-packages/keras/engine/training_arrays.py", line 15, in <module>
    from .. import callbacks as cbks
  File "/home/user/.local/lib/python3.6/site-packages/keras/callbacks/__init__.py", line 19, in <module>
    if K.backend() == 'tensorflow' and not K.tensorflow_backend._is_tf_1():
AttributeError: module 'keras.backend.tensorflow_backend' has no attribute '_is_tf_1'

убунту 18.04 LTS
питон 3.6.8
cv2 4.1.1
tf 1.14.0
numpy 1.17.3

Обучение mrcnn

Добрый день. Можно ли на этой модели обучать изображении с круглой разметкой?

Ошибка обучения options

Добрый день!

Код:

import os
import sys
import warnings
warnings.filterwarnings('ignore')

# change this property
NOMEROFF_NET_DIR = os.path.abspath('../../')

DATASET_NAME = "options"
VERSION = "2019_11_25"

LOG_DIR = os.path.join(NOMEROFF_NET_DIR, "logs/")
PATH_TO_DATASET = os.path.join(NOMEROFF_NET_DIR, "datasets/", DATASET_NAME)
RESULT_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.h5'.format(DATASET_NAME, VERSION))

FROZEN_MODEL_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.pb'.format(DATASET_NAME, VERSION))

sys.path.append(NOMEROFF_NET_DIR)

from NomeroffNet import OptionsDetector
from NomeroffNet.Base import convert_keras_to_freeze_pb

class MyNumberClassificator(OptionsDetector):
    def __init__(self):
        OptionsDetector.__init__(self)
        # outputs 1
        self.CLASS_STATE = ["BACKGROUND", "FILLED", "NOT_FILLED"]

        # outputs 2
        self.CLASS_REGION = ["xx-unknown", "eu-ua-2015", "eu-ua-2004", "eu-ua-1995", "eu", "xx-transit", "ru", "kz"]

        self.EPOCHS           = 2
        self.BATCH_SIZE       = 10

        self.HEIGHT         = 64
        self.WEIGHT         = 295

# initialize region detector.
numberClassificator = MyNumberClassificator()
numberClassificator.prepare(PATH_TO_DATASET)

# train
model = numberClassificator.train(LOG_DIR, cnn="simple")

numberClassificator.test()

numberClassificator.save(RESULT_PATH)
#model = numberClassificator.load(RESULT_PATH)

import keras
keras.backend.clear_session()
model = numberClassificator.load(RESULT_PATH)
convert_keras_to_freeze_pb(numberClassificator.MODEL, FROZEN_MODEL_PATH)

Вываливается ошибка, когда начинаю тренить по этому dataset https://nomeroff.net.ua/datasets/autoriaNumberplateOptionsDataset-2019-10-07.zip

Trace:

start train build
Traceback (most recent call last):
  File "options.py", line 40, in <module>
    numberClassificator.prepare(PATH_TO_DATASET)
  File "/nomeroff-net/NomeroffNet/OptionsDetector.py", line 159, in prepare
    self.train_generator = self.compile_train_generator(train_dir, (self.HEIGHT, self.WEIGHT), self.BATCH_SIZE)
  File "/nomeroff-net/NomeroffNet/OptionsDetector.py", line 330, in compile_train_generator
    imageGenerator.build_data()
  File "/nomeroff-net/NomeroffNet/Base/ImgGenerator.py", line 48, in build_data
    to_categorical(disc[0], self.labels_counts[0]),
  File "/usr/local/lib/python3.6/site-packages/keras/utils/np_utils.py", line 52, in to_categorical
    categorical[np.arange(n), y] = 1
IndexError: index 3 is out of bounds for axis 1 with size 3

Ошибка во время обучения собственной ocr

Для обучения ocr пользуюсь файлом ocr.py из папки train/py/
возникает ошибка keyError
GET ALPHABET
Max plate length in "val": 9
Traceback (most recent call last):
File "/nomeroff-net-master/train/py/ocr.py", line 31, in
model = ocrTextDetector.prepare(PATH_TO_DATASET, aug_count=0)
File "/nomeroff-net-master/NomeroffNet/Base/OCR.py", line 221, in prepare
self.letters, max_plate_length = self.get_alphabet(train_path, test_path, val_path, verbose=verbose)
File "/nomeroff-net-master/NomeroffNet/Base/OCR.py", line 81, in get_alphabet
c_train, max_plate_length_train = self.get_counter(train_path)
File "/nomeroff-net-master/NomeroffNet/Base/OCR.py", line 71, in get_counter
description = json.load(open(json_filepath, 'r'))['description']
KeyError: 'description'

Ошибка при распознавании в demo

Доброго времени суток, при распознавании чёрно-белого изображения в demo0 происходит ошибка:
Traceback (most recent call last): File "c:/Users/zakha/OneDrive/Рабочий стол/recognition.py", line 35, in <module> NP = nnet.detect([img]) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\NomeroffNet\Detector.py", line 98, in detect return self.MODEL.detect(self.normalize(images), verbose=verbose) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\mrcnn\model.py", line 2503, in detect molded_images, image_metas, windows = self.mold_inputs(images) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\mrcnn\model.py", line 2401, in mold_inputs mode=self.config.IMAGE_RESIZE_MODE) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\mrcnn\utils.py", line 459, in resize_image image = np.pad(image, padding, mode='constant', constant_values=0) File "<__array_function__ internals>", line 6, in pad File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\arraypad.py", line 748, in pad pad_width = _as_pairs(pad_width, array.ndim, as_index=True) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\arraypad.py", line 523, in _as_pairs return np.broadcast_to(x, (ndim, 2)).tolist() File "<__array_function__ internals>", line 6, in broadcast_to File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\stride_tricks.py", line 182, in broadcast_to return _broadcast_to(array, shape, subok=subok, readonly=True) File "C:\Users\zakha\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\lib\stride_tricks.py", line 127, in _broadcast_to op_flags=['readonly'], itershape=shape, order='C') ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,2) and requested shape (2,2)

попробовал распознать через https://nomeroff.net.ua/onlinedemo.html, там всё распознается корректно с тем же изображением, подскажите пожалуйста куда копать?

Ошибка list index out of range при вызове convert_keras_to_freeze_pb

Добрый день,
пытаюсь выполнить скрипт ocr-ru.ipynb, но получаю ошибку IndexError: list index out of range. Подскажите, пожалуйста, в чем проблема. Заранее благодарен. Прилагаю скрипт с ошибкой.

Python 3.7
tensorflow (14) пробовал и 13ю версию.
GPU нет, запускаю на ноутбуке.

ocr-ru.ipynb.zip

Чисто научный вопрос)

Есть изображение:
изображение

Я уменьшаю его в два раза и начинаю детектить номер. Получаю следующее: ["T22T15"] - то есть неверно.

На вашем же ресурсе работает все ок.
изображение

Может есть идеи как распознавать уменьшенную копию изображения и превращать ее в оригинал ?:)

ошибка tensorflow

И снова привет :)
подскажите пожалуйста, в чем я не прав?))) tensorflow = 1.15 или tensorflow = 2.0

No module named 'tensorflow_core.keras'

Ошибка TypeError: train() got an unexpected keyword argument 'class attribute name'

Здравствуйте. Вроде следую по инструкции. Но на строке
nnet.train(class_attribute_name="class") #nnet.loadModel(MASK_RCNN_MODEL_PATH)

Выходит ошибка TypeError: train() got an unexpected keyword argument 'class attribute name'

`import os
import cv2
import numpy as np
import sys
import json
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore')

NOMEROFF_NET_DIR = os.path.abspath('C:/Users/ZhuravlevRS/work/datasets/ocr/nomeroff-net-master')
sys.path.append(NOMEROFF_NET_DIR)

specify the path to Mask_RCNN if you placed it outside Nomeroff-net project

MASK_RCNN_DIR = os.path.join(NOMEROFF_NET_DIR, 'Mask_RCNN')
MASK_RCNN_LOG_DIR = os.path.join(NOMEROFF_NET_DIR, "logs")

DATASET_NAME = "mrcnn"
VERSION = "2019_09_18"
MASK_RCNN_FROZEN_PATH = os.path.join(NOMEROFF_NET_DIR, "models/", 'numberplate_{}_{}.pb'.format(DATASET_NAME, VERSION))`

`# Import license plate recognition tools.
from NomeroffNet import Detector
from NomeroffNet.Base import convert_keras_to_freeze_pb

CONFIG = {
"GPU_COUNT": 1,
"IMAGES_PER_GPU": 1,
"WEIGHTS": "coco",
"EPOCHS": 100,
"CLASS_NAMES": ["BG", "numberplate"],
"NAME": "numberplate",
"DATASET_DIR": "C:/Users/ZhuravlevRS/work/datasets/ocr/mrcnn",
"LAYERS": "all",
"NUM_CLASSES": 2
}

Initialize npdetector with default configuration file.

nnet = Detector(MASK_RCNN_DIR, MASK_RCNN_LOG_DIR, CONFIG)`

Проблема с инсталяцией

Система: Ubuntu
python: 3.6.8
Следовал инструкции по установке, все шло хорошо до последней комманды "pip3 install -r requirements.txt"

Комманда, что происходило и ошибка:

ubuntu@ros:~/Git/nomeroff-net$ pip3 install -r requirements.txt
Collecting cython (from -r requirements.txt (line 1))
  Using cached https://files.pythonhosted.org/packages/45/f2/a7101b3457561e57f5abcd6f5ac13190054fecd7370f58f36fe2d6574742/Cython-0.29.13-cp36-cp36m-manylinux1_x86_64.whl
Collecting matplotlib (from -r requirements.txt (line 2))
  Using cached https://files.pythonhosted.org/packages/57/4f/dd381ecf6c6ab9bcdaa8ea912e866dedc6e696756156d8ecc087e20817e2/matplotlib-3.1.1-cp36-cp36m-manylinux1_x86_64.whl
Collecting setuptools (from -r requirements.txt (line 3))
  Using cached https://files.pythonhosted.org/packages/6a/9a/50fadfd53ec909e4399b67c74cc7f4e883488035cfcdb90b685758fa8b34/setuptools-41.4.0-py2.py3-none-any.whl
Collecting numpy (from -r requirements.txt (line 4))
  Using cached https://files.pythonhosted.org/packages/0e/46/ae6773894f7eacf53308086287897ec568eac9768918d913d5b9d366c5db/numpy-1.17.3-cp36-cp36m-manylinux1_x86_64.whl
Collecting Keras==2.2.* (from -r requirements.txt (line 5))
  Downloading https://files.pythonhosted.org/packages/f8/ba/2d058dcf1b85b9c212cc58264c98a4a7dd92c989b798823cc5690d062bb2/Keras-2.2.5-py2.py3-none-any.whl (336kB)
    100% |████████████████████████████████| 337kB 443kB/s 
Collecting imgaug (from -r requirements.txt (line 6))
  Using cached https://files.pythonhosted.org/packages/11/df/5a3bba95b4600d5ca7aff072082ef0d9837056dd28cc4e738e7ce88dd8f8/imgaug-0.3.0-py2.py3-none-any.whl
Collecting tensorflow==1.15 (from -r requirements.txt (line 7))
  Could not find a version that satisfies the requirement tensorflow==1.15 (from -r requirements.txt (line 7)) (from versions: 0.12.1, 1.0.0, 1.0.1, 1.1.0rc0, 1.1.0rc1, 1.1.0rc2, 1.1.0, 1.2.0rc0, 1.2.0rc1, 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.4.1, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0, 1.7.1, 1.8.0rc0, 1.8.0rc1, 1.8.0, 1.9.0rc0, 1.9.0rc1, 1.9.0rc2, 1.9.0, 1.10.0rc0, 1.10.0rc1, 1.10.0, 1.10.1, 1.11.0rc0, 1.11.0rc1, 1.11.0rc2, 1.11.0, 1.12.0rc0, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.12.2, 1.12.3, 1.13.0rc0, 1.13.0rc1, 1.13.0rc2, 1.13.1, 1.13.2, 1.14.0rc0, 1.14.0rc1, 1.14.0, 2.0.0a0, 2.0.0b0, 2.0.0b1)
No matching distribution found for tensorflow==1.15 (from -r requirements.txt (line 7))

pip3 install tensorflow не решает проблему.
Возможные решения?

Использование претренированной модели для Flask API

Добрый день!
хочу использовать модель отсюда https://nomeroff.net.ua/models/mrcnn/ для написания простенького апи для распознования автомобильных номеров, есть ли какие нибудь требования к предварительной настройке модели перед подгрузкой .h5 файла?
Например я тренированную модель в pytorch подгружал так
model = models.vgg16(pretrained=False) class_names = ['benign', 'malignant'] num_features = model.classifier[6].in_features features = list(model.classifier.children())[:-1] # Remove last layer features.extend([nn.Linear(num_features, len(class_names))]) # Add our layer with 2 outputs model.classifier = nn.Sequential(*features) # Replace the model classifier model.load_state_dict(torch.load("./models/project.pth", map_location=lambda storage, loc: storage), strict=False) model.eval()
Нужно ли что то подобное делать в случае использования ваших моделей, и, если да, то не могли бы подсказать что?
Спасибо.

onlinedemo npdetect.php

Не могли бы вы показать пример этого файла "npdetect.php"?

Проблема с .h5 файлами - Google App Engine

Здравствуйте!

Есть API на Flask. Пытаюсь задеплоить на Google Cloud, точнее Google App Engine. Использую кастомный рантайм: dockerfile с установкой всех зависимостей и в конце запуск gunicorn. Сначала использовал инициализацию через параметр "latest", т.е. nnet.loadModel("latest") - аналогично optionsDetector.load("latest") и textDetector.load("latest"). Но при запуске приложение прогружало первый, самый тяжелый .h5 файл, после чего worker прекращал работу, либо же приложение просто бесконечно долго работало без какого-либо результата.
После нескольких безуспешных изменений, я перешёл к более грубому способу и переместил директиву models в корень директивы проекта и загрузил все вместе с самим проектом, перед этим указав в коде локальный путь, т.е. : nnet.loadModel('./models/Detector/mrcnn/mask_rcnn_numberplate_1000_2019_10_07.h5')

optionsDetector.load('./models/OptionsDetector/simple/numberplate_options_2019_10_07.h5')

textDetector.load('./models/TextDetector/eu/anpr_ocr_eu_2-cpu.h5')

Просто прописав данные строки кода глобально - эффект тот же, что и в начале.
Пробывал описать внутри if __name__ == '__main__' - ничего не получилось.

Я попытался разделить инициализацию каждого файла на отдельный роут, чтобы локализировать проблему и выяснил, что файл для textDetector загружается без проблем. Проблема только в nnet.loadModel() и optionsDetector.load().

Код роутов выглядит следующим образом (один роут, как пример):

@app.route('/init1')
def init_model1():
    
    global graph, nnet
    with graph.as_default():
        
        print("FIRST MODEL")
        logging.warning("FIRST MODEL")
        nnet.loadModel('./models/Detector/mrcnn/mask_rcnn_numberplate_1000_2019_10_07.h5')

    return "success1"

Весь код приложения оставлю как ссылку на Ideone, чтобы не засорять даную страницу.
https://ideone.com/S3hRZZ

У меня есть два роута: для изображения и для видео - думаю это не принципиально для данной проблемы, так как возникает она на более раннем этапе. При потребности могу скинуть и dockerfile. Возможно, я упускаю какие-нибудь моменты с зависимоcтями или с принципами работы приложения на сервере.

P.S.
Само собой, локально на компьютере все работает и в разных вариантах.

P.P.S.
Не совсем понимаю каким образом должен работать путь к Mask_RCNN, если устанавливается все в отдельных папках в site-packages.

NF_NET_DIR = os.path.join(dirname,'./nomeroff-net')
MASK_RCNN_DIR = os.path.join(NF_NET_DIR, 'Mask_RCNN')
MASK_RCNN_LOG_DIR = os.path.join(NF_NET_DIR, 'logs')

ValueError: too many values to unpack (expected 2)

Hi
I am get Error, when try to run script "Hello Nomeroff Net":

Traceback (most recent call last):
File "start.py", line 73, in
regionIds, isHiddenIds = optionsDetector.predict(zones)
ValueError: too many values to unpack (expected 2)

How to fix this error?

Same error:
~/nomeroff-net/examples/py$ python3 demo0.py
Using TensorFlow backend.
Traceback (most recent call last):
File "demo0.py", line 72, in
regionIds, stateIds = optionsDetector.predict(zones)
ValueError: too many values to unpack (expected 2)

Resource exhausted

Добрый день. Скопировал ваш проект, пытаюсь обучать на вашем датасете.
ошибка показана на скрине ниже.
проблема начинается в процессе обучения, на первоё
эпохе. Интересует это недостаточно производительности у GPU? или можно как то дотюнить модель, чтобы она влезла на GPU?
GPU nvidia gtx 970 4 Гб памяти.
11
22

Не работает админка для разметки датасета.

Добрый день! Перестала работать ваша админка для разметки номеров.

  1. Не генерирует json (изображения используются в формате png)
  2. При написании стороннего скрипта, который генерирует json файлы для изображений при нажатии на кнопку save and load next сохраняет сразу все изображения из папки и вешает флаг moderated:1

Как ещё сократить время распознавания номера?

Добрый день.
Мы тестируем вашу систему в нашей организации, цель - реализовать автоматическое управление шлагбаумами на основе БД номеров авто.
Для этих целей мы собрали небольшой сервер на Windows 10, core i5 6-го поколения, 8 Гб DRAM и Nvidia GeForce 2070 super.
Первое распознавание происходит за 7-8 секунд, потом в цикле примерно 2 секунды.
У вас указано 0,5 секунды на видеокарте. Подскажите, какие железки вы используете для достижения такого результата? И что можно сделать нам для сокращения времени распознавания до заветных 0,5 секунды?

Точность

Есть ли функция которая будет возвращать точность распознавания в процентах?

ошибка loadFrozenModel

Здравствуйте! Возникает ошибка, когда пытаюсь использовать модели *.pb

ValueError: NodeDef mentions attr 'explicit_paddings' not in Op<name=Conv2D; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=use_cudnn_on_gpu:bool,default=true; attr=padding:string,allowed=["SAME", "VALID"]; attr=data_format:string,default="NHWC",allowed=["NHWC", "NCHW"]; attr=dilations:list(int),default=[1, 1, 1, 1]>; NodeDef: {{node import/conv1/convolution}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 2, 2, 1], use_cudnn_on_gpu=true](import/zero_padding2d_1/Pad, import/conv1/kernel/read). (Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary.).

Python: 3.6
Tensorflow: 1.12.0
Tensorflow-gpu: 1.12.0

Может знаете, в чем может быть проблема?

Уменьшение времени распознования.

Добрый день!
Запустили проект на Tensorflow GPU, но время распознования сократилось только до 5 секунд. Хотелось бы сократить время до 1-2 секунд.
Комп: i7 8800k, GTX 1080 8G
Заранее спасибо за помощь.

Использование OCR

Добрый день! Хотелось бы проверить ocr на отдельной картинке с номером, однако, она не распознает номер, если вставлять картинку в демо пример. Не очень понимаю, как ее использовать отдельно от модели детектирования машин
Не могли бы вы , пожалуйста, описать алгоритм использования отдельно ocr

Проблема с запуском demo

Не хочу показаться идиотом, но при запуске выдает нечто следующее:

File "h5py\h5f.pyx", line 85, in h5py.h5f.open

OSError

Пол интернета облазал, так и не понял из-за чего это. Есть возможность помочь?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.