Tag Archives: OpenCV

Opencv detection yolov4 target detection video stream error

I encountered a bug today. I didn’t have a problem before, but I have a problem today

There is no problem with yolov4 target detection image. There is a problem with this test video or calling camera detection

Report the following error:

TypeError: Expected cv::UMat for argument ‘src’

src data type = 17 is not supported

Repeated installation of OpenCV and numpy versions keeps reporting this error

Later, I thought it might be because the dataset pictures were in Chinese, so I renamed the pictures and re labeled them. The labels were also in English, and then I trained. After training, I found that there were still problems.

Finally, it is found that the result of Yolo prediction code is not directly returned to the picture,

images = yolo.detect_ image(image)
r_ image = images.get(‘image’)

The picture is in the dictionary

When the video is called

frame = np.array(yolo.detect_image(frame))

It needs to be changed to

frame = yolo.detect_ image(frame)
frame = np.array(frame.get(‘image’))

Moreover, Chinese pictures and Chinese labels have no effect.

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

Error encountered during QT + opencv compilation: file not recognized: file format not recognized error resolution

catalogue

1. Error message:

2. Analysis  

3. Solution


1. Error message:

D:\InstallSoftware\opencv\OpenCV-MinGW-Build-OpenCV-4.5.2-x64\x64\mingw\bin\libopencv_ calib3d452.dll:-1: error: file not recognized: File format not recognized

2. Analysis  

This is because the opencv compiled file version is different from the QT project version. You should choose the correct version of the toolkit.

3. Solution

For example, my opencv compilation file is opencv build_ 64 bit, then select MinGW 64 bit for the project.

 

Error when using OpenCV: use of unclared identifier ‘CV_ Bgr2rgb ‘solution

catalogue

1. Error message:

2. Analysis:

3. Solution:

1. Error message:

F:\test\Qt-Demo\mainwindow.cpp:55: error: use of undeclared identifier ‘CV_ BGR2RGB’

2. Analysis:

Because opencv is used   CV_ Bgr2gray did not declare it. Therefore, an undeclared identifier is prompted.

3. Solution:

Reference the following code in the header file:

#include < opencv2\imgproc\types_ c.h>

Cv2.dnn read model error [How to Solve]

cv2.dnn read model error:

D:\ProgramData\Miniconda3\python.exe D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp (1878) cv::dnn::dnn4_v20201117::ONNXImporter::handleNode DNN/ONNX: ERROR during processing node with 2 inputs and 1 outputs: [Add]:(430)
Traceback (most recent call last):
  File "D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py", line 126, in <module>
    yolonet = yolov5(confThreshold=args.confThreshold, nmsThreshold=args.nmsThreshold, objThreshold=args.objThreshold)
  File "D:/project/detect/face/yolov5-face-landmarks-opencv/main_new.py", line 23, in __init__
    self.net = cv2.dnn.readNet(r'D:\project\detect\face\yolov5-face-master\yolov5n-face.onnx')
cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp:1887: error: (-2:Unspecified error) in function 'cv::dnn::dnn4_v20201117::ONNXImporter::handleNode'
> Node [Add]:(430) parse error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-oduouqig\opencv\modules\dnn\src\onnx\onnx_importer.cpp:780: error: (-215:Assertion failed) blob_0.size == blob_1.size in function 'cv::dnn::dnn4_v20201117::ONNXImporter::handleNode'
>
Process finished with exit code 1

Reason:
opencv4.5.1 torch 1.9.0
torch1.9.0 export onnx,opencv4.5.1not supported

Solution:
torch change to version 1.7.1, torchvision 0.8.2 version  —–the other version wil report an error.

Solution to error reporting in opencv4.0 compilation of logo-logo

Problem Description:

Recently, when learning integrated navigation, Ubuntu 20 + opencv4.0 was used. When compiling logo-beam, the following error messages were encountered:

10: fatal error: opencv/CV. H: no such file or directory
13 |#include & lt; opencv/cv.h>

Solution:

This is caused by the version change of OpenCV library. Put #include & lt; opencv/cv.h> Replace with #include & lt; opencv2/opencv.hpp> Just.

[Solved] Unity3d reports an error using the opencv plug-in: unsafe code may only appear if compiling with/unsafe.

Problem description

When using the opencv for unity plug-in, the error “assets \ opencvforunity \ examples \ advanced \ alphablendingexample \ alphablendingexample. CS (530, 17): error CS0227: Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in the inspector for ‘Assets/OpenCVForUnity/EnoxSoftware.OpenCVForUnity.asmdef’ to fix this error.”

