温馨提示×

怎样用Ubuntu的Python-OpenCV识别物体

小樊
81
2024-10-11 02:35:41
栏目: 编程语言

要使用Ubuntu的Python-OpenCV库来识别物体,你需要遵循以下步骤:

  1. 安装OpenCV: 如果你还没有安装OpenCV,可以使用pip命令来安装。在终端中输入以下命令:
pip3 install opencv-python
  1. 编写代码: 创建一个新的Python文件,例如object_recognition.py,并添加以下代码:
import cv2

# 加载预先训练的模型(在这个例子中是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)

# 设置要检测的类别标签
labels = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']

# 加载要检测的图像
image = cv2.imread('path/to/your/image.jpg')

# 预处理图像
(height, width) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)

# 设置输入并进行计算
net.setInput(blob)
detections = net.forward()

# 遍历检测结果并绘制边界框
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)

# 显示结果图像
cv2.imshow("Output", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

注意:

  • 你需要下载MobileNet SSD的模型文件(MobileNetSSD_deploy.caffemodelMobileNetSSD_deploy.prototxt)并将其路径替换为model_pathconfig_path
  • 你还需要准备一个要检测的图像,并将其路径替换为image
  1. 运行代码: 在终端中,导航到包含你的Python文件的目录,并输入以下命令来运行你的代码:
python3 object_recognition.py

你应该会看到一个窗口,显示带有物体边界框和标签的图像。

0