from keras.layers import Input
from efficientdet import EfficientDet
from PIL import Image
from utils.utils import BBoxUtility,letterbox_image,efficientdet_correct_boxes
from utils.anchors import get_anchors
import math
import copy
import json
import numpy as np
import os
def preprocess_input(image):
image /= 255
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
image -= mean
image /= std
return image
class mAP_EfficientDet(EfficientDet):
#---------------------------------------------------#
# 检测图片
#---------------------------------------------------#
def detect_image(self,image_id,image):
##coco的数据box是下x,y,w,h
self.confidence = 0.05 #起始的置信度
f = open("./input/detection-results/"+image_id+".txt","w")
image_shape = np.array(np.shape(image)[0:2])
crop_img = letterbox_image(image, [self.model_image_size[0],self.model_image_size[1]])
photo = np.array(crop_img,dtype = np.float32)
# 图片预处理,归一化
photo = np.reshape(preprocess_input(photo),[1,self.model_image_size[0],self.model_image_size[1],self.model_image_size[2]])
preds = self.Efficientdet.predict(photo)
# 将预测结果进行解码
results = self.bbox_util.detection_out(preds, self.prior, confidence_threshold=self.confidence)
if len(results[0])<=0:
return image
results = np.array(results)
# 筛选出其中得分高于confidence的框
det_label = results[0][:, 5]
det_conf = results[0][:, 4]
det_xmin, det_ymin, det_xmax, det_ymax = results[0][:, 0], results[0][:, 1], results[0][:, 2], results[0][:, 3]
top_indices = [i for i, conf in enumerate(det_conf) if conf >= self.confidence]
top_conf = det_conf[top_indices]
top_label_indices = det_label[top_indices].tolist()
top_xmin, top_ymin, top_xmax, top_ymax = np.expand_dims(det_xmin[top_indices],-1),np.expand_dims(det_ymin[top_indices],-1),np.expand_dims(det_xmax[top_indices],-1),np.expand_dims(det_ymax[top_indices],-1)
# 去掉灰条
boxes = efficientdet_correct_boxes(top_ymin,top_xmin,top_ymax,top_xmax,np.array([self.model_image_size[0],self.model_image_size[1]]),image_shape)
for i, c in enumerate(top_label_indices):
predicted_class = self.class_names[int(c)]
score =str(top_conf[i])
top, left, bottom, right = boxes[i]
image_result = {
'image_id': image_id, # 图片名称
'category_id': predicted_class, # 图片类别信息
'score': float(score[:6]),
'bbox':[(left+right)/2.0,(top+bottom)/2.0,right-left,bottom-top],
}
# f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom))))
results_json.append(image_result)
# f.close()
return
efficientdet = mAP_EfficientDet()
image_ids = open('VOCdevkit/VOC2007/ImageSets/Main/test.txt').read().strip().split()
if not os.path.exists("./input"):
os.makedirs("./input")
if not os.path.exists("./input/detection-results"):
os.makedirs("./input/detection-results")
if not os.path.exists("./input/images-optional"):
os.makedirs("./input/images-optional")
results_json=[]
imgIds= []
for image_id in image_ids:
image_path = "./VOCdevkit/VOC2007/JPEGImages/"+image_id+".jpg"
image = Image.open(image_path)
image.save("./input/images-optional/"+image_id+".jpg") #把对应的图片取出来
efficientdet.detect_image(image_id,image)
imgIds.append(image_id)
print(image_id," done!")
# write output
json.dump(results_json, open('test_bbox_results.json', 'w'), indent=4)
print("Conversion completed!")
print(1)