Solution:

There are two ways to modify:

1. Tools entry modification

Tools > on the upper side of the window; OpenCV For Unity > Check use unsafe code
as shown below:

However, if there may be no such entrance, use method 2

2. Modify asmdef file

The. Asmdef file is an assembly definition file. This method is also available in the error prompt
modify the file in the path of assets/opencvforunity/enoxsoftware.opencvforunity.asmdef. After selecting the file, check the allow ‘unsafe’ code option in the inspector window and click apply.

How to Solve Msys2/mingw64 Run cmake GUI Error

August 24, 2021
It has been updated to the latest version.

MINGW64 ~
$ cmake-gui –version
cmake version 3.21.1
CMake suite maintained and supported by Kitware (kitware.com/cmake).

But still error as below:

$ cmake-gui
C:/msys64/mingw64/bin/cmake-gui.exe: error while loading shared libraries: zlib1.dll: cannot open shared object file: No such file or directory

Finally found that the installation of qt5 can be solved

pacman -S mingw-w64-x86_64-qt5
resolving dependencies…
looking for conflicting packages…
Packages (16) mingw-w64-x86_64-assimp-5.0.1-11  mingw-w64-x86_64-dbus-1.12.20-3  mingw-w64-x86_64-double-conversion-3.1.5-1  mingw-w64-x86_64-icu-debug-libs-68.2-3  mingw-w64-x86_64-libgcrypt-1.9.2-2
mingw-w64-x86_64-libgpg-error-1.42-1  mingw-w64-x86_64-libmng-2.0.3-4  mingw-w64-x86_64-libmysofa-1.2-1  mingw-w64-x86_64-libxslt-1.1.34-4  mingw-w64-x86_64-minizip-git-1.2.445.e67b996-2  mingw-w64-x86_64-openal-1.21.1-2
mingw-w64-x86_64-pcre2-10.36-1  mingw-w64-x86_64-qtbinpatcher-2.2.0-4  mingw-w64-x86_64-xpm-nox-4.2.0-6  mingw-w64-x86_64-z3-4.8.9-2  mingw-w64-x86_64-qt5-5.15.2-10
Total Download Size:   223.16 MiB
Total Installed Size:  873.75 MiB
…………………………

then re-run:

cmake-gui

You will be able to value the dialog box of the gui pop-up!

C++ Opencv+BaiDu OCR“error“: “unsupported_grant_type“, “error_description“: “The authorization grant

1. Baidu general reference: authentication mechanism

https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

Introduction
this document is mainly for HTTP API callers. Baidu AIP open platform uses oauth2.0 authorization to call the open API. When calling the API, you must bring access in the URL_ Token parameter. The process of obtaining access token is as follows:

Get access token
request URL data format

To the authorized service address https://aip.baidubce.com/oauth/2.0/token Send the request (post is recommended), and take the following parameters in the URL:

grant_ Type: required parameter, fixed to client_ credentials;
client_ ID: required parameter, API key applied
client_ Secret: required parameter, the applied secret key;

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&c

2. However, the result of my test is:

https://aip.baidubce.com/oauth/2.0/token

Postman test

{

    " grant_type": "client_credentials",

    "client_id": "pGB2vIVTXn9ATexEsqMIDYO",

   "client_secret": "5yNZqWSIuj4PVRGdavjw1e5U3z9K6Kb"

}

Get the token value and display the following results

{
    "error": "unsupported_grant_type",
    "error_description": "The authorization grant type is not supported"
}

cv2 error – function not implemented [How to Solve]

Run target detection, import CV2   Normal, CV2. Write() is OK, but CV2. Imshow() has an error: function not implemented, prompting windows and Ubuntu to install libgtk2.0-dev and PKG config, re run cmake

PIP install opencv Python runs unresponsive.

Recall that Anaconda was installed later and uninstalled first. Sure enough, the original opencv relied on Python 3.8 of Ubuntu 20.04.

uninstall  After installation, reinstall install and everything is normal.

Solve the problem of error reporting from scipy.misc import imread & imresize in Python

from scipy.misc import imread& imresize

Problem description solution 1 solution 2

Problem description

from scipy.misc import imread # error

After query, the reason is that the from scipy.misc import imread, imwrite and other methods have been abandoned, and python has encapsulated the imread method in the imageio module

Solution 1

To install the imageio Library:

pip install imageio 

Normal use!

