python - opencv中的dnn模块使用 简单的物体识别

% 用于读取图像文件的py文件

import os

# 可供筛选的后缀名 以“元组”的方式,不然后续会查找出错
images_type = (".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff")

def list_images(base_path, contains=None):
    return list_file(base_path, validExt=images_type, contain=contains)

def list_file(base_path, validExt=None, contain=None):
    # 遍历base_path:rootDir 为根路径 dirNames为子文件夹名 fileNames为文件名
    for (rootDir, dirNames, fileNames) in os.walk(base_path):
        for file in fileNames:
            if contain is not None and file.find(contain) == -1:
                continue
            ext = file[file.rfind("."):].lower()
            if validExt is None or ext.endswith(validExt):
                imagePath = os.path.join(rootDir, file)
                yield imagePath  # 配合list使用
% main 文件
import utils_paths
import 
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当然,我可以为您介绍一下使用Python编写的OpenCV物体识别代码。下面是一个简单的示例代码: ```python import cv2 # 加载物体识别模型 net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'model.caffemodel') # 加载图像 image = cv2.imread('image.jpg') # 对图像进行预处理 blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5) # 输入图像到模型进行识别 net.setInput(blob) detections = net.forward() # 遍历识别结果 for i in range(detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > 0.5: # 设置置信度阈值 # 获取物体位置信息 box = detections[0, 0, i, 3:7] * np.array([image.shape[1], image.shape[0], image.shape[1], image.shape[0]]) (startX, startY, endX, endY) = box.astype("int") # 绘制边界框和标签 cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2) label = f'{confidence * 100:.2f}%' y = startY - 10 if startY - 10 > 10 else startY + 10 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() ``` 这段代码使用OpenCV的深度学习模块,通过加载预训练的物体识别模型进行图像识别。首先,我们需要加载模型文件(deploy.prototxt和model.caffemodel),然后读取待识别的图像。接下来,对图像进行预处理,将其转换为模型可接受的格式。然后,将预处理后的图像输入到模型进行识别,得到识别结果。最后,遍历识别结果,根据置信度阈值筛选出符合要求的物体,并在图像上绘制边界框和标签。最后,显示结果图像。 希望这段代码能够帮助到您!如果您有任何进一步的问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值