Category Archives: Python

[Solved] ProxyError: Conda cannot proceed due to an error in your proxy configuration.

ProxyError: Conda cannot proceed due to an error in your proxy configuration.

0. Problem reporting error

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

The following errors are reported when installing pytorch:

ProxyError: Conda cannot proceed due to an error in your proxy configuration.
Check for typos and other configuration errors in any '.netrc' file in your home directory,
any environment variables ending in '_PROXY', and any other system-wide proxy
configuration settings.

The problem lies in agency

1. Solutions

(1) View current terminal agent

env | grep -i "_PROXY"

(2) Delete agents in turn

unset HTTP_PROXY
unset https_proxy
unset http_proxy
unset no_proxy
unset NO_PROXY

3. Whether the verification is successful

Enter again

env | grep -i "_PROXY"

then enter the following:
env. grep -i "PROXY"

[Solved] AttributeError: ‘PngImageFile‘ object has no attribute ‘imshow‘

How to solve error attributeerror:’pngimagefile’object has no attribute’imshow’ Successfully.


Error:

AttributeError: ‘PngImageFile’ object has no attribute ‘imshow’

Reasons:

Attribute error: the “pngimagefile” object does not have the attribute “imshow”

Solution:

Pngimagefile does not have imshow method, but has show method, so the following changes are required!

Modify
img.imshow()
to
img.show()

[Solved] Yolov5 Deep Learning Error: RuntimeError: DataLoader worker (pid(s) 2516, 1768) exited unexpectedly

Project scenario:

There is a problem when using yolov5 for deep learning. I use GPU for learning.


Problem description

An error is reported at the beginning of learning, RuntimeError: DataLoader worker (pid(s) 2516, 1768) exited unexpectedly.


Cause analysis:

Because I use GPU to learn, Anaconda’s virtual memory is also allocated enough, so the problem should be the setting of the number of CPU threads. Before that, I tried to adjust the batch size, but it didn’t work.


Solution:

In train There is a parameter of --workers in the file of py.

There is a parameter named --workers in the train.py file. Set it to 0.

the following is my setting, you can refer to it~~~

def parse_opt(known=False):
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', type=str, default=ROOT/'yolov5x.pt', help='initial weights path') #初始权重值
    parser.add_argument('--cfg', type=str, default='yolov5_Scan_FDDI/PLC_model.yaml', help='model.yaml path') #训练模型文件
    parser.add_argument('--data', type=str, default=ROOT/'yolov5_Scan_FDDI/PLC_parameter.yaml', help='dataset.yaml path') #数据集参数文件
    parser.add_argument('--hyp', type=str, default=ROOT/'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path') #超参数设置
    parser.add_argument('--epochs', type=int, default=100) #训练轮数
    parser.add_argument('--batch-size', type=int, default=4, help='total batch size for all GPUs, -1 for autobatch') #batch size
    parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=320, help='train, val image size (pixels)') #图片大小
    parser.add_argument('--rect', action='store_true', help='rectangular training')
    parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') #断续训练
    parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
    parser.add_argument('--noval', action='store_true', help='only validate final epoch')
    parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
    parser.add_argument('--noplots', action='store_true', help='save no plot files')
    parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
    parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
    parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
    parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
    parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') #GPU
    parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
    parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
    parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
    parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
    parser.add_argument('--workers', type=int, default=0, help='max dataloader workers (per RANK in DDP mode)') #CPU线程数设置
    parser.add_argument('--project', default=ROOT/'runs/train', help='save to project/name')
    parser.add_argument('--name', default='exp', help='save to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--quad', action='store_true', help='quad dataloader')
    parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
    parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
    parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
    parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
    parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
    parser.add_argument('--seed', type=int, default=0, help='Global training seed')
    parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')

    # Weights & Biases arguments
    parser.add_argument('--entity', default=None, help='W&B: Entity')
    parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
    parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
    parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')

    opt = parser.parse_known_args()[0] if known else parser.parse_args()
    return opt

[Solved] error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor‘

Error Message:

error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor’

cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Reason:

Path read error

Solution:

Original code

videos_src_path = "D:\pythonProject\python3.9\dataset\image\baozi_image\3.png"
frame = cv2.imread(videos_src_path)

Press the following to modify the read path

videos_src_path = "D:/pythonProject/python3.9/dataset/image/baozi_image/3.png"
#or  videos_src_path = r" D:\pythonProject\python3.9\dataset\image\baozi_image\3.png"
frame = cv2.imread(videos_src_path)

 

ERROR: Failed building wheel for osgeo [How to Solve]

ERROR: Failed building wheel for osgeo

Problem: When Installing pip3 install osgeo report an error: ERROR: Failed building wheel for osgeo

Solution:

Method 1

conda install gdal

Method 2:

1. According to the python version, download the corresponding GDAL installation file

for example: Python 3.8 download GDAL‑3.4.3‑cp38‑cp38‑win_amd64.whl

Cp38 stands for python3.8 version and windows64 bit

2. install:

pip3 install gdal-3.4.3-cp38-cp38-win_amd64.whl

 

[Solved] ERROR: Failed building wheel for pycryptodome

Error: failed building wheel for pycryptodome PIP installation error solution

