MacOS-VScode-opencv4.3-yolov3-C++(测试成功)

MacOS-VScode-opencv4.3-yolov3-C++

MacOS-VScode-opencv4.3-yolov3-C++(测试成功)

本人10年前考了个计算机二级(c语言),再无其他开发经验,从0开始配置,将近半个月的摸索,写这篇文章也算是疏离一下自己的思路。期间借鉴了许多大神的文章,但是大神的文章多多少少都是给有那么一点基础的小神看的,次文章也算是对各位大神的致敬,由衷感谢。

在命令行测试yolov3

1、安装Homebrew
https://brew.sh/index_zh-cn
然后需要将下载源切换至国内,网上挺多的,自行搜一下吧!
*brew的安装目录在/usr/local/caller,以后用brew安装的软件都会在这个文件夹,牢记这个地址,你会经常用它。打开制定文件夹的快捷键(shift+command+G)

2、安装安装wget
brew install wget

3、安装opencv
brew install opencv
*这样安装的是最新版本的,与yolov3存在兼容问题,下面再修改即可。

4、安装darknet
git clone https://github.com/pjreddie/darknet.git

5、编译
cd darknet(进入darknet文件夹)
make(编译)

6、下载训练模型权重
wget https://pjreddie.com/media/files/yolov3.weights
tiny版(简版):wget https://pjreddie.com/media/files/yolov3-tiny.weights

7、测试
./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg
肯定会报错,下面,重点来了。

如何解决darknet与opencv4的兼容问题

1、启用opencv

找到/Users/lixiaolong/darknet/makefile文件,打开,
将opencv=0改成opencv=1;
在cpp后增加“ -std=c++11”;
将LDFLAGS+= pkg-config --libs opencv -lstdc++
COMMON+= pkg-config --cflags opencv
改成LDFLAGS+= pkg-config --libs opencv4 -lstdc++
COMMON+= pkg-config --cflags opencv4 -DOPENCV4

2、修改./src/image_opencv.cpp文件
用下面代码替换原内容,为什么?网上搜一下吧,有相关解释。

#ifdef OPENCV
 
#include "stdio.h"
#include "stdlib.h"
#include "opencv2/opencv.hpp"
#include "image.h"
 
using namespace cv;
 
