Category Archives: Python

[Solved] python opencv Error: findContours() Can only use the Grayscale

Original program

import cv2
import numpy as np


def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# Read the image
img = cv2.imread('contours.png')
cv_show('contours', img)

# Grayscale and binarization
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1]
cv_show('thresh', thresh)

# Find the outline
cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]

# Draw the outline
draw = img.copy()
res = cv2.drawContours(draw, cnt, -1, (0, 0, 255), 2)
cv_show('res', res)

report errors

Traceback (most recent call last):
  File "C:/Users/ccccj/PycharmProjects/a_opencv/opencv/opencv_notebook/ppt/ppt_season_2-8/2-7_notebook/image_operation/contours.py", line 21, in <module>
    cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]
cv2.error: OpenCV(3.4.11) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-7_3trius\opencv\modules\imgproc\src\contours.cpp:197: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFindContours_Impl'

Reason: the SRC of findcontours() function must be a grayscale image. The original program uses img, which is changed to the following:

# Find the outline
# cnt = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]


# Modify to:
cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[1]

[Solved] Forbidden (403) CSRF verification failed. Request aborted.

It is a cross site problem and a Django prevention mechanism. The error reports are as follows:

Generally, this can happen when a genuine cross-site request is forged, or when Django’s CSRF mechanism is not being used correctly. For POST forms, you need to make sure that:
Your browser is accepting cookies.
The view function passes a request to the template’s rendering method.
In the template, each POST form has a {% csrf_token %} template token pointing to an internal URL.

If you are not using the CsrfViewMiddleware, then you must use csrf_protect on any view that uses the csrf_token template tag and on those views that accept POST data.

The form has a valid CSRF token. You may need to reload the page with the form after logging in to another browser tab or clicking the back button after logging in, as the token is rotated after logging in.

You will see the help section of this page because there is DEBUG = True in your Django settings file. changing it to False will only show the initial error message.
You can customize this page using the CSRF_FAILURE_VIEW setting.
As the error message suggests, there are two ways we can do this.
1. go to setting and comment out # ‘django.middleware.csrf.CsrfViewMiddleware’
This is the same as removing the middleware from the cross-site prevention mechanism. Then not this error is reported, but if we really encounter cross-domain problems, we may not know it is reported this error, not very recommended.
2. Add {% csrf_token %} to the form below

[Solved] Flask Application Context Error: RuntimeError: Working outside of application context.

[problem description]

The author encountered a classic error in flash. The error information is as follows:

[problem analysis]

application context is the application context of Flask, which contains variables such as app and g. When it is not convenient to operate app, we use current_app instead of app. current_app can only be accessed when processing requests, and I used current_app outside of processing requests, so an error was reported. Specifically, I used current_app in a custom tool class, ran the program, and could not get the application context when the program loaded the tool class, so the error was reported. The error code is as follows.

[problem-solving]

Since you can’t use current_app in the class property in the tool class, comment out the code and put it in the class method, and modify it as follows. The class method defined by me is used in the view, so the current_app is used in the view when processing the request, so no error will be reported and the problem is solved.

[Solved] Model training Error: _pickle.PicklingError: Can’t pickle

How to Solve Model training Error: _pickle.Picklingerror: can’t pickle

 

1. Problem description

Recently, when learning the target tracking model of siamfc model, it is found that the following problems always occur during model training on window platform:

_pickle.PicklingError: Can’t pickle <class ‘pairwise.GenericDict’>: attribute lookup GenericDict on pairwise failed

See the following figure for details:

2. Solution

The main problem is that the code is written on Linux platform, test.py has no problem in actual operation, but train.py has problem in window platform, the main problem is on Dataloader, so we can modify this part of the code. The main problem lies in the Dataloader, so we can modify this part of the code. Or we can directly train and test the model under Linux with the source code.

The solution to this problem on Window platform is as follows:

Modify the original code from num_workers = 4 to num_workers = 0 and it will work as follows.

after the modification is completed, the operation effect is as follows:

[Solved] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter st

When using tensorflow.keras, this error is often reported during model training:

tensorflow/core/kernels/data/generator_dataset_op.cc:107] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated.
	 [[{{node PyFunc}}]]
tensorflow/core/kernels/data/generator_dataset_op.cc:107] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated.

       [[{{node PyFunc}}]]

 

According to my own experience, there are several reasons for this errory:

