Category Archives: Python

[How to Solve]AttributeError: module ‘scipy’ has no attribute ‘io’

The problem of io loading .mat data and imread reading pictures under Scipy

When we need to load MATLAB’s .mat file, if we use:

import scipy.misc 
import scipy.io
import os
cwd  = os.getcwd()
data = scipy.io.loadmat(cwd + "/data/imagenet-vgg-verydeep-19.mat")

Will report an error:
AttributeError: module’scipy’ has no attribute’io’

 

The reason for this may be that the submodules under scipy cannot be imported directly.

from scipy import io

Finally changed to:

import scipy.misc 
from scipy import io
import os
cwd  = os.getcwd()
data = io.loadmat(cwd + "/data/imagenet-vgg-verydeep-19.mat")

problem solved.

Also use the imread function under Scipy.misc,

import scipy.misc 
cwd  = os.getcwd()
VGG_PATH = cwd + "/data/imagenet-vgg-verydeep-19.mat"
IMG_PATH = cwd + "/data/cat.jpg"
input_image = imread(IMG_PATH)

appear:
AttributeError : ‘module’ object has no attribute’imread ‘

This is sometimes because you do not have pillow dependency packages

pip install pillow

This is how I solved it.

Mac Upgrade pip Error OSError: [Errno 13] Permission denied: ‘/Library/Python/2.7/site-packages/pip-9.0.1-py2….

Error Message:

Exception:

Traceback (most recent call last):

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py”, line 215, in main

    status = self.run(options, args)

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py”, line 342, in run

    prefix=options.prefix_path,

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py”, line 778, in install

    requirement.uninstall(auto_confirm=True)

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py”, line 754, in uninstall

    paths_to_remove.remove(auto_confirm)

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_uninstall.py”, line 115, in remove

    renames(path, new_path)

  File “/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py”, line 267, in renames

    shutil.move(old, new)

  File “/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”, line 300, in move

    rmtree(src)

  File “/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”, line 247, in rmtree

    rmtree(fullname, ignore_errors, onerror)

  File “/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”, line 252, in rmtree

    onerror(os.remove, fullname, sys.exc_info())

  File “/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”, line 250, in rmtree

    os.remove(fullname)

OSError: [Errno 13] Permission denied: ‘/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/EGG-INFO/PKG-INFO’

You are using pip version 9.0.1, however version 19.1.1 is available.

You should consider upgrading via the ‘pip install –upgrade pip’ command.

How to Solve this error:

When using pip to update a Python library under Mac, it prompts that the pip version is too low. The command line at the bottom shows that it needs to be upgraded. The upgrade command is: You should consider upgrading via the’pip install –upgrade pip’ command.

The command input given by the installation: pip install –upgrade pip; after the result is executed, the same error is still reported.

After retries N times, the execution still failed.

Finally, after searching online, I found out that it was a permission problem. Modify the execution command as follows: 

sudo  pip install –upgrade pip 

 

PIP Install Mysqlclient error C1083: Cannot open include file: ‘mysql.h‘: No such file or directory

Problem Description:
System: win10 (64 bit)

python version: 3.7.8

MySQL Server 8.0

MySQL Connector C 6.1

When using the pip install -r requirements.txt command, an error is reported when installing to mysqlclient (mysqlclient has been installed through the pip command):

