在faster-rcnn中调用yolo检测结果进行下一步检测

1.实现yolo批量检测,和检测结果保存和检测目标单个保存

修改quick_test.py

#批量检测图片
# 创建文件夹放截图
if not os.path.exists('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/'):
    os.makedirs('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/')
else:
    shutil.rmtree('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/')
    os.mkdir('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/')

 # 创建文件夹放完整检测结果   
if not os.path.exists('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_complete/'):
    os.makedirs('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_complete/')
else:
    shutil.rmtree('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_complete/')
    os.mkdir('/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_complete/')

    
for i in f:
    # 检测存储
    print("正在检测"+i+"--------------------------------------------")
    img = Image.open("/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_data/"+i)
    img_resized = np.array(img.resize(size=(IMAGE_W, IMAGE_H)), dtype=np.float32)
    img_resized = img_resized / 255.
    with tf.Session(graph=cpu_nms_graph) as sess:
        boxes, scores = sess.run(output_tensors, feed_dict={input_tensor: np.expand_dims(img_resized, axis=0)})
        boxes, scores, labels = utils.cpu_nms(boxes, scores, num_classes, score_thresh=0.3, iou_thresh=0.5)
        image = utils.draw_boxes(img, boxes, scores, labels, classes, [IMAGE_H, IMAGE_W],"/root/anaconda3/etc/jupyter/LLD/fasterrcnn+yolo+ince/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_data/"+i ,show=True)
        # 保存图片
        print('保存图片'+i+"完整检测结果")
        # portion = image_path.split("/")
        # print(portion)
        # image.show()
        # image.show()
        image_save_path = '/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_complete/' + i.split(".")[0] + "_detectresult.jpg"
        #print('detect result save to....:' + image_save_path)
        image.save(image_save_path)
        print("检测"+i+"完毕--------------------------------------------")

  修改draw_boxes函数,在utils.py

def draw_boxes(image, boxes, scores, labels, classes, detection_size,imagpath,
               font='/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/data/font/FiraMono-Medium.otf', show=True ):
    """
    :param boxes, shape of  [num, 4]
    :param scores, shape of [num, ]
    :param labels, shape of [num, ]
    :param image,
    :param classes, the return list from the function `read_coco_names`
    """
    #print(image, boxes, scores, labels, classes, detection_size)
    if boxes is None: return image
    draw = ImageDraw.Draw(image)
    # draw settings
    font = ImageFont.truetype(font = font, size = np.floor(2e-2 * image.size[1]).astype('int32'))
    hsv_tuples = [( x / len(classes), 0.9, 1.0) for x in range(len(classes))]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))


    for i in range(len(labels)): # for each bounding box, do:
        print("共"+str(len(labels))+"个框,正在绘制第"+ str(i)+"个")
        print("box合集:")
        print(boxes)
        bbox, score, label = boxes[i], scores[i], classes[labels[i]]
        print("第"+str(i)+"个box:")
        print(bbox)


        bbox_text = "%s %.2f" %(label, score)
        text_size = draw.textsize(bbox_text, font)
        # convert_to_original_size
        detection_size, original_size = np.array(detection_size), np.array(image.size)
        ratio = original_size / detection_size
        bbox = list((bbox.reshape(2,2) * ratio).reshape(-1))

        print("第"+str(i)+"个box:")
        print(bbox)
        # 保存目标`
        cutimage = cv2.imread(imagpath)  # path是原图路径
        cropped = cutimage[int(bbox[1]): int(bbox[3]), int(bbox[0]):int(bbox[2])]
        portion = imagpath.split("/")
        cutfilename = '/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/'+ portion[10].split(".")[0] +"_cut_" + str(i) +".jpg"
        cv2.imwrite(cutfilename, cropped)  # cropname是新的路径与文件名

        draw.rectangle(bbox, outline=colors[labels[i]])#, width=3
        text_origin = bbox[:2]-np.array([0, text_size[1]])
        draw.rectangle([tuple(text_origin), tuple(text_origin+text_size)], fill=colors[labels[i]])
        # # draw bbox
        draw.text(tuple(text_origin), bbox_text, fill=(0,0,0), font=font)

    image.show() if show else None
    print("本图drawbox结束")
    return image

  

2.fasterrcnn批量检测保存

修改demo.py,增加fun()函数def fun():

        print("叶片检测开始")
        os.system("python /tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/quick_test.py")

 在main中调用fun,并且修改

   test_image_path = '/root/anaconda3/etc/jupyter/LLD/fasterrcnn+yolo+ince/tensorflow_for_YOLOv3-master-leaf/tensorflow_for_YOLOv3-master/test_result_cut/'   #检测叶片切割的图片 
    im_names = os.listdir(test_image_path)
    
    #创建文件夹
    if not os.path.exists('data/testfigs/'):
        os.makedirs('data/testfigs/')
    else:
        shutil.rmtree('data/testfigs/')
        os.mkdir('data/testfigs/')

#     im_names = ['000001.jpg', '000002.jpg', '000003.jpg','000004.jpg',
#             '000005.jpg', '000006.jpg']
    
    for im_name in im_names:
        print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'+im_name)
        print('Demo for data/demo/{}'.format(im_name))
        demo(sess, net, im_name)
        plt.show()
        plt.savefig("data/testfigs/" + im_name)

  其中,demo函数定义时候。path写的相对的,改成yolo检测结果的文件夹就可以了

posted @ 2020-05-06 17:27  cocozi  阅读(388)  评论(0编辑  收藏  举报