怎樣用Ubuntu的Python-OpenCV識(shí)別物體

小樊
81
2024-10-11 02:35:41

要使用Ubuntu的Python-OpenCV庫(kù)來(lái)識(shí)別物體,你需要遵循以下步驟:

  1. 安裝OpenCV: 如果你還沒(méi)有安裝OpenCV,可以使用pip命令來(lái)安裝。在終端中輸入以下命令:
pip3 install opencv-python
  1. 編寫(xiě)代碼: 創(chuàng)建一個(gè)新的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()

注意:

  • 你需要下載MobileNet SSD的模型文件(MobileNetSSD_deploy.caffemodelMobileNetSSD_deploy.prototxt)并將其路徑替換為model_pathconfig_path。
  • 你還需要準(zhǔn)備一個(gè)要檢測(cè)的圖像,并將其路徑替換為image。
  1. 運(yùn)行代碼: 在終端中,導(dǎo)航到包含你的Python文件的目錄,并輸入以下命令來(lái)運(yùn)行你的代碼:
python3 object_recognition.py

你應(yīng)該會(huì)看到一個(gè)窗口,顯示帶有物體邊界框和標(biāo)簽的圖像。

0