ERROR: Command errored out with exit status 1:
command: ‘c:\python3.7.8\python.exe’ -u -c ‘import sys, setuptools, tokenize; sys.argv[0] = ‘”‘”‘C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-install-k4s1hfze\\mysqlclient\\setup.py'”‘”‘; __file__='”‘”‘C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-install-k4s1hfze\\mysqlclient\\setup.py'”‘”‘;f=getattr(tokenize, ‘”‘”‘open'”‘”‘, open)(__file__);code=f.read().replace(‘”‘”‘\r\n'”‘”‘, ‘”‘”‘\n'”‘”‘);f.close();exec(compile(code, __file__, ‘”‘”‘exec'”‘”‘))’ install –record ‘C:\Users\ADMINI~1\AppData\Local\Temp\pip-record-8r_vb76d\install-record.txt’ –single-version-externally-managed –compile –install-headers ‘c:\python3.7.8\Include\mysqlclient’
cwd: C:\Users\ADMINI~1\AppData\Local\Temp\pip-install-k4s1hfze\mysqlclient\
Complete output (30 lines):
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.7
copying _mysql_exceptions.py -> build\lib.win-amd64-3.7
creating build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb
creating build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants
running build_ext
building ‘_mysql’ extension
creating build\temp.win-amd64-3.7
creating build\temp.win-amd64-3.7\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,12,’final’,0) -D__version__=1.3.12 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include” -Ic:\python3.7.8\include -Ic:\python3.7.8\include “-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE” “-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt” “-IC:\Program Files (x86)\Windows Kits\8.1\include\shared” “-IC:\Program Files (x86)\Windows Kits\8.1\include\um” “-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt”/Tc_mysql.c /Fobuild\temp.win-amd64-3.7\Release\_mysql.obj / Zl
_mysql.c
_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe’ failed with exit status 2
—————————————-
Rolling back uninstall of mysqlclient
Moving to c:\python3.7.8\lib\site-packages\mysqlclient-1.4.6.dist-info\
from c:\python3.7.8\lib\site-packages\~ysqlclient-1.4.6.dist-info
Moving to c:\python3.7.8\lib\site-packages\mysqldb\
from c:\python3.7.8\lib\site-packages\~ysqldb
ERROR: Command errored out with exit status 1: ‘c:\python3.7.8\python.exe’ -u -c ‘import sys, setuptools, tokenize; sys.argv[0] = ‘”‘”‘C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-install-k4s1hfze\\mysqlclient\\setup.py'”‘”‘; __file__='”‘”‘C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\pip-install-k4s1hfze\\mysqlclient\\setup.py'”‘”‘;f=getattr(tokenize, ‘”‘”‘open'”‘”‘, open)(__file__);code=f.read().replace(‘”‘”‘\r\n'”‘”‘, ‘”‘”‘\n'”‘”‘);f.close();exec(compile(code, __file__, ‘”‘”‘exec'”‘”‘))’ install –record ‘C:\Users\ADMINI~1\AppData\Local\Temp\pip-record-8r_vb76d\install-record.txt’ –single-version-externally-managed –compile –install-headers ‘c:\python3.7.8\Include\mysqlclient’ Check the logs for full command output.

Reason analysis:
For 64-bit Windows, when pip installs mysqlclient, it only searches for certain MySQL files (such as “mysql.h”) in the Program files (x86) folder, but does not search for Program files. This machine installs the MySQL connector Go to C:\Program Files\MySQL, but there is no MySQL installation directory in C:\Program Files (x86), so no content is found in Program files (x86), resulting in an error.

Solution:
Copy the C:\Program Files\MySQL\MySQL Connector C 6.1 folder to the C:\Program Files (x86)\MySQL\MySQL Connector C 6.1 directory (I used a very simple and rude method to copy the entire MySQL folder ), re-execute the command pip install -r requirements.txt. The command was executed successfully

 


E:\HttpRunnerManager>pip install -r requirements.txt
Requirement already satisfied: Django==2.0.3 in c:\python3.7.8\lib\site-packages (from -r requirements.txt (line 1)) (2.0.3)
Requirement already satisfied: PyYAML==3.12 in c:\python3.7.8\lib\site-packages (from -r requirements.txt (line 2)) (3.12)
Requirement already satisfied: requests==2.18.4 in c:\python3.7.8\lib\site-packages (from -r requirements.txt (line 3)) (2.18.4)
Requirement already satisfied: eventlet==0.22.1 in c:\python3.7.8\lib\site-packages (from -r requirements.txt (line 4)) (0.22.1)
Collecting mysqlclient==1.3.12
  Using cached mysqlclient-1.3.12.tar.gz (89 kB)
Collecting django-celery==3.2.2
  Using cached django-celery-3.2.2.tar.gz (90 kB)
Collecting flower==0.9.2
  Using cached flower-0.9.2.tar.gz (1.3 MB)
Collecting dwebsocket==0.4.2
  Using cached dwebsocket-0.4.2.tar.gz (14 kB)
Collecting paramiko==2.4.1
  Using cached paramiko-2.4.1-py2.py3-none-any.whl (194 kB)
Collecting HttpRunner==1.5.8
  Using cached HttpRunner-1.5.8-py2.py3-none-any.whl (48 kB)
Requirement already satisfied: pytz in c:\python3.7.8\lib\site-packages (from Django==2.0.3->-r requirements.txt (line 1)) (2020.1)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\python3.7.8\lib\site-packages (from requests==2.18.4->-r requirements.txt (line 3)) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\python3.7.8\lib\site-packages (from requests==2.18.4->-r requirements.txt (line 3)) (2020.6.20)
Requirement already satisfied: idna<2.7,>=2.5 in c:\python3.7.8\lib\site-packages (from requests==2.18.4->-r requirements.txt (line 3)) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in c:\python3.7.8\lib\site-packages (from requests==2.18.4->-r requirements.txt (line 3)) (1.22)
Requirement already satisfied: greenlet>=0.3 in c:\python3.7.8\lib\site-packages (from eventlet==0.22.1->-r requirements.txt (line 4)) (0.4.16)
Requirement already satisfied: celery<4.0,>=3.1.15 in c:\users\administrator\appdata\roaming\python\python37\site-packages (from django-celery==3.2.2->-r requirements.txt (line 6)) (3.1.26.post2)
Collecting tornado>=4.2.0
  Using cached tornado-6.0.4-cp37-cp37m-win_amd64.whl (417 kB)
Collecting babel>=1.0
  Using cached Babel-2.8.0-py2.py3-none-any.whl (8.6 MB)
Requirement already satisfied: setuptools in c:\python3.7.8\lib\site-packages (from dwebsocket==0.4.2->-r requirements.txt (line 8)) (47.1.0)
Requirement already satisfied: six in c:\python3.7.8\lib\site-packages (from dwebsocket==0.4.2->-r requirements.txt (line 8)) (1.15.0)
Collecting cryptography>=1.5
  Using cached cryptography-3.1-cp37-cp37m-win_amd64.whl (1.5 MB)
Collecting pynacl>=1.0.1
  Using cached PyNaCl-1.4.0-cp37-cp37m-win_amd64.whl (206 kB)
Collecting pyasn1>=0.1.7
  Using cached pyasn1-0.4.8-py2.py3-none-any.whl (77 kB)
Collecting bcrypt>=3.1.3
  Using cached bcrypt-3.2.0-cp36-abi3-win_amd64.whl (28 kB)
Requirement already satisfied: har2case in c:\python3.7.8\lib\site-packages (from HttpRunner==1.5.8->-r requirements.txt (line 10)) (0.3.1)
Collecting requests-toolbelt
  Using cached requests_toolbelt-0.9.1-py2.py3-none-any.whl (54 kB)
Requirement already satisfied: Jinja2 in c:\python3.7.8\lib\site-packages (from HttpRunner==1.5.8->-r requirements.txt (line 10)) (2.11.2)
Requirement already satisfied: colorama in c:\python3.7.8\lib\site-packages (from HttpRunner==1.5.8->-r requirements.txt (line 10)) (0.4.3)
Collecting colorlog
  Using cached colorlog-4.2.1-py2.py3-none-any.whl (14 kB)
Requirement already satisfied: billiard<3.4,>=3.3.0.23 in c:\users\administrator\appdata\roaming\python\python37\site-packages (from celery<4.0,>=3.1.15->django-celery==3.2.2->-r requirements.txt (line 6)) (3.3.0.23)
Requirement already satisfied: kombu<3.1,>=3.0.37 in c:\users\administrator\appdata\roaming\python\python37\site-packages (from celery<4.0,>=3.1.15->django-celery==3.2.2->-r requirements.txt (line 6)) (3.0.37)
Requirement already satisfied: cffi!=1.11.3,>=1.8 in c:\python3.7.8\lib\site-packages (from cryptography>=1.5->paramiko==2.4.1->-r requirements.txt (line 9)) (1.14.2)
Requirement already satisfied: MarkupSafe>=0.23 in c:\python3.7.8\lib\site-packages (from Jinja2->HttpRunner==1.5.8->-r requirements.txt (line 10)) (1.1.1)
Requirement already satisfied: anyjson>=0.3.3 in c:\users\administrator\appdata\roaming\python\python37\site-packages (from kombu<3.1,>=3.0.37->celery<4.0,>=3.1.15->django-celery==3.2.2->-r requirements.txt (line 6)) (0.3.3)
Requirement already satisfied: amqp<2.0,>=1.4.9 in c:\users\administrator\appdata\roaming\python\python37\site-packages (from kombu<3.1,>=3.0.37->celery<4.0,>=3.1.15->django-celery==3.2.2->-r requirements.txt (line 6)) (1.4.9)
Requirement already satisfied: pycparser in c:\python3.7.8\lib\site-packages (from cffi!=1.11.3,>=1.8->cryptography>=1.5->paramiko==2.4.1->-r requirements.txt (line 9)) (2.20)
Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed.
Using legacy 'setup.py install' for django-celery, since package 'wheel' is not installed.
Using legacy 'setup.py install' for flower, since package 'wheel' is not installed.
Using legacy 'setup.py install' for dwebsocket, since package 'wheel' is not installed.
Installing collected packages: mysqlclient, django-celery, tornado, babel, flower, dwebsocket, cryptography, pynacl, pyasn1, bcrypt, paramiko, requests-toolbelt, colorlog, HttpRunner
  Attempting uninstall: mysqlclient
    Found existing installation: mysqlclient 1.4.6
    Uninstalling mysqlclient-1.4.6:
      Successfully uninstalled mysqlclient-1.4.6
    Running setup.py install for mysqlclient ... done
  Attempting uninstall: django-celery
    Found existing installation: django-celery 3.3.1
    Uninstalling django-celery-3.3.1:
      Successfully uninstalled django-celery-3.3.1
    Running setup.py install for django-celery ... done
    Running setup.py install for flower ... done
    Running setup.py install for dwebsocket ... done
  Attempting uninstall: HttpRunner
    Found existing installation: httprunner 3.1.4
    Uninstalling httprunner-3.1.4:
      Successfully uninstalled httprunner-3.1.4
Successfully installed HttpRunner-1.5.8 babel-2.8.0 bcrypt-3.2.0 colorlog-4.2.1 cryptography-3.1 django-celery-3.2.2 dwebsocket-0.4.2 flower-0.9.2 mysqlclient-1.3.12 paramiko-2.4.1 pyasn1-0.4.8 pynacl-1.4.0 requests-toolbelt-0.9.1 tornado-6.0.4
 
E:\HttpRunnerManager>

 

other reasons:
Reason 1:

1. Mysqlclient version does not match, Mysqlclient download address https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

2. Mysqlclient installation command

pip install mysqlclient-1.4.6-cp37-cp37m-win_amd64.whl

3. To verify whether the installation is successful, use the command:

python

>>> import MySQLdb

No error means success

C:\Users\Administrator>python
Python 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>>

Reason two:

MySQL Connector-c is not installed, the download address is https://downloads.mysql.com/archives/cc/ , just download and install.

Reason three:

Use the pip install mysql-connector command to install mysql-connector

C:\Users\Administrator>pip install mysql-connector
Collecting mysql-connector
  Downloading mysql-connector-2.2.9.tar.gz (11.9 MB)
     |████████████████████████████████| 11.9 MB 467 kB/s
Using legacy 'setup.py install' for mysql-connector, since package 'wheel' is not installed.
Installing collected packages: mysql-connector
    Running setup.py install for mysql-connector ... done
Successfully installed mysql-connector-2.2.9

can‘t multiply sequence by non-int of type ‘numpy.float64‘

{TypeError}can’t multiply sequence by non-int of type ‘numpy.float64’

Multiplying float64 and tuples raises an error

    a=(2,4,6)
    b=35.6
    c=a*b

The reason is that a is of int type and B is of float type, and the types are inconsistent, so the multiplication operation cannot be performed

The solution is to change the data type to consistent.

    a=(2,4,6)
    b=35
    c=a*b
    print(c)

How to Solve Python AttributeError: ‘module’ object has no attribute ‘xxx’

Python script error attributeerror: ‘module’ object has no attribute ‘xxx’ solution

when you encounter a few problems, you should pay attention to the same problem when you don’t ask for a solution

1. When naming py script, it should not be the same as the reserved word and module name of Python
(it is not easy to notice when naming files)
2 Delete the. PyC file of the library (because the. PyC file will be generated every time the PY script runs; if the. PyC file has been generated, if the code is not updated, the runtime will still go PyC, so you need to delete the. PyC file), rerun the code, or find an environment where you can run the code and copy and replace the. PyC file of the current machine Import questions </ font> </ font>

Python3 Fatal error in launcher: Unable to create process using ‘”‘

Under windows, python2 and python3 coexist. When installing pyGame or other third-party libraries with PIP3, an error is reported as follows:

Fatal error in launcher: Unable to create process using '"'

resolvent:

C:\Users\Administrator>python3 -m pip install pygame

Reason: it needs to be used like this in Windows environment. I don’t understand the reason, and the Python – M instruction can’t find the exact meaning

There are also hints that it is a problem with the PIP version. Just update the pip to the latest version. The update command is “Python – M PIP install – upgrade PIP”.

AttributeError: lower not found (NLP extracted tfidf features)

在这里插入图片描述

The root cause lies in the incorrect use of fit, transform and fit_transform.
First, make it clear that the incoming parameters can be possible causes of series
errors:

When using TfidfVectorizer(), transform after fit_transform

def tfidf(X_train):
    tfidf_vec = TfidfVectorizer()
    X_train_tfidf = tfidf_vec.fit_transform(X_train)
    X_train_tfidf = tfidf_vec.transform(X_train_tfidf)
    return X_train_tfidf

Here the result of fit_transform is passed to transform again, and the transform is repeated

The correct way to use it should be:

def tfidf(X_train,X_test):
tfidf_vec = TfidfVectorizer()
X_train_tfidf = tfidf_vec.fit_transform(X_train)
X_test_tfidf = tfidf_vec.transform(X_test)
return X_train_tfidf,X_test_tfidf

fit_transform into the training set, transform into the test set

Or you can fit first and then transform

def tfidf(data):
tfidf_vec = TfidfVectorizer()
tfidf_model = tfidf_vec.fit(data)
print(tfidf_model.dtype)
X_tfidf = tfidf_model.transform(data)
return X_tfidf

You can also use CountVectorizer() and TfidfTransformer()

def tfidf(data):
vectorizer = CountVectorizer() # This class will transform the words in the text into a word frequency matrix, and the matrix element a[i][j] represents the word frequency of word j under class i text
transformer = TfidfTransformer() # This class will count the tf-idf weights of each word
tfidf_before = vectorizer.fit_transform(data)
tfidf = transformer.fit_transform(tfidf_before)
return tfidf

Note that the first type is divided into training set and test set. It needs to be divided into training set and test set before
inputting parameters. The latter two need to extract tfidf features and then divide training set and test set,
otherwise it may cause training set and test set. The feature dimensions of the set are different, and they are not transformed under the same standard

Detailed explanation of OpenCV approxpolydp() function

CV_EXPORTS_W void approxPolyDP( InputArray curve,OutputArray approxCurve,double epsilon, bool closed );

@param curve Input vector of a 2D point stored in std::vector or Mat
@param approxCurve Result of the approximation. The type should match the type of the input curve.
@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance
between the original curve and its approximation.
@param closed If true, the approximated curve is closed (its first and last vertices are
connected). Otherwise, it is not closed.

The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less
vertices so that the distance between them is less or equal to the specified precision. It uses the
Douglas-Peucker algorithm <http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm>

The main function is to crease a continuous smooth curve

There are four parameters

Inputarray curve: input curve. The data type can be vector & lt; point & gt;.

Outputarray approxcurve: output polyline. The data type can be vector & lt; point & gt;.

Double epsilon: the threshold value for judging the distance between the point and the corresponding line segment. (if the distance is greater than this threshold, it will be discarded. If the distance is less than this threshold, it will be retained. The smaller the epsilon is, the closer the shape of the broken line is to the curve.)

Bool closed: Flag of whether the curve is closed or not.

Program example:

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace std;
using namespace cv;

void main()
{
    Mat srcImg = imread("01.jpg");
    imshow("src", srcImg);
    Mat dstImg(srcImg.size(), CV_8UC3, Scalar::all(0));

    cvtColor(srcImg, srcImg, CV_BGR2GRAY);
    threshold(srcImg, srcImg, 200, 255, CV_THRESH_BINARY_INV);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarcy;
    findContours(srcImg, contours, hierarcy, 0, CV_CHAIN_APPROX_NONE);
    vector<vector<Point>> contours_poly(contours.size());
    for (int i = 0; i<contours.size(); i++)
    {
        approxPolyDP(Mat(contours[i]), contours_poly[i], 15, true);

        drawContours(dstImg, contours_poly, i, Scalar(0, 255, 255), 2, 8); 
    }
    imshow("approx", dstImg);
    waitKey(0);
}

Image “01. JPG”:

Epsilon was 15

Epsilon was 5

To solve the problem that the loss of verification set of resnet50 pre-training model remains unchanged

# Available whenever available in the library Use pre-trained ResNet50 models
covn_base = tf.keras.applications.ResNet50(weights='imagenet', include_top = False,
                                           input_shape=(im_height,im_width,3), layers=tf.keras.layers)

K.set_learning_phase(1)
"""
freeze the weights for the first 174-33=141
frezee the level 141 before
"""
for layer in covn_base.layers[0:141]:
    layer.trainable = False

for layer in covn_base.layers[141:]:
    layer.trainable = True

model.add(covn_base)
model.add(tf.keras.layers.GlobalAveragePooling2D())
model.add(tf.keras.layers.Dense(512,activation="relu"))
model.add(tf.keras.layers.Dropout(rate=0.2))
model.add(tf.keras.layers.Dense(CLASS,activation="softmax"))

Load pre training model with your own classification model!!!

Python: Np.where Ternary Operator

through the use of np.where It can perform more complex operations

np.where ()

score = np.random.randint(40, 100, (10, 5))
score
array([[51, 81, 74, 58, 56],
       [94, 79, 51, 92, 94],
       [84, 79, 54, 87, 81],
       [52, 53, 69, 83, 73],
       [42, 68, 67, 50, 55],
       [45, 85, 58, 72, 61],
       [78, 63, 80, 99, 95],
       [66, 45, 51, 89, 48],
       [46, 63, 78, 43, 85],
       [93, 69, 83, 91, 96]])

temp = score[:4, :4]
# Judgment of the top four students, the first four courses, the grade greater than 60 set to 1, otherwise 0
np.where(temp > 60, 1, 0)
array([[0, 1, 1, 0],
       [1, 1, 0, 1],
       [1, 1, 0, 1],
       [0, 0, 1, 1]])

Compound logic needs combination np.logical_ And and np.logical_ Or use

# determine the first four students, the first four courses, the results of greater than 60 and less than 90 for 1, otherwise 0
np.where(np.logical_and(temp > 60, temp < 90), 1, 0) # greater than 60, less than 90 show 1
array([[0, 1, 1, 0],
       [0, 1, 0, 0],
       [1, 1, 0, 1],
       [0, 0, 1, 1]])

# determine the first four students, the first four courses, the grades in greater than 90 or less than 60 for 1, otherwise 0
np.where(np.logical_or(temp <60, temp > 90), 1, 0) less than 60 greater than 90 show 1
array([[1, 0, 0, 1],
       [1, 0, 1, 1],
       [0, 0, 1, 0],
       [1, 1, 0, 0]])