1. Questions

PIP install pycryptodome build wheel error error error stack display reference OpenSSL error

 ERROR: Failed building wheel for pycryptodome

2. Solutions

# ①. install brew
# ②. install openssl@1
# ③ link to openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include"

3. Other collected information

For devices using apple silicon, you can try this (because the default homebrew bin directory is different)

export LDFLAGS="-L/opt/homebrew/opt/[email protected]/lib"
export CPPFLAGS="-I/opt/homebrew/opt/[email protected]/include"

You can enter the view command yourself

brew info openssl

If you want to install an older version of cryptography (such as 2.9.x), you must link [email protected] instead of openssl@3

brew install openssl will prompt you to export

 

[Solved] UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring it

UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring it

After installing anaconda, there will report an error when you import some module in ipython:

UserWarning: mkl-service package failed to import, therefore Intel® MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package

 

Solution:
First configure three environment variables, one is missing
E:\Anaconda3
E:\Anaconda3\Scripts
E:\Anaconda3\Library\bin
Put E:\Anaconda3\Library\bin under
libcrypto-1_1-x64.dll
libssl-1_1-x64.dll
Copy the above two files to
E:\Anaconda3\DLLs
OK, you can restart pycharm and it will work

[Solved] wxauto error: ImportError: DLL load failed while importing win32gui: Can’t find the specified program

Background

Using wxauto to develop wechat robot, there was an error when running the program in Pycharm

Error prompt

Traceback (most recent call last):
  File "D:\Project\wechatBot\test.py", line 2, in <module>
    from wxauto import WeChat
  File "C:\Users\pokeu\anaconda3\envs\wechatbot\lib\site-packages\wxauto\__init__.py", line 2, in <module>
    from .wxauto import WxParam, WxUtils, WeChat, COPYDICT
  File "C:\Users\pokeu\anaconda3\envs\wechatbot\lib\site-packages\wxauto\wxauto.py", line 10, in <module>
    import win32gui, win32con
ImportError: DLL load failed while importing win32gui: Can't find the specified program.

Solution:

Check if the win32gui.pyd file exists in the C:\Users\username\anaconda3\envs\wechatbot\Lib\site-packages\win32 directory

If not, run pip install pywin32 to install it.

Add C:\Users\username\anaconda3\envs\wechatbot\Lib\site-packages\pywin32_system32 to the system environment variable.

Notes.
a. User name Replace with your own user name.
b. The first half of C:\Users\username\anaconda3 is the installation path of anaconda, replace it with your own.
c. \envs\wechatbot is the path of the new environment I created (wechatbot), replace it with your own environment, or ignore it if you didn’t create it, and just find \Lib\site-packages\win32.

In the original import … import the following library before the original import …: import pywintypes, e.g.

import pywintypes
#import pythoncom # Uncomment this if some other DLL load will fail
from wxauto import WeChat
import time, random

Now run the program again, and there should be no error.

[Solved] weditor Plug-in Dump Hierarchy Error: Local server not started, start with $ python -m weditor

I had tried many solutions online. but they do not work. here is my working solution I found finally.

 

Solution:

1. First, make sure that ADB devices can query your device

2. Key solution: delete ATX on the mobile phone and re-execute python -m uiautomator2 init

3. Just in case, don’t directly execute the WebEditor. Be sure to execute python -m weditor

Then click Dump Hierarchy to synchronize the screen. Don’t use real-time, just use static.

jpeg4py.JPEG(path).decode() Open Image Error [How to Solve]

Recorded:

import jpeg4py
path = template_image[0]
im = jpeg4py.JPEG(path).decode()
"""
Note: template_image is ndarray type
"""

1. Error Message:
\jpeg4py._py.JPEGRuntimeError: tjDecompressHeader2() failed with error -1 and error string Not a JPEG

2. Reason: Problem with data type

>>> type(path)
<class 'numpy.str_'>
>>> # Although equal
>>> str(path) == path
True
>>> # But they are different types
>>> type(str(path))
<class 'str'>

3. Solution:

import jpeg4py
path = template_image[0]
im = jpeg4py.JPEG(str(path)).decode()
"""
Note: path-->str(path) 
Type from <class 'numpy.str_'> modify to <class 'str'>
"""

 

[Solved] mindinsight modelart Error: RuntimeError: An attempt has been made to start a new process before…

 

Question:

Mindinsight uses error reporting on modelart.

After adding the summary and training some epoch normally, the operation will report an error:

Solution:

When using SummaryCollector, you need to put the code block in if__name__ == __main__:

The official mindspire tutorial has been updated. You can refer to the writing method of the latest tutorial: collect summary data – mindspire master document

Codes like this:

def train():
  summary_collector = SummaryCollector(summary_dir='./summary_dir')

  ...

  model.train(...., callback=[summary_collector])

if __name__ == '__main__':
    train()

 

How to Solve args = parser.parse_args() error

args = parser.parse_args() error


Problem description

args = parser.parse_args() reports an error

import argparse

parser = argparse.ArgumentParser(prog='top', description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
# args = parser.parse_args()
args, unknown = parser.parse_known_args() # Modified
print(args)

Solution:
Modify to args, unknown = parser.parse_known_args()