extern "C" {
 
/*IplImage *image_to_ipl(image im)
{
    int x,y,c;
    IplImage *disp = cvCreateImage(cvSize(im.w,im.h), IPL_DEPTH_8U, im.c);
    int step = disp->widthStep;
    for(y = 0; y < im.h; ++y){
        for(x = 0; x < im.w; ++x){
            for(c= 0; c < im.c; ++c){
                float val = im.data[c*im.h*im.w + y*im.w + x];
                disp->imageData[y*step + x*im.c + c] = (unsigned char)(val*255);
            }
        }
    }
    return disp;
}
image ipl_to_image(IplImage* src)
{
    int h = src->height;
    int w = src->width;
    int c = src->nChannels;
    image im = make_image(w, h, c);
    unsigned char *data = (unsigned char *)src->imageData;
    int step = src->widthStep;
    int i, j, k;
    for(i = 0; i < h; ++i){
        for(k= 0; k < c; ++k){
            for(j = 0; j < w; ++j){
                im.data[k*w*h + i*w + j] = data[i*step + j*c + k]/255.;
            }
        }
    }
    return im;
}*/
 
Mat image_to_mat(image im)
{
    image copy = copy_image(im);
    constrain_image(copy);
    if(im.c == 3) rgbgr_image(copy);
 
	int x, y, c;
	Mat m = Mat(Size(im.w, im.h), CV_8UC(im.c));
	int step = m.step;
 
	for (y = 0; y < im.h; ++y) {
			for (x = 0; x < im.w; ++x) {
					for (c = 0; c < im.c; ++c) {
							float val = copy.data[c*im.h*im.w + y * im.w + x];
							m.data[y*step + x * im.c + c] = (unsigned char)(val * 255);
					}
			}
	}
 
/*    IplImage *ipl = image_to_ipl(copy);
    Mat m = cvarrToMat(ipl, true);
    cvReleaseImage(&ipl);*/
    free_image(copy);
    return m;
}
 
image mat_to_image(Mat m)
{
/*    IplImage ipl = m;
    image im = ipl_to_image(&ipl);
    rgbgr_image(im);*/
	int h = m.rows;
	int w = m.cols;
	int c = m.channels();
	image im = make_image(w, h, c);
	unsigned char *data = (unsigned char *)m.data;
	int step = m.step;
	int i, j, k;
 
	for (i = 0; i < h; ++i) {
			for (k = 0; k < c; ++k) {
					for (j = 0; j < w; ++j) {
							im.data[k*w*h + i * w + j] = data[i*step + j * c + k] / 255.;
					}
			}
	}
    if (im.c == 3) rgbgr_image(im);
	
    return im;
}
 
void *open_video_stream(const char *f, int c, int w, int h, int fps)
{
    VideoCapture *cap;
    if(f) cap = new VideoCapture(f);
    else cap = new VideoCapture(c);
    if(!cap->isOpened()) return 0;
    if(w) cap->set(CAP_PROP_FRAME_WIDTH, w);
    if(h) cap->set(CAP_PROP_FRAME_HEIGHT, w);
    if(fps) cap->set(CAP_PROP_FPS, w);
    return (void *) cap;
}
 
image get_image_from_stream(void *p)
{
    VideoCapture *cap = (VideoCapture *)p;
    Mat m;
    *cap >> m;
    if(m.empty()) return make_empty_image(0,0,0);
    return mat_to_image(m);
}
 
image load_image_cv(char *filename, int channels)
{
    int flag = -1;
    if (channels == 0) flag = -1;
    else if (channels == 1) flag = 0;
    else if (channels == 3) flag = 1;
    else {
        fprintf(stderr, "OpenCV can't force load with %d channels\n", channels);
    }
    Mat m;
    m = imread(filename, flag);
    if(!m.data){
        fprintf(stderr, "Cannot load image \"%s\"\n", filename);
        char buff[256];
        sprintf(buff, "echo %s >> bad.list", filename);
        system(buff);
        return make_image(10,10,3);
        //exit(0);
    }
    image im = mat_to_image(m);
    return im;
}
 
int show_image_cv(image im, const char* name, int ms)
{
    Mat m = image_to_mat(im);
    imshow(name, m);
    int c = waitKey(ms);
    if (c != -1) c = c%256;
    return c;
}
 
void make_window(char *name, int w, int h, int fullscreen)
{
    namedWindow(name, WINDOW_NORMAL); 
    if (fullscreen) {
        setWindowProperty(name, WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN);
    } else {
        resizeWindow(name, w, h);
        if(strcmp(name, "Demo") == 0) moveWindow(name, 0, 0);
    }
}
 
}
 
#endif

3、重新编译
cd darknet
make

4、再次测试吧,这次就能够自动展示测试结果了!(点一下图片,任意键退出)

说了这么多,下面进入正题。

在VScode中配置opencv4.3.0_3,c++开发环境

首先安装VScode
官网下载——安装插件(Chinese、c/c++、code runner)
*一次没用过的去b站找个视频先简单看一下,学习下基础操作,我这里就不写了。

以下内容来源:原文链接:https://blog.csdn.net/qq_22073849/article/details/88893201

1、配置c_cpp_properties.json
这个文件从哪打开呢?答:快捷键:ctrl+shift+P,输入 Edit configurations,选择Edit configurations(JSON)。
对照下面的代码进行修改,其中文件的地址(像这样的代码/usr/local/Cellar/opencv/4.3.0_3/include)自己去安装目录核对一下。

{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/local/opt/opencv@4/include",
                "/usr/local/Cellar/opencv/4.3.0_3/include"
            ],
            "defines": [],
            "macFrameworkPath": [],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c11",
            "cppStandard": "c++11",
            "intelliSenseMode": "clang-x64",
            "browse": {
                "path": [
                    "/usr/local/Cellar/opencv/4.3.0_3/include"
                ],
                "limitSymbolsToIncludedHeaders": true,
                "databaseFilename": ""
            }
        }
    ],
    "version": 4
}

