Category Archives: Python

[Solved] error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function ‘copyMakeBorder‘

Question:

##Boundary fill
import cv2
top_size,bottom_size,left_size,right_size=(50,50,50,50)
replicate=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REPLICATE)
reflect=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REFLECT)
reflect101=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REFLECT101)
wrap=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_WRAP)
constant=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_CONSTANT,value=0) 
Outcome:
error Traceback (most recent call last)
<ipython-input-39-820a457b4770> in <module>
      2 import cv2
      3 top_size,bottom_size,left_size,right_size=(50,50,50,50)
----> 4 replicate=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REPLICATE)
      5 reflect=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REFLECT)
      6 reflect101=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,boderType=cv2.BORDER_REFLECT101)

error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'copyMakeBorder'
> Overload resolution failed:
>  - copyMakeBorder() missing required argument 'borderType' (pos 6)
>  - copyMakeBorder() missing required argument 'borderType' (pos 6)

analysis:

error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'copyMakeBorder'
> Overload resolution failed:
>  - copyMakeBorder() missing required argument 'borderType' (pos 6)
>  - copyMakeBorder() missing required argument 'borderType' (pos 6)

“Bordertype” spelling error!!!!

Correct code:

##Boundary fill
import cv2
top_size,bottom_size,left_size,right_size=(50,50,50,50)
replicate=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REPLICATE)
reflect=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REFLECT)
reflect101=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REFLECT101)
wrap=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_WRAP)
constant=cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_CONSTANT,value=0) 


import matplotlib.pyplot as plt
plt.subplot(231),plt.imshow(img,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANTL')

plt.show()

Output results:

    cv2.BORDER_ Replicate copy method, copy the edge pixel CV2. Border_ Reflect reflection method, the interested image pixels on both sides of the entry CV2. Border_ Reflect101 reflection method, with the most edge pixel as the axis, symmetrical CV2. Border_Wrap method cv2.border_Constant good method

[Solved] Error starting proxy server: oserror (10013), “an attempt was made to access the socket in a way that the access permission is not allowed.”, None, 10013, None)

1. Problem description

Error in starting mitmproxy script

PS D:\D1\code\AutoTest\python_interface_autotest\PythonInterfaceAutoTest> cd .\chapter7\mitmproxy\
PS D:\D1\code\AutoTest\python_interface_autotest\PythonInterfaceAutoTest\chapter7\mitmproxy> mitmweb -s .\get_data.py
Error starting proxy server: OSError(10013, 'Made an attempt to access the socket in a way that access rights are not allowed.', None, 10013, None)
PS D:\D1\code\AutoTest\python_interface_autotest\PythonInterfaceAutoTest\chapter7\mitmproxy> mitmweb -s .\get_data.py
Error starting proxy server: OSError(10013, 'Made an attempt to access the socket in a way that access rights are not allowed.', None, 10013, None)

2. Problem solving

1. Specify the port number to resolve the port conflict

PS D:\D1\code\AutoTest\python_interface_autotest\PythonInterfaceAutoTest\chapter7\mitmproxy> mitmweb -s .\get_data.py -p 8083
Web server listening at http://127.0.0.1:8081/
Loading script .\get_data.py
Proxy server listening at http://*:8083

2. Query the process corresponding to the default startup port number 8080 and close it

[How to Solve] RuntimeError: CUDA out of memory.

Problem description

Runtimeerror: CUDA out of memory. Tried to allocate 1.26 gib (GPU 0; 6.00 GiB total capacity; 557.81 MiB already allocated; 2.74 GiB free; 1.36 gib reserved in total by pytorch)

Solution:

GPU cache is not enough
you can reduce the size of batch size properly
if it works properly
1. Restart the computer
restart the computer and close the occupied GPU process, which is a solution
2. Kill process
input

nvidia-smi

View the process

and enter

kill -9 PID

[Solved] From pip._internal import cmdoptions ImportError: cannot import name SourceDistribution

Background of the problem

When changing 32-bit Python to 64 bit, this problem suddenly appeared. I was so confused that PIP list PIP install couldn’t be used. I made a mistake

Solution:
first execute the command: Python - M ensurepip -- default PIP
Download get-pip.py at https://bootstrap.pypa.io/get-pip.py After entering, it is directly code, so you need to create a new get-pip.py file, copy and paste it, and finally enter the directory where the get-pip.py file is located from the command line CMD, Execute command: Python get pip. Py
note that permission error may be reported when executing this step. At this time, Python get pip. Py -- user should be executed
Let’s go on