import imageio
imageio.imread("xxxx.png")

Solution 2

If the higher version is discarded, we can reduce the SciPy version!

Reduce the SciPy version to 1.2.1

pip install scipy==1.2.1

[Solved] CAP_IMAGES: can‘t find starting number (in the name of file)

Solve cap_ IMAGES: can’t find starting number (in the name of file)

1. Solutions

1. Confirm that the output file type matches FourCC. For details, please refer to the official website http://www.fourcc.org/codecs.php 。
simply use. Avi with videowriter:: FourCC (‘m ‘,’ J ‘,’ p ‘,’ g ‘)
I found a post on the Internet saying that FourCC was used in the old version, but it’s not used now. It’s wrong. For opencv4.3. X, FourCC is still used. When compiling, add videowriter:: FourCC (‘x’, ‘x’, ‘x’, ‘x’) to the class name.

2. If step 1 is correct but still reports an error:
linux platform: reinstall ffmpeg, then recompile opencv and install it. When compiling opencv, cmake needs to add the parameter – dwith_ FFMPEG=ON。
window platform: the output file type can be changed to. MP4. This method is lazy and does not need to install ffmpeg.

The following explains in detail why the lazy law can take effect.

2. Error code

#define VIDEO_OUTPUT_PATH "D:\\test_project\\output.avi" 

int main()
{
	Mat frame;

	frame = imread("xxx.jpg");

	VideoWriter vWriter(VIDEO_OUTPUT_PATH, CAP_OPENCV_MJPEG, 30, Size(frame.cols, frame.rows));
	//Using CAP_OPENCV_MJPEG for the above parameters is wrong haha, VideoWriter::fourcc('M', 'J', 'P', 'G') is the correct parameter
	int frameNum = 90;  
	while (frameNum) {
		vWriter << dst;
		frameNum--;
	}

	return 0;
}
	

3. Error log

[ERROR:0] global C:\build\master_winpack-build-win64-vc14\opencv\modules\videoio\src\cap.cpp (563) cv::VideoWriter::open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.5.1) C:\build\master_winpack-build-win64-vc14\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): D:\\test_project\\output.avi in function 'cv::icvExtractPattern'

4. Error analysis

The above two sentences are error messages at runtime
the first sentence is the exception received when videowriter:: open is running
the second sentence is the specific exception content:

OpenCV(4.5.1) C:\build\master_ winpack-build-win64-vc14\opencv\modules\videoio\src\cap_ images.cpp:253: error: (-5:Bad argument) CAP_ IMAGES: can’t find starting number (in the name of file): D:\test_ Project \ output.avi in function ‘CV:: icvextractpattern’
we can get the following information from the error log:

    the error log is generated by the file cap_ Images.cpp line 253 is printed. It seems that there is a problem with the file name. Specifically, it is the </ OL> printed in the CV:: icvextractpattern function

Next, let’s look at the opencv source code and find out what’s wrong with my file name

5. Opencv source code analysis

//The icvExtractPattern function is found in opencv\modules\videoio\src\cap.cpp
std::string icvExtractPattern(const std::string& filename, unsigned *offset)
{
     size_t len = filename.size(); //record the length of the filename


	。。。。。。 // a bunch of operations, don't care


        pos = filename.rfind('/'); //find the last "/" in the file name
#ifdef _WIN32
        if (pos == std::string::npos)
            pos = filename.rfind('\\'); //for window systems, find the last "\\" in the filename
#endif
        if (pos ! = std::string::npos)
            pos++;
        else
            pos = 0;

        while (pos < len && !isdigit(filename[pos])) pos++; //key point of filename error

        if (pos == len) //throw exception if position is equal to filename length

Translated with www.DeepL.com/Translator (free version)
        {
            CV_Error_(Error::StsBadArg, ("CAP_IMAGES: can't find starting number (in the name of file): %s", filename.c_str()));
        }

}

The above code should find the file type to be output from the output file name
because the key point while (POS & lt; len && amp; ! isdigit(filename[pos])) pos++; The implementation here is that if the character referred to by POS in the file name is not a number, then POS will point to the next character with + +. It seems that the reason is to find the file name with number of children
therefore, an idea occurred. Set the file type of the output file to MP4, and then the problem was solved.

#define VIDEO_ OUTPUT_ PATH “D:\test_ Project \ output. Avi ”
is changed to:
#define video_ OUTPUT_ PATH “D:\test_ project\output.mp4”

If it is helpful, you may wish to praise and pay attention to support.