Tag Archives: Computer vision

[Solved] OpenCV Import Error: ImportError: numpy.core.multiarray failed to import

cv2 import Error:

(paddle) C:\Windows\system32>python
Python 3.8.12 (default, Oct 12 2021, 03:01:40) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import cv2
ImportError: numpy.core.multiarray failed to import
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “D:\anaconda3\envs\paddle\lib\site-packages\cv2\__init__.py”, line 8, in <module>
from .cv2 import *
ImportError: numpy.core.multiarray failed to import
>>> exit()

Solution:

pip install -U numpy 

New problems,

(paddle) C:\Windows\system32>pip install -U numpy
Requirement already satisfied: numpy in d:\anaconda3\envs\paddle\lib\site-packages (1.19.3)
Collecting numpy
  Downloading numpy-1.22.3-cp38-cp38-win_amd64.whl (14.7 MB)
     |████████████████████████████████| 14.7 MB 547 kB/s
Installing collected packages: numpy
  Attempting uninstall: numpy
    Found existing installation: numpy 1.19.3
    Uninstalling numpy-1.19.3:
      Successfully uninstalled numpy-1.19.3
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
paddlepaddle-gpu 2.2.2 requires numpy<=1.19.3,>=1.13; python_version >= "3.5" and platform_system == "Windows", but you have numpy 1.22.3 which is incompatible.
openvino 2021.4.2 requires numpy<1.20,>=1.16.6, but you have numpy 1.22.3 which is incompatible.
openvino-dev 2021.4.2 requires numpy<1.20,>=1.16.6, but you have numpy 1.22.3 which is incompatible.
Successfully installed numpy-1.22.3

However, I tested it and found that this new error has not caused too many problems.

To meet compatibility, if you want to change back to the version, you can

pip install numpy==1.19.3
pip uninstall opencv-contrib-python
conda install opencv

Note that the following instructions will install (uninstall) the latest version of OpenCV,

pip (un)install opencv-contrib-python

 

Reference:

https://stackoverflow.com/questions/20518632/importerror-numpy-core-multiarray-failed-to-import

How to Solve Yolox Training C Disk Full Issue

0. Problem description: COCO dataset training to half suddenly interrupted, look at the C disk shows red, there is not much memory (training, generated in AppData/Temp in the temporary file too much)
As shown in the figure: as the epoch increases, the file is getting bigger and bigger (the figure is still yolox-tiny), if we use yolox-x, the C drive is directly full!

1. Problem Cause.
YOLOX-main/yolox/evaluators/coco_evaluator.py in line 203 or so **tempfile.mkstemp()** after creating the file, no close() and remove() operations are performed
The following figure.

2. Solution methods
(1) Method 1
As shown above, add os.close(_) and os.remove(tmp) two lines of code, directly delete the file just created after use. Note: import os module at the beginning]
(2) Method 2
The problem is already known, you can use with…as… to create, automatically delete and close the file.
(3) Method 3
If you want to keep each temporary file, and do not want to C drive blow up, then directly change the save location to a custom path.
Code location: Anoconda/envs/using-environment/Lib/tempfile.py in line 159-185.
directly change the direct dirlist operation to the user-defined folder location, as follows:

(4) Method 4
Manually clean up files in temp at regular intervals
Note: VOC format dataset training, no temporary files are generated because it uses the with…as… file creation method. For details, please refer to the end of voc_evaluater.py

[Solved] RuntimeError: Error(s) in loading state_dict for Model: Missing key(s) in state_dict

Error message:

Using the network weights trained by FCN, UNET and deeplab, an error is reported when loading the model:

RuntimeError: Error(s) in loading state_dict for Model: Missing key(s) in state_dict....

Training environment:

CPU:Intel E5
GPU: 3090*2
Pytorch1. ten

Solution:

Solve the mismatch problem
method 1 (invalid): the dictionary cannot match strictly. When the model is loaded, use the following code to add false to solve the mismatch problem

net.load_state_dict(t.load(ckpt_path),False)

Note: this method unlocks the strict matching and can ignore the error report. However, the model loaded by this method has problems in the actual segmentation effect due to the mismatch of parameters. Use it with caution!