How to enter the directory where the get-pip.py file is located, you can follow the steps below in general windows

      1. search for CMD in the lower left corner, enter the drive letter where the file is located, for example, my get pip.py file is in

D: , then enter CMD, enter D: and then copy the directory of the file, paste enter, my file is D: + enter
Postscript

After checking, it seems to say that PIP version 20. Has this problem, but PIP version 21. Is gone. Maybe there is a bug in the previous version

Tensor for argument #2 ‘mat1‘ is on CPU, but expected it to be on GPU (while checking arguments for

Tensor for argument #2 ‘mat1’ is on CPU, but expected it to be on GPU (while checking arguments for addmm)
Both the model and the input data need to be moved to the device

model=NonLinearRegression().to(device)#Moudle
for batch_idx,(data,target) in enumerate(train_loader):
	data,target=data.to(device),target.to(device)
	...
for data,target in val_loader: 
	data,target=data.to(device),target.to(device)
	...

To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe.

import numpy as np 
e = np.ones((3,3),np.float)# 3x3 floating-point 2-dimensional array, and initialize all elements to value 1

D:\projects\Numpy\array.py:25: DeprecationWarning:
np.float is a deprecated alias for the builtin float.
To silence this warning, use float by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use np.float64 here.
Deprecated in NumPy 1.20;
for more details and guidance:
https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

Change to:

import numpy as np 
e = np.ones((3,3),np.float64)# 3x3 floating-point 2-dimensional array, and initialize all elements to value 1

All right, we’re in the trough

[Solved] ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly

Solution

https://cryptography.io/en/latest/installation/

$ apk add gcc musl-dev python3-dev libffi-dev openssl-dev cargo
$ pip install --upgrade pip
$ export CRYPTOGRAPHY_DONT_BUILD_RUST=1
$ pip install cryptography

Solution process

      =============================DEBUG ASSISTANCE=============================
      If you are seeing a compilation error please try the following steps to
      successfully install cryptography:
      1) Upgrade to the latest pip and try again. This will fix errors for most
         users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip
      2) Read https://cryptography.io/en/latest/installation.html for specific
         instructions for your platform.
      3) Check our frequently asked questions for more information:
         https://cryptography.io/en/latest/faq.html
      4) Ensure you have a recent Rust toolchain installed:
         https://cryptography.io/en/latest/installation.html#rust
      5) If you are experiencing issues with Rust for *this release only* you may
         set the environment variable `CRYPTOGRAPHY_DONT_BUILD_RUST=1`.
      =============================DEBUG ASSISTANCE=============================

  error: can't find Rust compiler

  If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.

  To update pip, run:

      pip install --upgrade pip

  and then retry package installation.

  If you did intend to build this package from source, try installing a Rust compiler from your system package manager and ensure it is on the PATH during installation. Alternatively, rustup (available at https://rustup.rs) is the recommended way to download and update the Rust compiler toolchain.

  This package requires Rust >=1.41.0.
  ----------------------------------------
  ERROR: Failed building wheel for cryptography
Failed to build cryptography
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly

It is found that the solution is given above

      =============================DEBUG ASSISTANCE=============================
      If you are seeing a compilation error please try the following steps to
      successfully install cryptography:
      1) Upgrade to the latest pip and try again. This will fix errors for most
         users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip
      2) Read https://cryptography.io/en/latest/installation.html for specific
         instructions for your platform.
      3) Check our frequently asked questions for more information:
         https://cryptography.io/en/latest/faq.html
      4) Ensure you have a recent Rust toolchain installed:
         https://cryptography.io/en/latest/installation.html#rust
      5) If you are experiencing issues with Rust for *this release only* you may
         set the environment variable `CRYPTOGRAPHY_DONT_BUILD_RUST=1`.
      =============================DEBUG ASSISTANCE=============================

============================= Debugging assistance =============================
If you see a compilation error, try the following steps
Install encryption successfully:
1) Upgrade to the latest pip and try again. This will fix most errors
users. See:https://pip.pypa.io/en/stable/installing/ upgrading-pip
2) Read specifically https://cryptography.io/en/latest/installation.html
for your platform instructions.
3) Check out our FAQ for more information:
https://cryptography.io/en/latest/faq.html
4) Make sure you have recently installed the Rust toolchain:
https://cryptography.io/en/latest/installation.html#rust
5)If you are experiencing problems with Rust in *this version*, you can
set the environment variable ' CRYPTOGRAPHY_DONT_BUILD_RUST=1 '.
============================= Debugging assistance =============================

