要使用Ubuntu的Python-OpenCV庫(kù)來(lái)識(shí)別物體,你需要遵循以下步驟:
pip3 install opencv-python
object_recognition.py
,并添加以下代碼:import cv2
# 加載預(yù)先訓(xùn)練的模型(在這個(gè)例子中是MobileNet SSD)
model_path = 'path/to/your/MobileNetSSD_deploy.caffemodel'
config_path = 'path/to/your/MobileNetSSD_deploy.prototxt'
net = cv2.dnn.readNetFromCaffe(config_path, model_path)
# 設(shè)置要檢測(cè)的類(lèi)別標(biāo)簽
labels = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
# 加載要檢測(cè)的圖像
image = cv2.imread('path/to/your/image.jpg')
# 預(yù)處理圖像
(height, width) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
# 設(shè)置輸入并進(jìn)行計(jì)算
net.setInput(blob)
detections = net.forward()
# 遍歷檢測(cè)結(jié)果并繪制邊界框
confidence_threshold = 0.7
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > confidence_threshold:
idx = int(detections[0, 0, i, 1])
label = labels[idx]
bounding_box = detections[0, 0, i, 3:7] * np.array([width, height, width, height])
(startX, startY, endX, endY) = bounding_box.astype("int")
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
y = startY - 15 if startY - 15 > 15 else startY + 15
cv2.putText(image, label, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 顯示結(jié)果圖像
cv2.imshow("Output", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:
MobileNetSSD_deploy.caffemodel
和MobileNetSSD_deploy.prototxt
)并將其路徑替換為model_path
和config_path
。image
。python3 object_recognition.py
你應(yīng)該會(huì)看到一個(gè)窗口,顯示帶有物體邊界框和標(biāo)簽的圖像。