YOLOv3_Alexeyab darknet版本批量测试图片并保存

 参考了这篇:https://blog.csdn.net/dao_0123/article/details/102967244

但是上面那篇把单次输入路径的方式给覆盖了,

我这里偷了个懒,就是套了一层if else,实现可以单次或者批量输入路径进行测试,

下面这个是参考的那篇文章:

1.请在/darknet/src路径下找到detector.c文件,并打开,或请在根目录下直接执行:
2.定位到 void test_detector(char *datacfg …)这一行,将这个函数模块用以下代码完全替代:

注意3个地方:
(1)请在根路径下新建一个测试文档,本文新建了test.txt文件,里面是你需要测试图片的路径与文件名。

(2)请在根目录下新建文件夹,用来存放测试图片的结果,本文在根目录下新建文件夹,命名为result_img。读者可自己定义。
(3)请在以下代码 sprintf(b, “result_img/%d”, i); 处修改成对应自己的文件夹路径。
3.更改图片命名,在代码中添加GetFilename(),函数
————————————————
版权声明:本文为CSDN博主「小晴天明」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/dao_0123/article/details/102967244

如果自己不想改,可以直接复制下面的代码,然后替换到test_detector部分,注意上面的那个更改图片命名的是单另一个函数,放在一起方便复制。

还有一点值得注意的是,这里的test_detector的入口,是12个参数,需要看清楚,自己下的版本有几个参数,要不然改完就会报错

//更改图片命名
char *GetFilename(char *p)
{
    static char name[40] = { "" };
    char *q = strrchr(p, '/') + 1;
    strncpy(name, q, 35);//后面的35是图片名长度(不包括后缀),根据自己的需要进行修改
    return name;
}

//