Method 2: the network is the same, the only difference is that NN is used in the training process The dataparallel() method calls two graphics cards for training, so before loading the model weight, the model is also suitable for dataparallel packaging, which can solve the above error reporting problem.

net = nn.DataParallel(net)
net = net.to(device)

v2.error: OpenCV(4.5.5) error: (-215:Assertion failed) npoints > 0 in function ‘cv::drawContours‘

Error Messages: cv2.drawContours(thresh_Contours, cnts, -1, (0, 0, 255), 3)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\drawing.cpp:2502: error: (-215:Assertion failed) npoints > 0 in function ‘cv::drawContours’
Reason: Different Opencv versions cause errors

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(thresh_Contours, cnts, -1, (0, 0, 255), 3)

Correction method: change “1” to “0”

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(thresh_Contours, cnts, -1, (0, 0, 255), 3)

[Solved] cv2.error: OpenCV(4.5.1) XXX\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 &&……

Error resolution

Error reproduction

Traceback (most recent call last):
  File "D:/pythonProjects/Object_movement/object_movement.py", line 88, in <module>
    c = max(cnts, key=cv2.contourArea)
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-i1s8y2i1\opencv\modules\imgproc\src\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::contourArea'

source code

cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)
cnts=cnts[1]

Modified code

cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

Error reporting reason

New CV2 Findcontours returns two values. The result of [0] is contour instead of [1]

RuntimeError: Exporting the operator uniform to ONNX opset version 12 is not supported.

Pt to onnx error:

RuntimeError: Exporting the operator uniform to ONNX opset version 12 is not supported. 
Please open a bug to request ONNX export support for the missing operator.

The reason is that during conversion, you can’t dynamically obtain the value in forward for operation, but complete the corresponding operation in init..

[Solved] cv2.xfeatures2d.SIFT_create() Error: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’

Problem Description:

In the experiment of digital image processing course, SIFT algorithm is used in the feature matching experiment, and opencv4 is used for the first time with vscode 4 and python 3 8. An error is reported

module 'cv2.cv2' has no attribute 'xfeatures2d'

Then install the opencv Python 3.4.2.16 command in Anaconda prompt as follows, and an error occurs that the relevant version cannot be found

pip install opencv-python==3.4.2.16

And report an error as

cv2.error: OpenCV(3.4.8) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create'

Cause analysis

The reason for the first error is opencv4 Version 4 cannot be used due to sift patent; The second error is due to opencv4 2 and python 3 8 mismatch, need to be reduced to 3.6; This error is still a problem with the opencv version

Solution:

If it’s Python 3.6. You only need to install the package of the relevant version of OpenCV. Execute the following command in Anaconda prompt

pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16

Because I’m Python 3.8. Therefore, a virtual environment py36 is created for related configuration. For creating a virtual environment and activating a virtual environment, please refer to the creating a virtual environment – brief book in Anaconda blog, and then execute the above command in the activated virtual environment

Finally, run the PY file in the vs Code terminal

[Solved] ORB_SLAM3 Compile Error: opencv4.0 not found four

CMake Warning at CMakeLists.txt:33 (find_package):
  Could not find a configuration file for package "OpenCV" that is compatible
  with requested version "4.4".

  The following configuration files were considered but not accepted:

    /usr/share/OpenCV/OpenCVConfig.cmake, version: 3.2.0



CMake Error at CMakeLists.txt:35 (message):
  OpenCV > 4.4 not found.


-- Configuring incomplete, errors occurred!
See also "/home/tys/ORB_SLAM3/build/CMakeFiles/CMakeOutput.log".
make: *** No target specified and no makefile found. Stop.

The content of the error report is as above. I found a solution, and there is a solution available.

LIST(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules)

find_package(OpenCV 4.4)
   if(NOT OpenCV_FOUND)
      message(FATAL_ERROR "OpenCV > 4.4 not found.")
   endif()

Find the above location in CMakeList.txt in the ORB_SLAM3 folder and modify

find_package(OpenCV 4.4), as shown in the following code.