2、配置launch.json文件
这个文件怎么打开呢?答:点击左侧边栏上那个小虫子图标在这里插入图片描述-然后点击“创建launch.json"然后点击MacOS-VScode-opencv4.3-yolov3-C++(测试成功)_第1张图片
找到了吧。
然后安装下面的代码进行修改。

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}.out",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "lldb",
            "preLaunchTask": "Buile"
        }
    ]
}

3、配置settings.json

此settings是工作区设置,在工作区进行的配置只作用于当前工作去,另外还有个用户设置,用户设置相当于全局设置,具体可以网上搜一下。
这个文件怎么找到呢?答:参照第一个文件。
然后根据如下代码修改

//settings.json
{
    "python.pythonPath": "/Users/zjx/anaconda3/bin/python3",
    "code-runner.executorMap": {
        "c": "cd $dir && make  && ./$fileNameWithoutExt && make clean",
        "cpp": "cd $dir && make  && ./$fileNameWithoutExt && make clean"
    },
    "editor.renderWhitespace": "all",
    "editor.renderLineHighlight": "all",
    "editor.formatOnSave": true,
    "code-runner.runInTerminal": true,
    "code-runner.ignoreSelection": true,
    "code-runner.enableAppInsights": false,
    "C_Cpp.updateChannel": "Insiders",
    "[makefile]": {
        "editor.insertSpaces": true
    },
    "C_Cpp.default.includePath": [
        "/usr/local/Cellar/opencv/4.3.0_3/include"
    ]
}

到此为止,跟着慢慢操作,应该没遇到什么问题吧,下面这个文件的配置可能就不好弄了。

4、配置task.json

快捷键“shift+command+B”会让你选择这个文件,切记,点击弹窗最右边那个齿轮⚙️,然后这个文件就打开了。然后根据如下代码进行修改。

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "shell",
			"label": "Build",
			"command": "g++",
			"args": [
				"-g",
				"${file}",
				"-o",
				"${fileDirname}/${fileBasenameNoExtension}.out",
				"-std=c++11",
				"-I",
				"/usr/local/Cellar/opencv/4.3.0_3/include/opencv4/opencv",
				"-I",
				"/usr/local/Cellar/opencv/4.3.0_3/include/opencv4",
				"-L",
				"/usr/local/Cellar/opencv/4.3.0_3/lib",
				"-l",
				"opencv_gapi",
				"-l",
				"opencv_stitching",
				"-l",
				"opencv_alphamat",
				"-l",
				"opencv_aruco",
				"-l",
				"opencv_bgsegm",
				"-l",
				"opencv_bioinspired",
				"-l",
				"opencv_ccalib",
				"-l",
				"opencv_dnn_objdetect",
				"-l",
				"opencv_dnn_superres",
				"-l",
				"opencv_dpm",
				"-l",
				"opencv_highgui",
				"-l",
				"opencv_face",
				"-l",
				"opencv_freetype",
				"-l",
				"opencv_fuzzy",
				"-l",
				"opencv_hfs",
				"-l",
				"opencv_img_hash",
				"-l",
				"opencv_intensity_transform",
				"-l",
				"opencv_line_descriptor",
				"-l",
				"opencv_quality",
				"-l",
				"opencv_rapid",
				"-l",
				"opencv_reg",
				"-l",
				"opencv_rgbd",
				"-l",
				"opencv_saliency",
				"-l",
				"opencv_sfm",
				"-l",
				"opencv_stereo",
				"-l",
				"opencv_structured_light",
				"-l",
				"opencv_phase_unwrapping",
				"-l",
				"opencv_superres",
				"-l",
				"opencv_optflow",
				"-l",
				"opencv_surface_matching",
				"-l",
				"opencv_tracking",
				"-l",
				"opencv_datasets",
				"-l",
				"opencv_text",
				"-l",
				"opencv_dnn",
				"-l",
				"opencv_plot",
				"-l",
				"opencv_videostab",
				"-l",
				"opencv_videoio",
				"-l",
				"opencv_xfeatures2d",
				"-l",
				"opencv_shape",
				"-l",
				"opencv_ml",
				"-l",
				"opencv_ximgproc",
				"-l",
				"opencv_video",
				"-l",
				"opencv_xobjdetect",
				"-l",
				"opencv_objdetect",
				"-l",
				"opencv_calib3d",
				"-l",
				"opencv_imgcodecs",
				"-l",
				"opencv_features2d",
				"-l",
				"opencv_flann",
				"-l",
				"opencv_xphoto",
				"-l",
				"opencv_photo",
				"-l",
				"opencv_imgproc",
				"-l",
				"opencv_core",
				"-g"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"problemMatcher": [
				"$gcc"
			]
		}
	]
}

