目标:实现批量预测,保存预测结果及原图标注后的图片
安装
mkdir release
cd release
cmake ..
make -j`nproc`
批量测试
1.在darknet可执行文件目录下手动建立result_img
和result_labels
文件(用于程序时运行相关文件的保存,建立一个空文件夹即可)
result_img
:保存检测到的图像(原图标注)
result_labels
:保存与检测图像同名的txt文件,内容是预测结果(cls,xmin,ymin,wight,high)或者绝对位置(xmin,ymin,wight,high)——目前是后者,可以根据实际情况修改
0 0.240625 0.591912 0.181250 0.323529
or 177.0 76.0 308.0 289.0
2.将批量待检测的test.txt
文件保存在该文件夹
内容:所有待测图片的绝对路径
/media/scut214/data/XZY/paper/MyCFTrackers/Mosse/people/PeopleDec_1_1.jpg
/media/scut214/data/XZY/paper/MyCFTrackers/Mosse/people/PeopleDec_1_2.jpg
3.执行批量预测指令
./darknet detector test ../train_head/cfg/my_yolo.data \
../train_head/cfg/weight/yolov4-tiny_train.cfg \
../train_head/weights/yolov4-tiny_train_020000_480_288.weights \
test.txt #测试批训练程序
代码修改方法
在src/detector.c
文件的void test_detector()
上方增加以下辅助函数
//读取文件名,包括后缀
char *GetFilename(char *p)
{
static char name[40] = { "" };
char *q = strrchr(p, '/') + 1;
strncpy(name, q, 35);//后面的35是图片名长度(不包括后缀),根据自己的需要进行修改
return name;
}
//判断文件是不是图片
typedef enum {false, true} bool;
bool IsImageByTail(char *path)
{
char str[6];
strncpy(str,path+(strlen(path))-4,4);
if(strncmp(str,".jpg",4) == 0 || strncmp(str,".png",4) == 0)
return true;
else
return false;
}
在test_detector
函数中添加代码
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
//开始循环//
while (1) {
// 只添加了一个if (filename){},其他完全保留
if (filename) {
strncpy(input, filename, 256);
// 确保可以预测单张图片和批量图片
list *plist;
char **paths;
if (IsImageByTail(input)){ //预测单张图片处理方法,输入为.jpg
plist = make_list();
list_insert(plist, input);
}
else
{ //预测多张图片处理方法,输入为.txt
plist = get_paths(input);
}
paths = (char **)list_to_array(plist);
printf("Start Testing!\n");
int m = plist->size;
for (int 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 (!dont_show && IsImageByTail(input)) {
show_image(im, "predictions");
wait_until_press_key_cv();
destroy_all_windows_cv();
}
//----------------------为每张图片保存检测结果--------------------------------------
save_labels = 1;
if (save_labels)
{
printf("save labels\n");
char labelpath[4096];
//------------------保存预测结果labels到指定文件夹下---------------
char b[2048];
sprintf(b, "./result_labels/%s", GetFilename(path));
replace_image_to_label(b, labelpath);
printf("labelpath:%s\n", 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);
//---------------保存实际xmin,ymin,with,high---------------------------
sprintf(buff, "%.1f %.1f %.1f %.1f\n",
round((dets[i].bbox.x - dets[i].bbox.w / 2)*im.w),
round((dets[i].bbox.y - dets[i].bbox.h / 2)*im.h),
round(dets[i].bbox.w*im.w),
round(dets[i].bbox.h*im.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可以整体删掉
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);
int i;
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);
}