2021-10-15 Summary of python programming problems and occasional supplements

Summary of some common problems in python programming and supplements from time to time

File reading problem

1. Solve the problem that cv2.imread reads files containing Chinese paths.
cv2.imread() directly reads pictures containing Chinese paths and returns None. The solution is as follows:

import cv2
import numpy as np
img=cv2.imdecode(np.fromfile(path+picname, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)

2. How to determine whether the txt document has been read to the end
. When you need to process each line of the txt document, you finally need to determine how to read to the end of the file to break out of the loop. The solution is as follows:

f=open(path+'xx.txt','r')
    while(True):
        line=f.readline()[:-1]#去掉最后的换行符号‘\n’
        if not line:
            break
        #下方可继续编程处理数据

There is no problem with this attribute

Generally speaking, if there is no such attribute, you can choose the pip install xx statement to solve it. However, sometimes there will be situations that cannot be solved. These problems are mainly explained here.
1. module 'cv2.cv2' has no attribute 'face'
because generally when learning opencv we only install opencv-python. If we need to implement some algorithms for face recognition, we also need to install opencv-contrib-python, so theoretically Just pip install opencv-contrib-python directly, but in practice it is found that this cannot be installed successfully. The specific operations are as follows:

pip uninstall opencv-python
pip install opencv-python
pip install opencv-contrib-python

I don’t know the specific reason, but it works magically after installation. Some blogs said that the possible reason is that the relevant packages are not installed or the relevant packages of cv2 are not installed [Link: link . ]

other problems

1. Appears during face recognition: labels data type = 19 is not supported.
The original code is as follows:

model=cv2.face.EigenFaceRecognizer_create()
model.train(np.asarray(data[0]),np.asarray(data[1]))

The error is reported as follows:
Insert image description here
This is because model.train requires the label to be of int type, so it can be solved by simply converting the data type. The solution is as follows:

model=cv2.face.EigenFaceRecognizer_create()
model.train(np.asarray(data[0]),np.asarray(data[1],dtype=np.int32))

Guess you like

Origin blog.csdn.net/LJ1120142576/article/details/120783006