First, upgrade pip

pip install --upgrade pip

After I upgrade, I will install again or report an error (some people on the Internet have solved it, if you have solved it, ignore the following contents)

Continue to look at the above content and say that my rust version is too low
to view the official website, you need to install the relevant dependencies

https://cryptography.io/en/latest/installation/

sudo apk add gcc musl-dev python3-dev libffi-dev openssl-dev cargo

Re install or report an error, continue to follow the instructions to continue processing

     ERROR: Command errored out with exit status 1:
     command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-km3x31je/matplotlib_fcb1836ff32b459797e98afb66f6211e/setup.py'"'"'; __file__='"'"'/tmp/pip-install-km3x31je/matplotlib_fcb1836ff32b459797e98afb66f6211e/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-7833r8p7
         cwd: /tmp/pip-install-km3x31je/matplotlib_fcb1836ff32b459797e98afb66f6211e/
    Complete output (44 lines):
    WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'.
    ERROR: Could not find a version that satisfies the requirement numpy>=1.16 (from versions: none)
    ERROR: No matching distribution found for numpy>=1.16
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/setuptools/installer.py", line 75, in fetch_build_egg
        subprocess.check_call(cmd)
      File "/usr/local/lib/python3.7/subprocess.py", line 363, in check_call
        raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command '['/usr/local/bin/python', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmpd6d05k3_', '--quiet', 'numpy>=1.16']' returned non-zero exit status 1.

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-km3x31je/matplotlib_fcb1836ff32b459797e98afb66f6211e/setup.py", line 314, in <module>
        cmdclass=cmdclass,
      File "/usr/local/lib/python3.7/site-packages/setuptools/__init__.py", line 152, in setup
        _install_setup_requires(attrs)
      File "/usr/local/lib/python3.7/site-packages/setuptools/__init__.py", line 147, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "/usr/local/lib/python3.7/site-packages/setuptools/dist.py", line 782, in fetch_build_eggs
        replace_conflicting=True,
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 768, in resolve
        replace_conflicting=replace_conflicting
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1051, in best_match
        return self.obtain(req, installer)
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1063, in obtain
        return installer(requirement)
      File "/usr/local/lib/python3.7/site-packages/setuptools/dist.py", line 838, in fetch_build_egg
        return fetch_build_egg(self, req)
      File "/usr/local/lib/python3.7/site-packages/setuptools/installer.py", line 77, in fetch_build_egg
        raise DistutilsError(str(e)) from e
    distutils.errors.DistutilsError: Command '['/usr/local/bin/python', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmpd6d05k3_', '--quiet', 'numpy>=1.16']' returned non-zero exit status 1.

    Edit setup.cfg to change the build options; suppress output with --quiet.

    BUILDING MATPLOTLIB
      matplotlib: yes [3.4.2]
          python: yes [3.7.10 (default, Jun 29 2021, 01:54:47)  [GCC 10.3.1
                      20210424]]
        platform: yes [linux]
           tests: no  [skipping due to configuration]
          macosx: no  [Mac OS-X only]

Setting environment variables

export CRYPTOGRAPHY_DONT_BUILD_RUST=1
pip install cryptography

It was a success this time.

[Solved] Ubuntu18.04 Install pyqt5 error: Command “python setup.py egg_info“ failed with error code 1 in /tmp/pip-build-92

Error in installing pyqt5 on Ubuntu 18.04:
command “Python setup.py egg”_ info” failed with error code 1 in /tmp/pip-build-92ggdywh/PyQt5/

As a result, the version of PIP is too low. The default system version is pip9, so we need to update the PIP version
the update method is as follows:

python3 -m pip install --upgrade pip

Because most of the time, we install python, or apt install Python directly, resulting in the installation of python2.7. If you just want to use a version of python, such as python3, you can uninstall python2. It’s better to uninstall to avoid conflicts.

[Solved] Pytorch Tensor to numpy error: RuntimeError: Can‘t call numpy() on Tensor that requires grad.报错

Solution:

Use tensor. Detach(). Numpy() when turning numpy:

a = torch.ones(5)
b = a.detach().numpy()
print(b)

Problem analysis

When the tensor conversion in calculation, because it has gradient value, it cannot be directly converted to numpy format, so it is better to call . Detach(). Numpy() no matter how