1. The input image_size and input_shape does not match or is not defined when the model is built. Note that the input_shape must be defined when defining the first layer of the convolutional layer, e.g.

    model = keras.models.Sequential([
        # Input image [None,224,224,3]
        # Convolution layer 1: 32 5*5*3 filters, step size set to 1, fill set to same
        # Output [None,32,32,3]
        keras.layers.Conv2D(32, kernel_size=5, strides=1, padding='same', data_format='channels_last',
                            activation='relu', input_shape=(224, 224, 3)),

2. There is also train_generator and validate_generator related parameters must be consistent, such as batch_size, target_size, class_mode, etc.

3. The configuration limit itself, try to change the batch_size to a smaller size, or even to 1

4. The last program did not finish completely, finish all python programs to see.

[Solved] urllib.error.URLError: <urlopen error [SSL: WRONG_VERSION_NUMBER] wrong version number

There are totally four methods to solve this error

 

Solution:
Method 1: the SSL certificate problem
you can open the URL with the following code

import ssl
 
# This restores the same behavior as before.
context = ssl._create_unverified_context()
response = urllib.request.urlopen("https://no-valid-cert", context=context)

https://no-valid-cert you can change it to the website you want

Method 2: Change https to http, because some versions of python verify the SSL certificate once when you urllib.urlopen an https.

Method 3: Add the following codes:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context

I just add it to the py file when calling commands from the urllib library that comes with python 3.8.0

model = ALBEF(config=config, text_encoder=args.text_encoder, tokenizer=tokenizer, init_deit=True)

That is, when the model is initialized (init_deit), the error occurs when calling return self.sslsocket_class._create in lib/python3.8/http/client.py under python 3.8, but at the beginning of the py file for initializing the model Add these two lines and you’ll be fine

Method 4:
Upgrade your python interpreter version, e.g. 2.7 or 3.7 to 3.8 or even 3.9

[Solved] AttributeError: ‘_IncompatibleKeys‘ object has no attribute ‘parameters‘

Errors are reported when running the pytorch program. It should be a problem with the torch syntax.

Original code:

model=CNN()#CNN as a self-compiling neural network model
best_model_wts = copy.deepcopy(model.state_dict())
*************************************#(the error codes is below)
model=model.load_state_dict(best_model_wts)

Error message:

Modified code:

model=CNN()#CNN as a self-compiling neural network model
best_model_wts = copy.deepcopy(model.state_dict())
model.load_state_dict(best_model_wts)

Python 3.7 Error: AttributeError: ‘str‘ object has no attribute ‘decode‘ [How to Solve]

Background

python 3.7.6
django 2.2

Phenomenon

Execute Python manage Error in py makemigrations:

  File "E:\software\Python3-64bit\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

reason:

The reason is unknown. This problem will occur in some versions.

Solution:

Modify line 146 of {PYHTON_HOME}\lib\site-packages\django\db\backends\mysql\operations.py to change
query = query.decode(errors=’replace’) to query = query.encode(errors=’replace’)

[Solved] RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dim

Error Messages:
tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
RuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0

Error Reason:
Dimensional information mismatch

Original Code:

image = Image.open(image_path)

After modification:

image = Image.open(image_path).convert('RGB')

Python Openyxl Error: AttributeError: ‘int‘ object has no attribute ‘upper‘ [How to Solve]

preface

I use the openpyxl library. When I want to read out a value and put it into a variable, there is an error like the title.

Wrong line

I wanted to read the contents of cell A1 into the value variable, but there was an error in the execution of the code.

value = sheet.cell(1, 1).value

How to Solve:

After Reading some articles, it is found that the parameter dislocation problem is caused by the openpyxl version. The first and second parameters of this version are not row and column. Reading this, I believe there must be a smart little partner who came up with a solution. This paper lists two solutions.

Solution 1:

Set the first parameter to null

value = sheet.cell(None, 1, 1).value

Solution 2:

It’s okay if you don’t want to write None. Just write the assignment to the specified parameter directly in parentheses.

value = sheet.cell(row=1, column=1).value

Summary

The execution effect of these two methods is the same. The first method is to copy an unnecessary variable as empty. The second method is to copy the specified variable without caring about other variables.

Both methods have the same goal, but I prefer the second method, so that we can no longer worry about dislocation and write the position freely, while the first method locks the position of parameter input.

Examples

When using the first method

1. The first line of code below will read the values of the cells in the first line and the second column

2. The second line of code below will read the value of the cell in the first column of the second line

value = sheet.cell(None, 1, 2).value
value = sheet.cell(None, 2, 1).value

When using the second method

1. The execution effect of the following two lines of code is the same. They both get values from the cells in the first row and the second column

value = sheet.cell(column=2, row=1).value
value = sheet.cell(row=1, column=2).value