opencv-dnn

复制代码
# utils_words.txt  标签文件
import os


image_types = (".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff")


def list_images(basePath, contains=None):
    # return the set of files that are valid
    return list_files(basePath, validExts=image_types, contains=contains)


def list_files(basePath, validExts=None, contains=None):
    # loop over the directory structure
    for (rootDir, dirNames, filenames) in os.walk(basePath):
        # loop over the filenames in the current directory
        for filename in filenames:
            # if the contains string is not none and the filename does not contain
            # the supplied string, then ignore the file
            if contains is not None and filename.find(contains) == -1:
                continue

            # determine the file extension of the current file
            ext = filename[filename.rfind("."):].lower()

            # check to see if the file is an image and should be processed
            if validExts is None or ext.endswith(validExts):
                # construct the path to the image and yield it
                imagePath = os.path.join(rootDir, filename)
                yield imagePath

​
# 导入工具包
import utils_paths
import numpy as np
import cv2

# 标签文件处理
rows = open("synset_words.txt").read().strip().split("\n")
classes = [r[r.find(" ") + 1:].split(",")[0] for r in rows]

# Caffe所需配置文件
net = cv2.dnn.readNetFromCaffe("bvlc_googlenet.prototxt",
	"bvlc_googlenet.caffemodel")

# 图像路径
imagePaths = sorted(list(utils_paths.list_images("images/")))

# 图像数据预处理
image = cv2.imread(imagePaths[0])
resized = cv2.resize(image, (224, 224))
# image scalefactor size mean swapRB 
blob = cv2.dnn.blobFromImage(resized, 1, (224, 224), (104, 117, 123))
print("First Blob: {}".format(blob.shape))

# 得到预测结果
net.setInput(blob)
preds = net.forward()

# 排序,取分类可能性最大的
idx = np.argsort(preds[0])[::-1][0]
text = "Label: {}, {:.2f}%".format(classes[idx],
	preds[0][idx] * 100)
cv2.putText(image, text, (5, 25),  cv2.FONT_HERSHEY_SIMPLEX,
	0.7, (0, 0, 255), 2)

# 显示
cv2.imshow("Image", image)
cv2.waitKey(0)

# Batch数据制作
images = []

# 方法一样,数据是一个batch
for p in imagePaths[1:]:
	image = cv2.imread(p)
	image = cv2.resize(image, (224, 224))
	images.append(image)

# blobFromImages函数,注意有s
blob = cv2.dnn.blobFromImages(images, 1, (224, 224), (104, 117, 123))
print("Second Blob: {}".format(blob.shape))

# 获取预测结果
net.setInput(blob)
preds = net.forward()
for (i, p) in enumerate(imagePaths[1:]):
	image = cv2.imread(p)
	idx = np.argsort(preds[i])[::-1][0]
	text = "Label: {}, {:.2f}%".format(classes[idx],
		preds[i][idx] * 100)
	cv2.putText(image, text, (5, 25),  cv2.FONT_HERSHEY_SIMPLEX,
		0.7, (0, 0, 255), 2)
	cv2.imshow("Image", image)
	cv2.waitKey(0)

​
相关推荐
无忧智库4 分钟前
车路云一体化复杂交通博弈多智能体系统可行性研究报告(WORD)
大数据·人工智能·自动化
smith成长之旅12 分钟前
06 | Mem0 框架分析:为什么要从记忆中提取实体?——Entity Store 的设计动机与工程实现
人工智能·python
小月土星13 分钟前
不止前端!大一全栈生:深挖 JS 原理 + 落地 AI 应用全记录
人工智能
Cho1yon16 分钟前
【AI Agent 第十期:Claude Code 完全配置指南:三系统一步到位,AI编程助手轻松上手】
人工智能·ai编程
数据皮皮侠AI21 分钟前
上市公司耐心资本数据(2010-2025)
大数据·人工智能·笔记·能源·1024程序员节
陕西企来客22 分钟前
陕西 KNIT 可信知识网络构建模块对于 GEO 优化行业的影响深度调查:企来客科技技术落地真相揭示
大数据·人工智能
追光者♂23 分钟前
【测评系列5】CSDN AI数字营销实测体验官——Claude 大模型深度评测:从参数解析到实战边界
人工智能·ai·大模型·大语言模型·claude·模型幻觉·架构参数
yubo050928 分钟前
计算机视觉第七课:颜色追踪(只框红色 / 蓝色 / 绿色物体)
人工智能·opencv·计算机视觉
编码小哥30 分钟前
OpenCV去噪算法实战:中值滤波与双边滤波应用
人工智能·opencv·计算机视觉
zhangshuang-peta38 分钟前
MCP 如何重新定义 Skill:从“能力函数”变成“可治理行为”
人工智能·ai·ai agent·mcp·peta