那么大一串东西从哪来 的呢?答:在终端运行命令:pkg-config --cflags --libs opencv,如果运行结果是MacOS-VScode-opencv4.3-yolov3-C++(测试成功)_第2张图片
恭喜你,你可以省去下面的操作了,下面的这些内容折腾我一天。

如果运行结果报错(Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc’
to the PKG_CONFIG_PATH environment variable
No package ‘opencv’ found)了怎么办呢?

那是因为opencv没有配置环境变量,具体什么原因我也不清楚,跟我我操作就行了。
a、打开访达快捷键(shift+command+G) /usr/local/lib/pkgconfig
你的这个文件夹下肯定没有opencv.pc这个文件,但是你的电脑上是有这个文件了,它在(usr/local/Cellar/opencv/4.3.0_3/lib/pkgconfig/opencv4.pc )因为安装的opencv4,所以它的名字是opencv4.pc然后吧这个复制过来改名成opencv.pc即可。
b、在终端运行命令:
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

到此,你的变量就配置好了,然后在运行:pkg-config --cflags --libs opencv,把运行的结果,对照的我刚才的那段代码的格式录入就行了(不建议直接复制我那段代码,有可能会跟你的不一样)

5、配置Makefile

我才知道还要配置这个东西!
在项目文件夹新建文件,名字“Makefile”M必须大写,代码如下

TARGET = ./main

SRCS := $(wildcard ./src/*.cpp ./*.cpp)

OBJS := $(patsubst %cpp,%o,$(SRCS))

CFLG = -g -Wall -I/usr/local/Cellar/opencv@3/3.4.5/include -Iinc -I./ -std=c++11

LDFG = -Wl, $(shell pkg-config opencv --cflags --libs)

CXX = g++

$(TARGET) : $(OBJS)
	$(CXX) -o $(TARGET) $(OBJS) $(LDFG)

%.o:%.cpp
	$(CXX) $(CFLG) -c $< -o $@ 

.PHONY : clean
clean:
	-rm ./*.o


然后你就能从网上找段c++的代码测试一下啦。我提供一段

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>

using namespace cv;
using namespace std;

void drawText(Mat & image);

int main()
{
    cout << "Built with OpenCV " << CV_VERSION << endl;
    Mat image;
    VideoCapture capture;
    capture.open(0);
    if(capture.isOpened())
    {
        cout << "Capture is opened" << endl;
        for(;;)
        {
            capture >> image;
            if(image.empty())
                break;
            drawText(image);
            imshow("Sample", image);
            if(waitKey(10) >= 0)
                break;
        }
    }
    else
    {
        cout << "No capture" << endl;
        image = Mat::zeros(480, 640, CV_8UC1);
        drawText(image);
        imshow("Sample", image);
        waitKey(0);
    }
    return 0;
}

void drawText(Mat & image)
{
    putText(image, "Hello OpenCV",
            Point(20, 50),
            FONT_HERSHEY_COMPLEX, 1, // font face and scale
            Scalar(255, 255, 255), // white
            1, LINE_AA); // line thickness and type
}


此代码来源:原文链接:https://blog.csdn.net/PecoHe/article/details/97476135

你可能感兴趣的:(深度学习,机器学习,神经网络)