void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh,
    float hier_thresh, int dont_show, int ext_output, int save_labels, char *outfile, int letter_box, int benchmark_layers)
{
    list *options = read_data_cfg(datacfg);
    char *name_list = option_find_str(options, "names", "data/names.list");
    int names_size = 0;
    char **names = get_labels_custom(name_list, &names_size); //get_labels(name_list);

    image **alphabet = load_alphabet();
    network net = parse_network_cfg_custom(cfgfile, 1, 1); // set batch=1
    if (weightfile) {
        load_weights(&net, weightfile);
    }
    net.benchmark_layers = benchmark_layers;
    fuse_conv_batchnorm(net);
    calculate_binary_weights(net);
    if (net.layers[net.n - 1].classes != names_size) {
        printf("\n Error: in the file %s number of names %d that isn't equal to classes=%d in the file %s \n",
            name_list, names_size, net.layers[net.n - 1].classes, cfgfile);
        if (net.layers[net.n - 1].classes > names_size) getchar();
    }
    srand(2222222);
    char buff[256];
    char *input = buff;
    char *json_buf = NULL;
    int json_image_id = 0;
    FILE* json_file = NULL;
    if (outfile) {
        json_file = fopen(outfile, "wb");
        if(!json_file) {
          error("fopen failed");
        }
        char *tmp = "[\n";
        fwrite(tmp, sizeof(char), strlen(tmp), json_file);
    }
    int j;
    float nms = .45;    // 0.4F
    //开始循环//
    int i;
    while (1) {
        if (filename) {
            strncpy(input, filename, 256);
            list *plist = get_paths(input);
            char **paths = (char **)list_to_array(plist);
            printf("Start Testing!\n");
            int m = plist->size;

            for (i = 0; i < m; ++i) {
                char *path = paths[i];
                image im = load_image(path, 0, 0, net.c);
                int letterbox = 0;
                image sized = resize_image(im, net.w, net.h);
                //image sized = letterbox_image(im, net.w, net.h); letterbox = 1;
                layer l = net.layers[net.n - 1];
                float *X = sized.data;
                double time = get_time_point();
                network_predict(net, X);
                printf("%s: Predicted in %lf milli-seconds.\n", input, ((double)get_time_point() - time) / 1000);
                printf("Try Very Hard:");
                printf("%s: Predicted in %lf milli-seconds.\n", path, ((double)get_time_point() - time) / 1000);
                int nboxes = 0;
                detection *dets = get_network_boxes(&net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes, letterbox);
                if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
                // draw_detections_v3(basecfg(input), im, dets, nboxes, thresh, names, alphabet, l.classes, ext_output);
                draw_detections_v3(im, dets, nboxes, thresh, names, alphabet, l.classes, ext_output);

                char b[2048];
                sprintf(b, "result_img/%s", GetFilename(path));     //***改成自己的文件夹路径
                save_image(im, b);
                printf("save %s successfully!\n", GetFilename(path));//文件命名在这个地方,可改为i
                if (save_labels)
                {
                    char labelpath[4096];
                    replace_image_to_label(input, labelpath);
                    FILE* fw = fopen(labelpath, "wb");
                    int i;
                    for (i = 0; i < nboxes; ++i) {
                        char buff[1024];
                        int class_id = -1;
                        float prob = 0;
                        for (j = 0; j < l.classes; ++j) {
                            if (dets[i].prob[j] > thresh && dets[i].prob[j] > prob) {
                                prob = dets[i].prob[j];
                                class_id = j;
                            }
                        }
                        if (class_id >= 0) {
                            sprintf(buff, "%d %2.4f %2.4f %2.4f %2.4f\n", class_id, dets[i].bbox.x, dets[i].bbox.y, dets[i].bbox.w, dets[i].bbox.h);
                            fwrite(buff, sizeof(char), strlen(buff), fw);
                        }
                    }
                    fclose(fw);
                }
                free_detections(dets, nboxes);
                free_image(im);
                free_image(sized);
            }
        
            printf("All Done!\n");
            
            exit(0);
             
          
        }
        else {
               //这里这个if可以删掉,为了更好地看到哪里改动了,这块我就没有删。
            if (filename) {
                strncpy(input, filename, 256);
                if (strlen(input) > 0)
                    if (input[strlen(input) - 1] == 0x0d) input[strlen(input) - 1] = 0;
            }
            else {
                printf("Enter Image Path: ");
                fflush(stdout);
                input = fgets(input, 256, stdin);
                if (!input) break;
                strtok(input, "\n");
            }
            //image im;
            //image sized = load_image_resize(input, net.w, net.h, net.c, &im);
            image im = load_image(input, 0, 0, net.c);
            image sized;
            if (letter_box) sized = letterbox_image(im, net.w, net.h);
            else sized = resize_image(im, net.w, net.h);
            layer l = net.layers[net.n - 1];

            //box *boxes = calloc(l.w*l.h*l.n, sizeof(box));
            //float **probs = calloc(l.w*l.h*l.n, sizeof(float*));
            //for(j = 0; j < l.w*l.h*l.n; ++j) probs[j] = (float*)xcalloc(l.classes, sizeof(float));

            float *X = sized.data;

            //time= what_time_is_it_now();
            double time = get_time_point();
            network_predict(net, X);
            //network_predict_image(&net, im); letterbox = 1;
            printf("%s: Predicted in %lf milli-seconds.\n", input, ((double)get_time_point() - time) / 1000);
            //printf("%s: Predicted in %f seconds.\n", input, (what_time_is_it_now()-time));

            int nboxes = 0;
            detection *dets = get_network_boxes(&net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes, letter_box);
            if (nms) {
                if (l.nms_kind == DEFAULT_NMS) do_nms_sort(dets, nboxes, l.classes, nms);
                else diounms_sort(dets, nboxes, l.classes, nms, l.nms_kind, l.beta_nms);
            }
            draw_detections_v3(im, dets, nboxes, thresh, names, alphabet, l.classes, ext_output);
            save_image(im, "predictions");
            if (!dont_show) {
                show_image(im, "predictions");
            }

            if (json_file) {
                if (json_buf) {
                    char *tmp = ", \n";
                    fwrite(tmp, sizeof(char), strlen(tmp), json_file);
                }
                ++json_image_id;
                json_buf = detection_to_json(dets, nboxes, l.classes, names, json_image_id, input);

                fwrite(json_buf, sizeof(char), strlen(json_buf), json_file);
                free(json_buf);
            }

            // pseudo labeling concept - fast.ai
            if (save_labels)
            {
                char labelpath[4096];
                replace_image_to_label(input, labelpath);

                FILE* fw = fopen(labelpath, "wb");
                int i;
                for (i = 0; i < nboxes; ++i) {
                    char buff[1024];
                    int class_id = -1;
                    float prob = 0;
                    for (j = 0; j < l.classes; ++j) {
                        if (dets[i].prob[j] > thresh && dets[i].prob[j] > prob) {
                            prob = dets[i].prob[j];
                            class_id = j;
                        }
                    }
                    if (class_id >= 0) {
                        sprintf(buff, "%d %2.4f %2.4f %2.4f %2.4f\n", class_id, dets[i].bbox.x, dets[i].bbox.y, dets[i].bbox.w, dets[i].bbox.h);
                        fwrite(buff, sizeof(char), strlen(buff), fw);
                    }
                }
                fclose(fw);
            }

            free_detections(dets, nboxes);
            free_image(im);
            free_image(sized);

            if (!dont_show) {
                wait_until_press_key_cv();
                destroy_all_windows_cv();
            }

            if (filename) break;
        }
    }






    //这里之前的是循环部分//
    if (json_file) {
        char *tmp = "\n]";
        fwrite(tmp, sizeof(char), strlen(tmp), json_file);
        fclose(json_file);
    }

    // free memory
    free_ptrs((void**)names, net.layers[net.n - 1].classes);
    free_list_contents_kvp(options);
    free_list(options);

    
    const int nsize = 8;
    for (j = 0; j < nsize; ++j) {
        for (i = 32; i < 127; ++i) {
            free_image(alphabet[j][i]);
        }
        free(alphabet[j]);
    }
    free(alphabet);

    free_network(net);
}

完成之后,运行:

注意那些data、cfg、weights的路径都是自己的

还有这个test.txt要放在运行darknet的下面,或者写test的绝对路径

darknet.exe detector test cfg/xxx.data  yolov3.cfg backup/yolov3-groundbox_final.weights test.txt

只能测单张的问题:

这里有个问题需要注意一下,在做test.txt的时候,需要是反斜杠/,也就是在ubuntu的写法,我在win上自己生成测试list的时候,因为用了\\,造成只能测试一张图片的问题,然后我还以为是名字必须是ImageSets,改了之后发现不是

import os

class ReName:
    def __init__(self,filePath,startNum):
        self.filePath=filePath
        self.startNum=startNum


    def RName(self):
        fileNames = os.listdir(self.filePath)
        i=0
        for name in fileNames:

            if name[-3:]=='jpg':
                print('change')
                newName=str("%06d" %(self.startNum+i))#"%06d" % int(id)
                os.rename(name,newName+'.jpg')
                i+=1
        return 'finish'

    def list_make(self):
        filePath=os.listdir(self.filePath)
        print(self.filePath)
        with open('testlist.txt','w')as f:
            for file in filePath:
                f.write(self.filePath+file+'\n')
            f.close()
        return 'listmake'




if __name__=='__main__':
    startNum=58  #这里根据自己的需要,改名字的起始数字
    filePath='./text/VOCdevkit/VOC2018/JPEGImages/'#改成自己的,注意用反斜杠
    re=ReName(filePath,startNum)
    # print(re.RName())
    print(re.list_make())

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值