LIST(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules)

find_package(OpenCV 3 REQUIRED)
   if(NOT OpenCV_FOUND)
      message(FATAL_ERROR "OpenCV > 4.4 not found.")
   endif()

Normal, so that the fault can be solved.

[Solved] error: (-215:Assertion failed) size.width>0 && size.height>0 in function ‘imshow‘

Error: cv2.error: OpenCV(4.5.4) /tmp/pip-req-build-w88qv8vs/opencv/modules/highgui/src/window.cpp:1006: error: (-215:Assertion failed) size.width>0 && size.height>0 in function ‘imshow’
Check if there is a problem with the image path:

It is found that None ==> You cannot use “~” to formulate the path, just modify it to the full path:

[Solved] torch Do Targer Detection Error: RuntimeError: CUDA error: device-side assert triggered

When training torchvision’s maskrcnn with your own data, the following errors are reported:

Traceback (most recent call last):
  File "main_train_detection.py", line 232, in <module>
    main(params)
  File "main_train_detection.py", line 201, in main
    train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
  File "/raid/huaqing/tyler/suzhou/code/utils/engine.py", line 37, in train_one_epoch
    loss_dict = model(images, targets)
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/torchvision/models/detection/generalized_rcnn.py", line 97, in forward
    detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets)
  File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/torchvision/models/detection/roi_heads.py", line 760, in forward
    loss_classifier, loss_box_reg = fastrcnn_loss(
  File "/usr/local/lib/python3.8/dist-packages/torchvision/models/detection/roi_heads.py", line 40, in fastrcnn_loss
    sampled_pos_inds_subset = torch.where(labels > 0)[0]
RuntimeError: CUDA error: device-side assert triggered
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.

The root cause is that the category label is not numbered from 0:
there are actually three categories of targets to be identified, so the total number of categories set is 3 Then set the corresponding relationship between category labels and categories as follows:

cls_dict = {'holes':1, 'marker':2, 'band':3}.

When numbering category labels, they are actually numbered from 0. For a total of 3 categories, the label numbers are 0, 1 and 2 respectively In other words, there is no label = = 3 category Therefore, the above CLS_Dict is adopted, which will cause the number of band class to overflow It should be corrected as follows:

cls_dict = {'holes':0, 'marker':1, 'band':2}

[Solved] OpenCV VideoWriter Error: FFMPEG: tag ‘MP4V‘ is not supported with codec id 12 and format mp4

1. Problem code

A few months ago, a piece of code could be executed normally. Some of the codes are as follows:

def buildVideoByCV():
    videoMake = cv2.VideoWriter()
    fourcc = cv2.VideoWriter_fourcc(*'MP4V') #https://blog.csdn.net/whudee/article/details/108689420
    fps = 12
    videoMake.open(r"g:\video\lightShowCV.MP4", fourcc, fps, (800,600))

    for t in range(65*fps):
        img = makeframe(t*1.0/fps)
        videoMake.write(img)
        if t%20==0:print(f'\r视频制作进度:{(t*100.0)/(66*fps):4.2f}%',end='')
    videoMake.release()

2. Error message

Error in execution today:

Video production progress: 95.96%OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 12 and format 'mp4/MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

3. Solution

Set FourCC = cv2.videowriter_FourCC (*'mp4v') is changed to: FourCC = CV2.Videowriter_FourCC (*'mp4v') , just change the encoded uppercase mp4v to lowercase.

4. Summary

This paper introduces the solution to the error reported by opencv videowriter: ffmpeg: tag ‘mp4v’ is not supported. You only need to replace the code ‘mp4v’ with ‘mp4v’.

[Solved] Android Studio Error: Use of undeclared identifier ‘cv‘

Problem description

This error occurs when I use the opencv3.4.16 official so file in Android studio

Sort by Pvalue from smallest to largest

Change the build.gradle file

Change arguments “- dandroid_stl = C + + _shared”
to arguments “- dandroid_stl = gnustl_shared”

Possible causes:

Opencv3.4.16 officially uses the gun compiler, so it is specified as gnustl_shared