import numpy as np
import cv2
if __name__=="__main__":
	image_name = '11.jpg'
	prototxt = 'MobileNetSSD_deploy.prototxt.txt'
	model_path = 'MobileNetSSD_deploy.caffemodel'
	confidence_ta = 0.2
	# 初始化MobileNet SSD训练的类标签列表
	# 检测，然后为每个类生成一组边界框颜色
	CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
			   "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
			   "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
			   "sofa", "train", "tvmonitor"]
	COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
	# load our serialized model from disk
	print("[INFO] loading model...")
	net = cv2.dnn.readNetFromCaffe(prototxt, model_path)
	# 加载输入图像并为图像构造一个输入blob
	# 将大小调整为固定的300x300像素。
	# （注意：SSD模型的输入是300x300像素）
	image = cv2.imread(image_name)
	(h, w) = image.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843,
								 (300, 300), 127.5)
	# 通过网络传递blob并获得检测结果和
	# 预测
	print("[INFO] computing object detections...")
	net.setInput(blob)
	detections = net.forward()
	# 循环检测结果
	for i in np.arange(0, detections.shape[2]):
		# 提取与数据相关的置信度（即概率）
		# 预测
		confidence = detections[0, 0, i, 2]
		# 通过确保“置信度”来过滤掉弱检测
		# 大于最小置信度
		if confidence > confidence_ta:
			# 从`detections`中提取类标签的索引，
			# 然后计算物体边界框的 (x, y) 坐标
			idx = int(detections[0, 0, i, 1])
			box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = box.astype("int")
			# 显示预测
			label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
			print("[INFO] {}".format(label))
			cv2.rectangle(image, (startX, startY), (endX, endY),
						  COLORS[idx], 2)
			y = startY - 15 if startY - 15 > 15 else startY + 15
			cv2.putText(image, label, (startX, y),
						cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
	# show the output image
	cv2.imshow("Output", image)
	cv2.imwrite("output.jpg", image)
	cv2.waitKey(0)

