Tag Archives: python

[Solved] R Error: Python module tensorflow.keras was not found.

Scenario:

rstudio reported error R: Python module tensorflow.keras was not found.
at first, I suspected that I could not accurately locate the keras package of R, because I was using Anaconda to do other things, but later I saw other error reports and felt that they were not so complex… Later, I found that they were just simple and not installed properly… In short, the solution is as follows


Solution:

terminal input:

install.packages(tensorflow)
install_tensorflow()
library(tensorflow)
#Keras The R interface uses the TensorFlow backend engine.
# To install the core Keras library and TensorFlow backend, use the install_keras() function
install_keras()
library(keras)
# Run them all and then tune the package, if you have already done so, restart RStudio
-------------------------------------------
#Other solutions to this problem are as follows:
library(tensorflow)
library(keras)
use_condaenv("r-tensorflow")

Pip3 install Mysqlclient Error: Command “python setup.py egg_info“ failed with error

pip3 install mysqlclient error Command “python setup.py egg_info” failed with error
1. Software description

    centos 8.0python3.6

2. Problem description
Use the command

pip3 install mysqlclient
error
[root@z ~]# pip3 install mysqlclient
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting mysqlclient
  Using cached https://files.pythonhosted.org/packages/3c/df/59cd2fa5e48d0804d213bdcb1acb4d08c403b61c7ff7ed4dd4a6a2deb3f7/mysqlclient-2.0.3.tar.gz
    Complete output from command python setup.py egg_info:
    /bin/sh: mysql_config: Command not found
    /bin/sh: mariadb_config: Command not found
    /bin/sh: mysql_config: Command not found
    mysql_config --version
    mariadb_config --version
    mysql_config --libs
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-8k22usrq/mysqlclient/setup.py", line 15, in <module>
        metadata, options = get_config()
      File "/tmp/pip-build-8k22usrq/mysqlclient/setup_posix.py", line 70, in get_config
        libs = mysql_config("libs")
      File "/tmp/pip-build-8k22usrq/mysqlclient/setup_posix.py", line 31, in mysql_config
        raise OSError("{} not found".format(_mysql_config_path))
    OSError: mysql_config not found
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-8k22usrq/mysqlclient/

3. Solutions

yum install python3-devel mysql-devel 

[Perfectly Solved] attributeerror: module ‘SciPy. Misc’ has no attribute ‘toimage’ error

Problem Description:

When learning the MNIST machine learning introductory course, the attributeerror: module ‘SciPy. Misc’ has no attribute ‘toimage’ error occurs when converting the numpy array into a picture and saving it
the execution code is as follows:

# Save the first 20 images
for i in range(20):
    image_array = train_images[i]
    #Save file as the format:mnist_train_0.jpg,mnist_train_1.jpg,...
    filename = save_dir + '/mnist_train_%d.jpg' %i
    #save image_array to image
    # use scipy.misc.toimage to convert to image and save
    scipy.misc.toimage(image_array, cmin=0.0, cmax=1.0).save(filename)

Crux attribution:
I checked the scene where Python 3 uses the toimage() function on the Internet and found that this function has been deprecated. Many tutorials recommend reducing the version of the third-party SciPy to match the use of the toimage() function. I feel that this is a bit “married down” and can not fundamentally solve the problem. Moreover, the iteration of technology update is inevitable, We need to follow the trend.

Scipy.misc.toimage official latest instructions.

Solution:

Turn the problem into how to save the array as an image?

Method 1: use the .Imwrite() function of CV2 module to convert the numpy array into an image and save it. The specific codes are as follows:

cv2.imwrite(filename, image_array)  #Mutual transformation of images and numpy arrays using cv2

Method 2: use the .Fromarray() function under Image in PIL module to convert the numpy array into an image and save it. The specific codes are as follows:

from PIL import Image
Image.fromarray((image_array)).save(filename)  #Mutual transformation of images and numpy arrays using PIL
# or
Image.fromarray((image_array*255).astype('uint8'), mode='L').convert('RGB').save(filename)  # For processing color images

Method 3: use the Matplotlib module to convert the numpy array into a picture and save it. (including two methods): (1) preferred recommendation:   Use the . Imsave() function under Image in the Matplotlib module to convert the numpy array into an image for saving. The specific codes are as follows:

from matplotlib import image
image.imsave(filename,image_array,cmap='gray')  # cmap is often used to change the drawing style, such as black and white gray, emerald green virdidis

(2) Not recommended:   Use the .Savefig() function under pyplot in Matplotlib module to convert the numpy array into a picture for saving. The generated picture contains coordinate axis and border information. The specific codes are as follows:

import matplotlib.pyplot as plt
# Drawing pictures
plt.imshow(image_array,cmap='gray')
# save image
plt.savefig(filename) # In this case, the picture variable is already specified when drawing the picture, so there is no need to specify it again when saving

raise RuntimeError(RuntimeError: ‘cryptography‘ package is required for sha256_password or caching

The Django project in normal operation was written before. After a period of time, when the project is run again, an error occurs when Python manage.py runserver is started:

Reason: when connecting to the database, cryptography   The package is required.

Solution: PIP install   cryptography。

Run again to successfully resolve:

 

 

 

SyntaxError: (unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 2-3: truncated \UX

…2222312; and 20064; and to authenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthenticauthentic2222222222222222222222222222222222222222222222220; and to your 20340; and to 382382382; and to 38203822222222222220; and to 3823820;.382222222222222220;.1997992;65292. usr/bin/python3
35;–coding: UTF-8
import os, sys

*25171;*24320;*20214

fd = os.open(“C:Users\ericDesktoppythonfoot.txt”, os.o.o. RDWR 124os.o. CREAT)

*22797;*21046;*20214;*2551;*36848;*31526;

d o u fd= os.dup(fd)

.20351; -29992; -22797; -21046; -30340; -20214; -2551; -36848; -31526; -20889; -20837;*

os.write(d.u fd, “This is test”.encode())

*20851;*38381;*20214

closerange(fd, d.u.fd)

print (“20851;”38381;”25152;”26377;”20214;”25104;”21151!!”

File, line 6.br> fd.open(“C:Users s\eric\Desktoppython\foot.txt”, as.O.R.WR124.o.o.CREAT
SyntaxErro: (unicoerror)’unicodeescapcan’codecan’t decodes in 2-3-3-position: trun244..23601;-26159;65306;SyntaxError:-652881;unicorn 38169;-3582365289; ‘Unico-Scape’int32534;’352991.30721;’222212080;’and.35861;’3072122222-30120013;’30340;* and 33410410;6530630130000;’260290290;UX br>382;’39064;’280-78530630620303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030663;.xx26159;65292;x24517;.21435;.25481;.36716;.20041;20.br>26041;.27861;.19968;6530630621152;r242437821046;’2121991;.e36716;.20016;.20041;and 20999999990;.26041;.26041;.222222222222209999999999999999999999996;;;;,1963063066306669666669999999999999999999996ericDesktoppythonfoot.txt”, os.o. RDWR 124s.o.o. CREAT
26041; 27861; 653062.
fd open(“C:Users\eric Desktoppythonfoot.txt o.O.R.R.124s.O.CREAT
26041;<27861;
19977;65306;27491;<26012;<464;<27861 br> fd.open(“C:/Users/eric/Desktop/python/foot.txt”), O.b.

AttributeError:‘AxesSubplot’object has no attribute‘bar_label’

Question:

Using bar in Matplotlib_ An error was encountered in the label function:
attributeerror: 'axessubplot' object has no attribute 'bar_ label'

resolvent:

Because the version of Matplotlib is too low, you need to reinstall Matplotlib (enter the following command in the console)

① Uninstall Matplotlib

conda uninstall matplotlib

② Download again

pip install matplotlib

[Solved] error: when using the property decorator in Python, an error occurs: typeerror: descriptor ‘setter’ requires a ‘property’ object but

Error message

• When we use the property decorator, the following errors may be caused by the wrong writing of the decorator Name:

TypeError: descriptor 'setter' requires a 'property' object but received a 'function'

Problem analysis

• The reason for this error is that we write all decorator names as property instead of the same method name in our class:

Problem code

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

    @property
    def age_test(self):
        return self.age

    @property.setter   # error
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

Resolve error reporting

• Change the name of the decorator with an error in the figure to the same name set in our class to solve this error
the code is as follows:

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

    @property
    def age_test(self):
        return self.age

    @age_test.setter # 修改的代码行
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

How to Solve Opencv Reads Video Error: cv2.error

Recently, due to the needs of the project, I often need to use OpenCV to read video. I often encounter a problem that an error will be reported after reading the video. Although it does not affect the code results, I really can’t stand being picky.

Error reporting procedures:

# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2


def read_video(video_path: str):
    """
    OpenCV read video widget, solve the video read error problem
    :param video_path: input the path of the video file to be read
    :return: no return value
    """
    print('Video path:', video_path)
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        # get a frame
        ret, frame = cap.read()

        cv2.imshow("capture", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('Read through the video!')
    cap.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\multi_insect_videos\multi_object00.mp4'
    read_video(path)

You can read the video normally, but the result will output an error

Traceback (most recent call last):
  File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 76, in <module>
    read_video(path)
  File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 65, in read_video
    cv2.imshow("capture", frame)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-uzca7qz1\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

The reason is that after the video is finished, the imshow() function of OpenCV can’t read the frame and makes an error. Solution: add judgment before imshow(). Read-only when there are frames. Exit the loop directly when there are no frames.

Error-free code:

# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2


def read_video(video_path: str):
    """
    OpenCV read video widget, solve the video read error problem
    :param video_path: input the path of the video file to be read
    :return: no return value
    """
    print('Video path:', video_path)
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        # get a frame
        ret, frame = cap.read()
        if not ret:
            break
        cv2.imshow("capture", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('Read through the video!')
    cap.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\multi_insect_videos\multi_object00.mp4'
    read_video(path)

Program output results:

Video path: D:\multi_insect_videos\multi_object00.mp4
Read through the video!

Process finished with exit code 0

[Solved] Python 3.7 from collections import Iterable Error

Python 3.7 use from collections import Iterable error

Error Message:
DeprecationWarning: Using or importing the ABCs from ‘collections’ instead of from ‘collections.abc’ is deprecated, and in 3.8 it will stop working
from collections import Iterable

Solution:
Change to from collections.abc import Iterable

Python2.7 Pyinstaller Install Error: ERROR: Command errored out with exit status 1

Python2.7 pyinstaller installation error: Command erred out with exit status 1


Error reporting reason:

Installing pyinstaller directly in python2.7 will report an error. Version 4 is incompatible with python2, so we need to specify a compatible pyinstaller version number during installation. The installation commands are as follows:

pip install pyinstaller==3.2.1

Py2exe installation command

pip install py2exe==0.6.9 

[Solved] ModuleNotFoundError: No module named ‘_polyiou‘

Problem recurrence

//install swig
sudo apt-get install swig
swig -c++ -python polyiou.i
python setup.py build_ext --inplace

//report error
ModuleNotFoundError: No module named '_polyiou'

Solution:

Swig is not installed correctly. Because there are python2 and python3 in the environment, the command to install swig is modified as follows

sudo apt-get install swig
swig -c++ -python polyiou.i
python3 setup.py build_ext --inplace